CRM-18379: QA fix
[civicrm-core.git] / CRM / Logging / ReportSummary.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 * $Id$
33 */
34 class CRM_Logging_ReportSummary extends CRM_Report_Form {
35 protected $cid;
36
37 protected $_logTables = array();
38
39 protected $loggingDB;
40
41 /**
42 * The log table currently being processed.
43 *
44 * @var string
45 */
46 protected $currentLogTable;
47
48 /**
49 * Class constructor.
50 */
51 public function __construct() {
52 // don’t display the ‘Add these Contacts to Group’ button
53 $this->_add2groupSupported = FALSE;
54
55 $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
56 $this->loggingDB = $dsn['database'];
57
58 // used for redirect back to contact summary
59 $this->cid = CRM_Utils_Request::retrieve('cid', 'Integer');
60
61 $this->_logTables = array(
62 'log_civicrm_contact' => array(
63 'fk' => 'id',
64 ),
65 'log_civicrm_email' => array(
66 'fk' => 'contact_id',
67 'log_type' => 'Contact',
68 ),
69 'log_civicrm_phone' => array(
70 'fk' => 'contact_id',
71 'log_type' => 'Contact',
72 ),
73 'log_civicrm_address' => array(
74 'fk' => 'contact_id',
75 'log_type' => 'Contact',
76 ),
77 'log_civicrm_note' => array(
78 'fk' => 'entity_id',
79 'entity_table' => TRUE,
80 'bracket_info' => array(
81 'table' => 'log_civicrm_note',
82 'column' => 'subject',
83 ),
84 ),
85 'log_civicrm_note_comment' => array(
86 'fk' => 'entity_id',
87 'table_name' => 'log_civicrm_note',
88 'joins' => array(
89 'table' => 'log_civicrm_note',
90 'join' => "entity_log_civireport.entity_id = fk_table.id AND entity_log_civireport.entity_table = 'civicrm_note'",
91 ),
92 'entity_table' => TRUE,
93 'bracket_info' => array(
94 'table' => 'log_civicrm_note',
95 'column' => 'subject',
96 ),
97 ),
98 'log_civicrm_group_contact' => array(
99 'fk' => 'contact_id',
100 'bracket_info' => array(
101 'entity_column' => 'group_id',
102 'table' => 'log_civicrm_group',
103 'column' => 'title',
104 ),
105 'action_column' => 'status',
106 'log_type' => 'Group',
107 ),
108 'log_civicrm_entity_tag' => array(
109 'fk' => 'entity_id',
110 'bracket_info' => array(
111 'entity_column' => 'tag_id',
112 'table' => 'log_civicrm_tag',
113 'column' => 'name',
114 ),
115 'entity_table' => TRUE,
116 ),
117 'log_civicrm_relationship' => array(
118 'fk' => 'contact_id_a',
119 'bracket_info' => array(
120 'entity_column' => 'relationship_type_id',
121 'table' => 'log_civicrm_relationship_type',
122 'column' => 'label_a_b',
123 ),
124 ),
125 'log_civicrm_activity_contact' => array(
126 'fk' => 'contact_id',
127 'table_name' => 'log_civicrm_activity_contact',
128 'log_type' => 'Activity',
129 'field' => 'activity_id',
130
131 'bracket_info' => array(
132 'entity_column' => 'activity_type_id',
133 'options' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE),
134 'lookup_table' => 'log_civicrm_activity',
135 ),
136 ),
137 'log_civicrm_case' => array(
138 'fk' => 'contact_id',
139 'joins' => array(
140 'table' => 'log_civicrm_case_contact',
141 'join' => 'entity_log_civireport.id = fk_table.case_id',
142 ),
143 'bracket_info' => array(
144 'entity_column' => 'case_type_id',
145 'options' => CRM_Case_BAO_Case::buildOptions('case_type_id', 'search'),
146 ),
147 ),
148 );
149
150 $logging = new CRM_Logging_Schema();
151
152 // build _logTables for contact custom tables
153 $customTables = $logging->entityCustomDataLogTables('Contact');
154 foreach ($customTables as $table) {
155 $this->_logTables[$table] = array(
156 'fk' => 'entity_id',
157 'log_type' => 'Contact',
158 );
159 }
160
161 // build _logTables for address custom tables
162 $customTables = $logging->entityCustomDataLogTables('Address');
163 foreach ($customTables as $table) {
164 $this->_logTables[$table] = array(
165 // For join of fk_table with contact table.
166 'fk' => 'contact_id',
167 'joins' => array(
168 // fk_table
169 'table' => 'log_civicrm_address',
170 'join' => 'entity_log_civireport.entity_id = fk_table.id',
171 ),
172 'log_type' => 'Contact',
173 );
174 }
175
176 // Allow log tables to be extended via report hooks.
177 CRM_Report_BAO_Hook::singleton()->alterLogTables($this, $this->_logTables);
178
179 parent::__construct();
180 }
181
182 public function groupBy() {
183 $this->_groupBy = 'GROUP BY entity_log_civireport.log_conn_id, entity_log_civireport.log_user_id, EXTRACT(DAY_MICROSECOND FROM entity_log_civireport.log_date), entity_log_civireport.id';
184 }
185
186 /**
187 * Adjust query for the activity_contact table.
188 *
189 * As this is just a join table the ID we REALLY care about is the activity id.
190 *
191 * @param string $tableName
192 * @param string $tableKey
193 * @param string $fieldName
194 * @param string $field
195 *
196 * @return string
197 */
198 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
199 if ($this->currentLogTable == 'log_civicrm_activity_contact' && $fieldName == 'id') {
200 $alias = "{$tableName}_{$fieldName}";
201 $select[] = "{$tableName}.activity_id as $alias";
202 $this->_selectAliases[] = $alias;
203 return "activity_id";
204 }
205 }
206
207 public function where() {
208 // reset where clause as its called multiple times, every time insert sql is built.
209 $this->_whereClauses = array();
210
211 parent::where();
212 $this->_where .= " AND (entity_log_civireport.log_action != 'Initialization')";
213 }
214
215 public function postProcess() {
216 $this->beginPostProcess();
217 $rows = array();
218
219 $tempColumns = "id int(10)";
220 if (!empty($this->_params['fields']['log_action'])) {
221 $tempColumns .= ", log_action varchar(64)";
222 }
223 $tempColumns .= ", log_type varchar(64), log_user_id int(10), log_date timestamp";
224 if (!empty($this->_params['fields']['altered_contact'])) {
225 $tempColumns .= ", altered_contact varchar(128)";
226 }
227 $tempColumns .= ", altered_contact_id int(10), log_conn_id int(11), is_deleted tinyint(4)";
228 if (!empty($this->_params['fields']['display_name'])) {
229 $tempColumns .= ", display_name varchar(128)";
230 }
231
232 // temp table to hold all altered contact-ids
233 $sql = "CREATE TEMPORARY TABLE civicrm_temp_civireport_logsummary ( {$tempColumns} ) ENGINE=HEAP";
234 CRM_Core_DAO::executeQuery($sql);
235
236 $logTypes = CRM_Utils_Array::value('log_type_value', $this->_params);
237 unset($this->_params['log_type_value']);
238 if (empty($logTypes)) {
239 foreach (array_keys($this->_logTables) as $table) {
240 $type = $this->getLogType($table);
241 $logTypes[$type] = $type;
242 }
243 }
244
245 $logTypeTableClause = '(1)';
246 if ($logTypeTableValue = CRM_Utils_Array::value("log_type_table_value", $this->_params)) {
247 $logTypeTableClause = $this->whereClause($this->_columns['log_civicrm_entity']['filters']['log_type_table'],
248 $this->_params['log_type_table_op'], $logTypeTableValue, NULL, NULL);
249 unset($this->_params['log_type_table_value']);
250 }
251
252 foreach ($this->_logTables as $entity => $detail) {
253 if ((in_array($this->getLogType($entity), $logTypes) &&
254 CRM_Utils_Array::value('log_type_op', $this->_params) == 'in') ||
255 (!in_array($this->getLogType($entity), $logTypes) &&
256 CRM_Utils_Array::value('log_type_op', $this->_params) == 'notin')
257 ) {
258 $this->currentLogTable = $entity;
259 $sql = $this->buildQuery(FALSE);
260 $sql = str_replace("entity_log_civireport.log_type as", "'{$entity}' as", $sql);
261 $sql = "INSERT IGNORE INTO civicrm_temp_civireport_logsummary {$sql}";
262 CRM_Core_DAO::executeQuery($sql);
263 }
264 }
265
266 $this->currentLogTable = '';
267
268 // add computed log_type column so that we can do a group by after that, which will help
269 // alterDisplay() counts sync with pager counts
270 $sql = "SELECT DISTINCT log_type FROM civicrm_temp_civireport_logsummary";
271 $dao = CRM_Core_DAO::executeQuery($sql);
272 $replaceWith = array();
273 while ($dao->fetch()) {
274 $type = $this->getLogType($dao->log_type);
275 if (!array_key_exists($type, $replaceWith)) {
276 $replaceWith[$type] = array();
277 }
278 $replaceWith[$type][] = $dao->log_type;
279 }
280 foreach ($replaceWith as $type => $tables) {
281 if (!empty($tables)) {
282 $replaceWith[$type] = implode("','", $tables);
283 }
284 }
285
286 $sql = "ALTER TABLE civicrm_temp_civireport_logsummary ADD COLUMN log_civicrm_entity_log_type_label varchar(64)";
287 CRM_Core_DAO::executeQuery($sql);
288 foreach ($replaceWith as $type => $in) {
289 $sql = "UPDATE civicrm_temp_civireport_logsummary SET log_civicrm_entity_log_type_label='{$type}', log_date=log_date WHERE log_type IN('$in')";
290 CRM_Core_DAO::executeQuery($sql);
291 }
292
293 // note the group by columns are same as that used in alterDisplay as $newRows - $key
294 $this->limit();
295 $sql = "{$this->_select}
296 FROM civicrm_temp_civireport_logsummary entity_log_civireport
297 WHERE {$logTypeTableClause}
298 GROUP BY log_civicrm_entity_log_date, log_civicrm_entity_log_type_label, log_civicrm_entity_log_conn_id, log_civicrm_entity_log_user_id, log_civicrm_entity_altered_contact_id
299 ORDER BY log_civicrm_entity_log_date DESC {$this->_limit}";
300 $sql = str_replace('modified_contact_civireport.display_name', 'entity_log_civireport.altered_contact', $sql);
301 $sql = str_replace('modified_contact_civireport.id', 'entity_log_civireport.altered_contact_id', $sql);
302 $sql = str_replace(array(
303 'modified_contact_civireport.',
304 'altered_by_contact_civireport.',
305 ), 'entity_log_civireport.', $sql);
306 $this->buildRows($sql, $rows);
307
308 // format result set.
309 $this->formatDisplay($rows);
310
311 // assign variables to templates
312 $this->doTemplateAssignment($rows);
313
314 // do print / pdf / instance stuff if needed
315 $this->endPostProcess($rows);
316 }
317
318 /**
319 * Get log type.
320 *
321 * @param string $entity
322 *
323 * @return string
324 */
325 public function getLogType($entity) {
326 if (!empty($this->_logTables[$entity]['log_type'])) {
327 return $this->_logTables[$entity]['log_type'];
328 }
329 $logType = ucfirst(substr($entity, strrpos($entity, '_') + 1));
330 return $logType;
331 }
332
333 /**
334 * Get entity value.
335 *
336 * @param int $id
337 * @param $entity
338 * @param $logDate
339 *
340 * @return mixed|null|string
341 */
342 public function getEntityValue($id, $entity, $logDate) {
343 if (!empty($this->_logTables[$entity]['bracket_info'])) {
344 if (!empty($this->_logTables[$entity]['bracket_info']['entity_column'])) {
345 $logTable = !empty($this->_logTables[$entity]['table_name']) ? $this->_logTables[$entity]['table_name'] : $entity;
346 if (!empty($this->_logTables[$entity]['bracket_info']['lookup_table'])) {
347 $logTable = $this->_logTables[$entity]['bracket_info']['lookup_table'];
348 }
349 $sql = "
350 SELECT {$this->_logTables[$entity]['bracket_info']['entity_column']}
351 FROM `{$this->loggingDB}`.{$logTable}
352 WHERE log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
353
354 $entityID = CRM_Core_DAO::singleValueQuery($sql, array(
355 1 => array(
356 CRM_Utils_Date::isoToMysql($logDate),
357 'Timestamp',
358 ),
359 2 => array($id, 'Integer'),
360 ));
361 }
362 else {
363 $entityID = $id;
364 }
365
366 if ($entityID && $logDate &&
367 array_key_exists('table', $this->_logTables[$entity]['bracket_info'])
368 ) {
369 $sql = "
370 SELECT {$this->_logTables[$entity]['bracket_info']['column']}
371 FROM `{$this->loggingDB}`.{$this->_logTables[$entity]['bracket_info']['table']}
372 WHERE log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
373 return CRM_Core_DAO::singleValueQuery($sql, array(
374 1 => array(CRM_Utils_Date::isoToMysql($logDate), 'Timestamp'),
375 2 => array($entityID, 'Integer'),
376 ));
377 }
378 else {
379 if (array_key_exists('options', $this->_logTables[$entity]['bracket_info']) &&
380 $entityID
381 ) {
382 return CRM_Utils_Array::value($entityID, $this->_logTables[$entity]['bracket_info']['options']);
383 }
384 }
385 }
386 return NULL;
387 }
388
389 /**
390 * Get entity action.
391 *
392 * @param int $id
393 * @param int $connId
394 * @param $entity
395 * @param $oldAction
396 *
397 * @return null|string
398 */
399 public function getEntityAction($id, $connId, $entity, $oldAction) {
400 if (!empty($this->_logTables[$entity]['action_column'])) {
401 $sql = "select {$this->_logTables[$entity]['action_column']} from `{$this->loggingDB}`.{$entity} where id = %1 AND log_conn_id = %2";
402 $newAction = CRM_Core_DAO::singleValueQuery($sql, array(
403 1 => array($id, 'Integer'),
404 2 => array($connId, 'Integer'),
405 ));
406
407 switch ($entity) {
408 case 'log_civicrm_group_contact':
409 if ($oldAction !== 'Update') {
410 $newAction = $oldAction;
411 }
412 if ($oldAction == 'Insert') {
413 $newAction = 'Added';
414 }
415 break;
416 }
417 return $newAction;
418 }
419 return NULL;
420 }
421
422 }