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