Merge pull request #2326 from eileenmcnaughton/CRM-14069
[civicrm-core.git] / CRM / Report / Form / Mailing / Summary.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36 class CRM_Report_Form_Mailing_Summary extends CRM_Report_Form {
37
38 protected $_summary = NULL;
39
40 # just a toggle we use to build the from
41 protected $_mailingidField = FALSE;
42
43 protected $_customGroupExtends = array();
44
45 protected $_add2groupSupported = FALSE;
46
47 public $_drilldownReport = array('contact/detail' => 'Link to Detail Report');
48
49 protected $_charts = array(
50 '' => 'Tabular',
51 'bar_3dChart' => 'Bar Chart',
52 );
53
54 public $campaignEnabled = False;
55
56 /**
57 *
58 */
59 /**
60 *
61 */
62 function __construct() {
63 $this->_columns = array();
64
65 $this->_columns['civicrm_mailing'] = array(
66 'dao' => 'CRM_Mailing_DAO_Mailing',
67 'fields' => array(
68 'name' => array(
69 'title' => ts('Mailing Name'),
70 'required' => TRUE,
71 ),
72 'created_date' => array(
73 'title' => ts('Date Created'),
74 ),
75 'subject' => array(
76 'title' => ts('Subject'),
77 ),
78 ),
79 'filters' => array(
80 'is_completed' => array(
81 'title' => ts('Mailing Status'),
82 'operatorType' => CRM_Report_Form::OP_SELECT,
83 'type' => CRM_Utils_Type::T_INT,
84 'options' => array(
85 0 => 'Incomplete',
86 1 => 'Complete',
87 ),
88 //'operator' => 'like',
89 'default' => 1,
90 ),
91 'mailing_name' => array(
92 'name' => 'name',
93 'title' => ts('Mailing'),
94 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
95 'type' => CRM_Utils_Type::T_STRING,
96 'options' => self::mailing_select(),
97 'operator' => 'like',
98 ),
99 ),
100 );
101
102 $this->_columns['civicrm_mailing_job'] = array(
103 'dao' => 'CRM_Mailing_DAO_MailingJob',
104 'fields' => array(
105 'start_date' => array(
106 'title' => ts('Start Date'),
107 ),
108 'end_date' => array(
109 'title' => ts('End Date'),
110 ),
111 ),
112 'filters' => array(
113 'status' => array(
114 'type' => CRM_Utils_Type::T_STRING,
115 'default' => 'Complete',
116 'no_display' => TRUE,
117 ),
118 'is_test' => array(
119 'type' => CRM_Utils_Type::T_INT,
120 'default' => 0,
121 'no_display' => TRUE,
122 ),
123 'start_date' => array(
124 'title' => ts('Start Date'),
125 'default' => 'this.year',
126 'operatorType' => CRM_Report_Form::OP_DATE,
127 'type' => CRM_Utils_Type::T_DATE,
128 ),
129 'end_date' => array(
130 'title' => ts('End Date'),
131 'default' => 'this.year',
132 'operatorType' => CRM_Report_Form::OP_DATE,
133 'type' => CRM_Utils_Type::T_DATE,
134 ),
135 ),
136 );
137
138 $this->_columns['civicrm_mailing_event_queue'] = array(
139 'dao' => 'CRM_Mailing_DAO_Mailing',
140 'fields' => array(
141 'queue_count' => array(
142 'name' => 'id',
143 'title' => ts('Intended Recipients'),
144 ),
145 ),
146 );
147
148 $this->_columns['civicrm_mailing_event_delivered'] = array(
149 'dao' => 'CRM_Mailing_DAO_Mailing',
150 'fields' => array(
151 'delivered_count' => array(
152 'name' => 'id',
153 'title' => ts('Delivered'),
154 ),
155 'accepted_rate' => array(
156 'title' => 'Accepted Rate',
157 'statistics' => array(
158 'calc' => 'PERCENTAGE',
159 'top' => 'civicrm_mailing_event_delivered.delivered_count',
160 'base' => 'civicrm_mailing_event_queue.queue_count',
161 ),
162 ),
163 ),
164 );
165
166 $this->_columns['civicrm_mailing_event_bounce'] = array(
167 'dao' => 'CRM_Mailing_DAO_Mailing',
168 'fields' => array(
169 'bounce_count' => array(
170 'name' => 'id',
171 'title' => ts('Bounce'),
172 ),
173 'bounce_rate' => array(
174 'title' => 'Bounce Rate',
175 'statistics' => array(
176 'calc' => 'PERCENTAGE',
177 'top' => 'civicrm_mailing_event_bounce.bounce_count',
178 'base' => 'civicrm_mailing_event_queue.queue_count',
179 ),
180 ),
181 ),
182 );
183
184 $this->_columns['civicrm_mailing_event_opened'] = array(
185 'dao' => 'CRM_Mailing_DAO_Mailing',
186 'fields' => array(
187 'open_count' => array(
188 'name' => 'id',
189 'title' => ts('Opened'),
190 ),
191 'open_rate' => array(
192 'title' => 'Confirmed Open Rate',
193 'statistics' => array(
194 'calc' => 'PERCENTAGE',
195 'top' => 'civicrm_mailing_event_opened.open_count',
196 'base' => 'civicrm_mailing_event_delivered.delivered_count',
197 ),
198 ),
199 ),
200 );
201
202 $this->_columns['civicrm_mailing_event_trackable_url_open'] = array(
203 'dao' => 'CRM_Mailing_DAO_Mailing',
204 'fields' => array(
205 'click_count' => array(
206 'name' => 'id',
207 'title' => ts('Clicks'),
208 ),
209 'CTR' => array(
210 'title' => 'Click through Rate',
211 'default' => 0,
212 'statistics' => array(
213 'calc' => 'PERCENTAGE',
214 'top' => 'civicrm_mailing_event_trackable_url_open.click_count',
215 'base' => 'civicrm_mailing_event_delivered.delivered_count',
216 ),
217 ),
218 'CTO' => array(
219 'title' => 'Click to Open Rate',
220 'default' => 0,
221 'statistics' => array(
222 'calc' => 'PERCENTAGE',
223 'top' => 'civicrm_mailing_event_trackable_url_open.click_count',
224 'base' => 'civicrm_mailing_event_opened.open_count',
225 ),
226 ),
227 ),
228 );
229
230 $this->_columns['civicrm_mailing_event_unsubscribe'] = array(
231 'dao' => 'CRM_Mailing_DAO_Mailing',
232 'fields' => array(
233 'unsubscribe_count' => array(
234 'name' => 'id',
235 'title' => ts('Unsubscribe'),
236 ),
237 ),
238 );
239 $config = CRM_Core_Config::singleton();
240 $this->campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
241 if ($this->campaignEnabled) {
242 $this->_columns['civicrm_campaign'] = array(
243 'dao' => 'CRM_Campaign_DAO_Campaign',
244 'fields' => array(
245 'title' => array(
246 'title' => ts('Campaign Name'),
247 ),
248 ),
249 'filters' => array(
250 'title' => array(
251 'type' => CRM_Utils_Type::T_STRING,
252 ),
253 ),
254 );
255 }
256 parent::__construct();
257 }
258
259 /**
260 * @return array
261 */
262 function mailing_select() {
263
264 $data = array();
265
266 $mailing = new CRM_Mailing_BAO_Mailing();
267 $query = "SELECT name FROM civicrm_mailing WHERE sms_provider_id IS NULL";
268 $mailing->query($query);
269
270 while ($mailing->fetch()) {
271 $data[mysql_real_escape_string($mailing->name)] = $mailing->name;
272 }
273
274 return $data;
275 }
276
277 function preProcess() {
278 $this->assign('chartSupported', TRUE);
279 parent::preProcess();
280 }
281
282 // manipulate the select function to query count functions
283 function select() {
284
285 $count_tables = array(
286 'civicrm_mailing_event_queue',
287 'civicrm_mailing_event_delivered',
288 'civicrm_mailing_event_opened',
289 'civicrm_mailing_event_bounce',
290 'civicrm_mailing_event_trackable_url_open',
291 'civicrm_mailing_event_unsubscribe',
292 );
293
294 $select = array();
295 $this->_columnHeaders = array();
296 foreach ($this->_columns as $tableName => $table) {
297 if (array_key_exists('fields', $table)) {
298 foreach ($table['fields'] as $fieldName => $field) {
299 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
300
301 # for statistics
302 if (!empty($field['statistics'])) {
303 switch ($field['statistics']['calc']) {
304 case 'PERCENTAGE':
305 $base_table_column = explode('.', $field['statistics']['base']);
306 $top_table_column = explode('.', $field['statistics']['top']);
307
308 $select[] = "CONCAT(round(
309 count(DISTINCT {$this->_columns[$top_table_column[0]]['fields'][$top_table_column[1]]['dbAlias']}) /
310 count(DISTINCT {$this->_columns[$base_table_column[0]]['fields'][$base_table_column[1]]['dbAlias']}) * 100, 2
311 ), '%') as {$tableName}_{$fieldName}";
312 break;
313 }
314 }
315 else {
316 if (in_array($tableName, $count_tables)) {
317 $select[] = "count(DISTINCT {$field['dbAlias']}) as {$tableName}_{$fieldName}";
318 }
319 else {
320 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
321 }
322 }
323 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
324 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
325 }
326 }
327 }
328 }
329
330 $this->_select = "SELECT " . implode(', ', $select) . " ";
331 //print_r($this->_select);
332 }
333
334 function from() {
335
336 $this->_from = "
337 FROM civicrm_mailing {$this->_aliases['civicrm_mailing']}
338 LEFT JOIN civicrm_mailing_job {$this->_aliases['civicrm_mailing_job']}
339 ON {$this->_aliases['civicrm_mailing']}.id = {$this->_aliases['civicrm_mailing_job']}.mailing_id
340 LEFT JOIN civicrm_mailing_event_queue {$this->_aliases['civicrm_mailing_event_queue']}
341 ON {$this->_aliases['civicrm_mailing_event_queue']}.job_id = {$this->_aliases['civicrm_mailing_job']}.id
342 LEFT JOIN civicrm_mailing_event_bounce {$this->_aliases['civicrm_mailing_event_bounce']}
343 ON {$this->_aliases['civicrm_mailing_event_bounce']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
344 LEFT JOIN civicrm_mailing_event_delivered {$this->_aliases['civicrm_mailing_event_delivered']}
345 ON {$this->_aliases['civicrm_mailing_event_delivered']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
346 AND {$this->_aliases['civicrm_mailing_event_bounce']}.id IS null
347 LEFT JOIN civicrm_mailing_event_opened {$this->_aliases['civicrm_mailing_event_opened']}
348 ON {$this->_aliases['civicrm_mailing_event_opened']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
349 LEFT JOIN civicrm_mailing_event_trackable_url_open {$this->_aliases['civicrm_mailing_event_trackable_url_open']}
350 ON {$this->_aliases['civicrm_mailing_event_trackable_url_open']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
351 LEFT JOIN civicrm_mailing_event_unsubscribe {$this->_aliases['civicrm_mailing_event_unsubscribe']}
352 ON {$this->_aliases['civicrm_mailing_event_unsubscribe']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id";
353
354 if ($this->campaignEnabled) {
355 $this->_from .= "
356 LEFT JOIN civicrm_campaign {$this->_aliases['civicrm_campaign']}
357 ON {$this->_aliases['civicrm_campaign']}.id = {$this->_aliases['civicrm_mailing']}.campaign_id";
358 }
359
360 // need group by and order by
361
362 //print_r($this->_from);
363 }
364
365 function where() {
366 $clauses = array();
367 //to avoid the sms listings
368 $clauses[] = "{$this->_aliases['civicrm_mailing']}.sms_provider_id IS NULL";
369
370 foreach ($this->_columns as $tableName => $table) {
371 if (array_key_exists('filters', $table)) {
372 foreach ($table['filters'] as $fieldName => $field) {
373 $clause = NULL;
374 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
375 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
376 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
377 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
378
379 $clause = $this->dateClause($this->_aliases[$tableName] . '.' . $field['name'], $relative, $from, $to, $field['type']);
380 }
381 else {
382 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
383
384 if ($op) {
385 if ($fieldName == 'relationship_type_id') {
386 $clause = "{$this->_aliases['civicrm_relationship']}.relationship_type_id=" . $this->relationshipId;
387 }
388 else {
389 $clause = $this->whereClause($field,
390 $op,
391 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
392 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
393 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
394 );
395 }
396 }
397 }
398
399 if (!empty($clause)) {
400 $clauses[] = $clause;
401 }
402 }
403 }
404 }
405
406 if (empty($clauses)) {
407 $this->_where = "WHERE ( 1 )";
408 }
409 else {
410 $this->_where = "WHERE " . implode(' AND ', $clauses);
411 }
412
413 // if ( $this->_aclWhere ) {
414 // $this->_where .= " AND {$this->_aclWhere} ";
415 // }
416 }
417
418 function groupBy() {
419 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_mailing']}.id";
420 }
421
422 function orderBy() {
423 $this->_orderBy = " ORDER BY {$this->_aliases['civicrm_mailing_job']}.end_date DESC ";
424 }
425
426 function postProcess() {
427
428 $this->beginPostProcess();
429
430 // get the acl clauses built before we assemble the query
431 $this->buildACLClause(CRM_Utils_Array::value('civicrm_contact', $this->_aliases));
432
433 $sql = $this->buildQuery(TRUE);
434
435 // print_r($sql);
436
437 $rows = $graphRows = array();
438 $this->buildRows($sql, $rows);
439
440 $this->formatDisplay($rows);
441 $this->doTemplateAssignment($rows);
442 $this->endPostProcess($rows);
443 }
444
445 /**
446 * @return array
447 */
448 static function getChartCriteria() {
449 return array('count' => array('civicrm_mailing_event_delivered_delivered_count' => ts('Delivered'),
450 'civicrm_mailing_event_bounce_bounce_count' => ts('Bounce'),
451 'civicrm_mailing_event_opened_open_count' => ts('Opened'),
452 'civicrm_mailing_event_trackable_url_open_click_count' => ts('Clicks'),
453 'civicrm_mailing_event_unsubscribe_unsubscribe_count' => ts('Unsubscribe'),
454 ),
455 'rate' => array('civicrm_mailing_event_delivered_accepted_rate' => ts('Accepted Rate'),
456 'civicrm_mailing_event_bounce_bounce_rate' => ts('Bounce Rate'),
457 'civicrm_mailing_event_opened_open_rate' => ts('Confirmed Open Rate'),
458 'civicrm_mailing_event_trackable_url_open_CTR' => ts('Click through Rate'),
459 'civicrm_mailing_event_trackable_url_open_CTO' => ts('Click to Open Rate'),
460 ),
461 );
462 }
463
464 /**
465 * @param $fields
466 * @param $files
467 * @param $self
468 *
469 * @return array
470 */
471 function formRule($fields, $files, $self) {
472 $errors = array();
473
474 if (empty($fields['charts'])) {
475 return $errors;
476 }
477
478 $criterias = self::getChartCriteria();
479 $isError = TRUE;
480 foreach ($fields['fields'] as $fld => $isActive) {
481 if (in_array($fld, array(
482 'delivered_count', 'bounce_count', 'open_count', 'click_count', 'unsubscribe_count', 'accepted_rate', 'bounce_rate', 'open_rate', 'CTR', 'CTO'))) {
483 $isError = FALSE;
484 }
485 }
486
487 if ($isError) {
488 $errors['_qf_default'] = ts('For Chart view, please select at least one field from %1 OR %2.', array(1 => implode(', ', $criterias['count']), 2 => implode(', ', $criterias['rate'])));
489 }
490
491 return $errors;
492 }
493
494 /**
495 * @param $rows
496 */
497 function buildChart(&$rows) {
498 if (empty($rows)) {
499 return;
500 }
501
502 $criterias = self::getChartCriteria();
503
504 $chartInfo = array('legend' => ts('Mail Summary'),
505 'xname' => ts('Mailing'),
506 'yname' => ts('Statistics'),
507 'xLabelAngle' => 20,
508 'tip' => array(),
509 );
510
511 $plotRate = $plotCount = TRUE;
512 foreach ($rows as $row) {
513 $chartInfo['values'][$row['civicrm_mailing_name']] = array();
514 if ($plotCount) {
515 foreach ($criterias['count'] as $criteria => $label) {
516 if (isset($row[$criteria])) {
517 $chartInfo['values'][$row['civicrm_mailing_name']][$label] = $row[$criteria];
518 $chartInfo['tip'][$label] = "{$label} #val#";
519 $plotRate = FALSE;
520 }
521 elseif (isset($criterias['count'][$criteria])) {
522 unset($criterias['count'][$criteria]);
523 }
524 }
525 }
526 if ($plotRate) {
527 foreach ($criterias['rate'] as $criteria => $label) {
528 if (isset($row[$criteria])) {
529 $chartInfo['values'][$row['civicrm_mailing_name']][$label] = $row[$criteria];
530 $chartInfo['tip'][$label] = "{$label} #val#";
531 $plotCount = FALSE;
532 }
533 elseif (isset($criterias['rate'][$criteria])) {
534 unset($criterias['rate'][$criteria]);
535 }
536 }
537 }
538 }
539
540 if ($plotCount) {
541 $criterias = $criterias['count'];
542 }
543 else {
544 $criterias = $criterias['rate'];
545 }
546
547 $chartInfo['criteria'] = array_values($criterias);
548
549 // dynamically set the graph size
550 $chartInfo['xSize'] = ((count($rows) * 125) + (count($rows) * count($criterias) * 40));
551
552 // build the chart.
553 CRM_Utils_OpenFlashChart::buildChart($chartInfo, $this->_params['charts']);
554 $this->assign('chartType', $this->_params['charts']);
555 }
556
557 /**
558 * @param $rows
559 */
560 function alterDisplay(&$rows) {
561 // custom code to alter rows
562 $entryFound = FALSE;
563 foreach ($rows as $rowNum => $row) {
564 // make count columns point to detail report
565 // convert display name to links
566 if (array_key_exists('civicrm_contact_display_name', $row) &&
567 array_key_exists('civicrm_contact_id', $row)
568 ) {
569 $url = CRM_Report_Utils_Report::getNextUrl('contact/detail',
570 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
571 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
572 );
573 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
574 $rows[$rowNum]['civicrm_contact_display_name_hover'] = ts("View Contact details for this contact.");
575 $entryFound = TRUE;
576 }
577
578 // handle country
579 if (array_key_exists('civicrm_address_country_id', $row)) {
580 if ($value = $row['civicrm_address_country_id']) {
581 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
582 }
583 $entryFound = TRUE;
584 }
585 if (array_key_exists('civicrm_address_state_province_id', $row)) {
586 if ($value = $row['civicrm_address_state_province_id']) {
587 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
588 }
589 $entryFound = TRUE;
590 }
591
592
593 // skip looking further in rows, if first row itself doesn't
594 // have the column we need
595 if (!$entryFound) {
596 break;
597 }
598 }
599 }
600 }
601