Merge pull request #9363 from colemanw/CRM-19560
[civicrm-core.git] / CRM / Report / Form / Mailing / Summary.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 */
33 class CRM_Report_Form_Mailing_Summary extends CRM_Report_Form {
34
35 protected $_summary = NULL;
36
37 protected $_customGroupExtends = array();
38
39 protected $_add2groupSupported = FALSE;
40
41 public $_drilldownReport = array('mailing/detail' => 'Link to Detail Report');
42
43 protected $_charts = array(
44 '' => 'Tabular',
45 'bar_3dChart' => 'Bar Chart',
46 );
47
48 public $campaignEnabled = FALSE;
49
50 /**
51 * Class constructor.
52 */
53 public function __construct() {
54 $this->_columns = array();
55
56 $this->_columns['civicrm_mailing'] = array(
57 'dao' => 'CRM_Mailing_DAO_Mailing',
58 'fields' => array(
59 'id' => array(
60 'name' => 'id',
61 'title' => ts('Mailing ID'),
62 'required' => TRUE,
63 'no_display' => TRUE,
64 ),
65 'name' => array(
66 'title' => ts('Mailing Name'),
67 'required' => TRUE,
68 ),
69 'created_date' => array(
70 'title' => ts('Date Created'),
71 ),
72 'subject' => array(
73 'title' => ts('Subject'),
74 ),
75 ),
76 'filters' => array(
77 'is_completed' => array(
78 'title' => ts('Mailing Status'),
79 'operatorType' => CRM_Report_Form::OP_SELECT,
80 'type' => CRM_Utils_Type::T_INT,
81 'options' => array(
82 0 => 'Incomplete',
83 1 => 'Complete',
84 ),
85 //'operator' => 'like',
86 'default' => 1,
87 ),
88 'mailing_name' => array(
89 'name' => 'name',
90 'title' => ts('Mailing'),
91 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
92 'type' => CRM_Utils_Type::T_STRING,
93 'options' => self::mailing_select(),
94 'operator' => 'like',
95 ),
96 ),
97 );
98
99 $this->_columns['civicrm_mailing_job'] = array(
100 'dao' => 'CRM_Mailing_DAO_MailingJob',
101 'fields' => array(
102 'start_date' => array(
103 'title' => ts('Start Date'),
104 ),
105 'end_date' => array(
106 'title' => ts('End Date'),
107 ),
108 ),
109 'filters' => array(
110 'status' => array(
111 'type' => CRM_Utils_Type::T_STRING,
112 'default' => 'Complete',
113 'no_display' => TRUE,
114 ),
115 'is_test' => array(
116 'type' => CRM_Utils_Type::T_INT,
117 'default' => 0,
118 'no_display' => TRUE,
119 ),
120 'start_date' => array(
121 'title' => ts('Start Date'),
122 'default' => 'this.year',
123 'operatorType' => CRM_Report_Form::OP_DATE,
124 'type' => CRM_Utils_Type::T_DATE,
125 ),
126 'end_date' => array(
127 'title' => ts('End Date'),
128 'default' => 'this.year',
129 'operatorType' => CRM_Report_Form::OP_DATE,
130 'type' => CRM_Utils_Type::T_DATE,
131 ),
132 ),
133 );
134
135 $this->_columns['civicrm_mailing_event_queue'] = array(
136 'dao' => 'CRM_Mailing_DAO_Mailing',
137 'fields' => array(
138 'queue_count' => array(
139 'name' => 'id',
140 'title' => ts('Intended Recipients'),
141 ),
142 ),
143 );
144
145 $this->_columns['civicrm_mailing_event_delivered'] = array(
146 'dao' => 'CRM_Mailing_DAO_Mailing',
147 'fields' => array(
148 'delivered_count' => array(
149 'name' => 'event_queue_id',
150 'title' => ts('Delivered'),
151 ),
152 'accepted_rate' => array(
153 'title' => ts('Accepted Rate'),
154 'statistics' => array(
155 'calc' => 'PERCENTAGE',
156 'top' => 'civicrm_mailing_event_delivered.delivered_count',
157 'base' => 'civicrm_mailing_event_queue.queue_count',
158 ),
159 ),
160 ),
161 );
162
163 $this->_columns['civicrm_mailing_event_bounce'] = array(
164 'dao' => 'CRM_Mailing_DAO_Mailing',
165 'fields' => array(
166 'bounce_count' => array(
167 'name' => 'event_queue_id',
168 'title' => ts('Bounce'),
169 ),
170 'bounce_rate' => array(
171 'title' => ts('Bounce Rate'),
172 'statistics' => array(
173 'calc' => 'PERCENTAGE',
174 'top' => 'civicrm_mailing_event_bounce.bounce_count',
175 'base' => 'civicrm_mailing_event_queue.queue_count',
176 ),
177 ),
178 ),
179 );
180
181 $this->_columns['civicrm_mailing_event_opened'] = array(
182 'dao' => 'CRM_Mailing_DAO_Mailing',
183 'fields' => array(
184 'unique_open_count' => array(
185 'name' => 'id',
186 'alias' => 'mailing_event_opened_civireport',
187 'dbAlias' => 'mailing_event_opened_civireport.event_queue_id',
188 'title' => ts('Unique Opens'),
189 ),
190 'unique_open_rate' => array(
191 'title' => ts('Unique Open Rate'),
192 'statistics' => array(
193 'calc' => 'PERCENTAGE',
194 'top' => 'civicrm_mailing_event_opened.unique_open_count',
195 'base' => 'civicrm_mailing_event_delivered.delivered_count',
196 ),
197 ),
198 'open_count' => array(
199 'name' => 'event_queue_id',
200 'title' => ts('Total Opens'),
201 ),
202 'open_rate' => array(
203 'title' => ts('Total Open Rate'),
204 'statistics' => array(
205 'calc' => 'PERCENTAGE',
206 'top' => 'civicrm_mailing_event_opened.open_count',
207 'base' => 'civicrm_mailing_event_delivered.delivered_count',
208 ),
209 ),
210 ),
211 );
212
213 $this->_columns['civicrm_mailing_event_trackable_url_open'] = array(
214 'dao' => 'CRM_Mailing_DAO_Mailing',
215 'fields' => array(
216 'click_count' => array(
217 'name' => 'event_queue_id',
218 'title' => ts('Clicks'),
219 ),
220 'CTR' => array(
221 'title' => ts('Click through Rate'),
222 'default' => 0,
223 'statistics' => array(
224 'calc' => 'PERCENTAGE',
225 'top' => 'civicrm_mailing_event_trackable_url_open.click_count',
226 'base' => 'civicrm_mailing_event_delivered.delivered_count',
227 ),
228 ),
229 'CTO' => array(
230 'title' => ts('Click to Open Rate'),
231 'default' => 0,
232 'statistics' => array(
233 'calc' => 'PERCENTAGE',
234 'top' => 'civicrm_mailing_event_trackable_url_open.click_count',
235 'base' => 'civicrm_mailing_event_opened.open_count',
236 ),
237 ),
238 ),
239 );
240
241 $this->_columns['civicrm_mailing_event_unsubscribe'] = array(
242 'dao' => 'CRM_Mailing_DAO_Mailing',
243 'fields' => array(
244 'unsubscribe_count' => array(
245 'name' => 'id',
246 'title' => ts('Unsubscribe'),
247 'alias' => 'mailing_event_unsubscribe_civireport',
248 'dbAlias' => 'mailing_event_unsubscribe_civireport.event_queue_id',
249 ),
250 'optout_count' => array(
251 'name' => 'id',
252 'title' => ts('Opt-outs'),
253 'alias' => 'mailing_event_optout_civireport',
254 'dbAlias' => 'mailing_event_optout_civireport.event_queue_id',
255 ),
256 ),
257 );
258 $this->_columns['civicrm_mailing_group'] = array(
259 'dao' => 'CRM_Mailing_DAO_MailingGroup',
260 'filters' => array(
261 'entity_id' => array(
262 'title' => ts('Groups Included in Mailing'),
263 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
264 'type' => CRM_Utils_Type::T_INT,
265 'options' => CRM_Core_PseudoConstant::group(),
266 ),
267 ),
268 );
269 $config = CRM_Core_Config::singleton();
270 $this->campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
271 if ($this->campaignEnabled) {
272 $this->_columns['civicrm_campaign'] = array(
273 'dao' => 'CRM_Campaign_DAO_Campaign',
274 'fields' => array(
275 'title' => array(
276 'title' => ts('Campaign Name'),
277 ),
278 ),
279 'filters' => array(
280 'title' => array(
281 'type' => CRM_Utils_Type::T_STRING,
282 ),
283 ),
284 );
285 }
286 parent::__construct();
287 }
288
289 /**
290 * @return array
291 */
292 public function mailing_select() {
293
294 $data = array();
295
296 $mailing = new CRM_Mailing_BAO_Mailing();
297 $query = "SELECT name FROM civicrm_mailing WHERE sms_provider_id IS NULL";
298 $mailing->query($query);
299
300 while ($mailing->fetch()) {
301 $data[CRM_Core_DAO::escapeString($mailing->name)] = $mailing->name;
302 }
303
304 return $data;
305 }
306
307 public function preProcess() {
308 $this->assign('chartSupported', TRUE);
309 parent::preProcess();
310 }
311
312 /**
313 * manipulate the select function to query count functions.
314 */
315 public function select() {
316
317 $count_tables = array(
318 'civicrm_mailing_event_queue',
319 'civicrm_mailing_event_delivered',
320 'civicrm_mailing_event_opened',
321 'civicrm_mailing_event_bounce',
322 'civicrm_mailing_event_trackable_url_open',
323 'civicrm_mailing_event_unsubscribe',
324 );
325
326 $select = array();
327 $this->_columnHeaders = array();
328 foreach ($this->_columns as $tableName => $table) {
329 if (array_key_exists('fields', $table)) {
330 foreach ($table['fields'] as $fieldName => $field) {
331 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
332
333 # for statistics
334 if (!empty($field['statistics'])) {
335 switch ($field['statistics']['calc']) {
336 case 'PERCENTAGE':
337 $base_table_column = explode('.', $field['statistics']['base']);
338 $top_table_column = explode('.', $field['statistics']['top']);
339
340 $select[] = "CONCAT(round(
341 count(DISTINCT {$this->_columns[$top_table_column[0]]['fields'][$top_table_column[1]]['dbAlias']}) /
342 count(DISTINCT {$this->_columns[$base_table_column[0]]['fields'][$base_table_column[1]]['dbAlias']}) * 100, 2
343 ), '%') as {$tableName}_{$fieldName}";
344 break;
345 }
346 }
347 else {
348 if (in_array($tableName, $count_tables)) {
349 $select[] = "count(DISTINCT {$field['dbAlias']}) as {$tableName}_{$fieldName}";
350 }
351 else {
352 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
353 }
354 }
355 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
356 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
357 }
358 }
359 }
360 }
361
362 $this->_selectClauses = $select;
363 $this->_select = "SELECT " . implode(', ', $select) . " ";
364 //print_r($this->_select);
365 }
366
367 public function from() {
368
369 $this->_from = "
370 FROM civicrm_mailing {$this->_aliases['civicrm_mailing']}
371 LEFT JOIN civicrm_mailing_job {$this->_aliases['civicrm_mailing_job']}
372 ON {$this->_aliases['civicrm_mailing']}.id = {$this->_aliases['civicrm_mailing_job']}.mailing_id
373 LEFT JOIN civicrm_mailing_event_queue {$this->_aliases['civicrm_mailing_event_queue']}
374 ON {$this->_aliases['civicrm_mailing_event_queue']}.job_id = {$this->_aliases['civicrm_mailing_job']}.id
375 LEFT JOIN civicrm_mailing_event_bounce {$this->_aliases['civicrm_mailing_event_bounce']}
376 ON {$this->_aliases['civicrm_mailing_event_bounce']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
377 LEFT JOIN civicrm_mailing_event_delivered {$this->_aliases['civicrm_mailing_event_delivered']}
378 ON {$this->_aliases['civicrm_mailing_event_delivered']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
379 AND {$this->_aliases['civicrm_mailing_event_bounce']}.id IS null
380 LEFT JOIN civicrm_mailing_event_opened {$this->_aliases['civicrm_mailing_event_opened']}
381 ON {$this->_aliases['civicrm_mailing_event_opened']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
382 LEFT JOIN civicrm_mailing_event_trackable_url_open {$this->_aliases['civicrm_mailing_event_trackable_url_open']}
383 ON {$this->_aliases['civicrm_mailing_event_trackable_url_open']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
384 LEFT JOIN civicrm_mailing_event_unsubscribe {$this->_aliases['civicrm_mailing_event_unsubscribe']}
385 ON {$this->_aliases['civicrm_mailing_event_unsubscribe']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id AND {$this->_aliases['civicrm_mailing_event_unsubscribe']}.org_unsubscribe = 0
386 LEFT JOIN civicrm_mailing_event_unsubscribe mailing_event_optout_civireport
387 ON mailing_event_optout_civireport.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id AND mailing_event_optout_civireport.org_unsubscribe = 1";
388
389 if ($this->isTableSelected('civicrm_mailing_group')) {
390 $this->_from .= "
391 LEFT JOIN civicrm_mailing_group {$this->_aliases['civicrm_mailing_group']}
392 ON {$this->_aliases['civicrm_mailing_group']}.mailing_id = {$this->_aliases['civicrm_mailing']}.id";
393 }
394 if ($this->campaignEnabled) {
395 $this->_from .= "
396 LEFT JOIN civicrm_campaign {$this->_aliases['civicrm_campaign']}
397 ON {$this->_aliases['civicrm_campaign']}.id = {$this->_aliases['civicrm_mailing']}.campaign_id";
398 }
399
400 // need group by and order by
401
402 //print_r($this->_from);
403 }
404
405 public function where() {
406 $clauses = array();
407 //to avoid the sms listings
408 $clauses[] = "{$this->_aliases['civicrm_mailing']}.sms_provider_id IS NULL";
409
410 foreach ($this->_columns as $tableName => $table) {
411 if (array_key_exists('filters', $table)) {
412 foreach ($table['filters'] as $fieldName => $field) {
413 $clause = NULL;
414 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
415 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
416 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
417 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
418
419 $clause = $this->dateClause($this->_aliases[$tableName] . '.' . $field['name'], $relative, $from, $to, $field['type']);
420 }
421 else {
422 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
423
424 if ($op) {
425 if ($fieldName == 'relationship_type_id') {
426 $clause = "{$this->_aliases['civicrm_relationship']}.relationship_type_id=" . $this->relationshipId;
427 }
428 else {
429 $clause = $this->whereClause($field,
430 $op,
431 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
432 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
433 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
434 );
435 }
436 }
437 }
438
439 if (!empty($clause)) {
440 $clauses[] = $clause;
441 }
442 }
443 }
444 }
445
446 if (empty($clauses)) {
447 $this->_where = "WHERE ( 1 )";
448 }
449 else {
450 $this->_where = "WHERE " . implode(' AND ', $clauses);
451 }
452
453 // if ( $this->_aclWhere ) {
454 // $this->_where .= " AND {$this->_aclWhere} ";
455 // }
456 }
457
458 public function groupBy() {
459 $groupBy = array(
460 "{$this->_aliases['civicrm_mailing']}.id",
461 );
462 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $groupBy);
463 }
464
465 public function orderBy() {
466 $this->_orderBy = " ORDER BY {$this->_aliases['civicrm_mailing_job']}.end_date DESC ";
467 }
468
469 public function postProcess() {
470
471 $this->beginPostProcess();
472
473 // get the acl clauses built before we assemble the query
474 $this->buildACLClause(CRM_Utils_Array::value('civicrm_contact', $this->_aliases));
475
476 $sql = $this->buildQuery(TRUE);
477
478 // print_r($sql);
479
480 $rows = $graphRows = array();
481 $this->buildRows($sql, $rows);
482
483 $this->formatDisplay($rows);
484 $this->doTemplateAssignment($rows);
485 $this->endPostProcess($rows);
486 }
487
488 /**
489 * @return array
490 */
491 public static function getChartCriteria() {
492 return array(
493 'count' => array(
494 'civicrm_mailing_event_delivered_delivered_count' => ts('Delivered'),
495 'civicrm_mailing_event_bounce_bounce_count' => ts('Bounce'),
496 'civicrm_mailing_event_opened_open_count' => ts('Total Opens'),
497 'civicrm_mailing_event_opened_unique_open_count' => ts('Unique Opens'),
498 'civicrm_mailing_event_trackable_url_open_click_count' => ts('Clicks'),
499 'civicrm_mailing_event_unsubscribe_unsubscribe_count' => ts('Unsubscribe'),
500 ),
501 'rate' => array(
502 'civicrm_mailing_event_delivered_accepted_rate' => ts('Accepted Rate'),
503 'civicrm_mailing_event_bounce_bounce_rate' => ts('Bounce Rate'),
504 'civicrm_mailing_event_opened_open_rate' => ts('Total Open Rate'),
505 'civicrm_mailing_event_opened_unique_open_rate' => ts('Unique Open Rate'),
506 'civicrm_mailing_event_trackable_url_open_CTR' => ts('Click through Rate'),
507 'civicrm_mailing_event_trackable_url_open_CTO' => ts('Click to Open Rate'),
508 ),
509 );
510 }
511
512 /**
513 * @param $fields
514 * @param $files
515 * @param $self
516 *
517 * @return array
518 */
519 public static function formRule($fields, $files, $self) {
520 $errors = array();
521
522 if (empty($fields['charts'])) {
523 return $errors;
524 }
525
526 $criteria = self::getChartCriteria();
527 $isError = TRUE;
528 foreach ($fields['fields'] as $fld => $isActive) {
529 if (in_array($fld, array(
530 'delivered_count',
531 'bounce_count',
532 'open_count',
533 'click_count',
534 'unsubscribe_count',
535 'accepted_rate',
536 'bounce_rate',
537 'open_rate',
538 'CTR',
539 'CTO',
540 'unique_open_rate',
541 'unique_open_count',
542 ))) {
543 $isError = FALSE;
544 }
545 }
546
547 if ($isError) {
548 $errors['_qf_default'] = ts('For Chart view, please select at least one field from %1 OR %2.', array(
549 1 => implode(', ', $criteria['count']),
550 2 => implode(', ', $criteria['rate']),
551 ));
552 }
553
554 return $errors;
555 }
556
557 /**
558 * @param $rows
559 */
560 public function buildChart(&$rows) {
561 if (empty($rows)) {
562 return;
563 }
564
565 $criteria = self::getChartCriteria();
566
567 $chartInfo = array(
568 'legend' => ts('Mail Summary'),
569 'xname' => ts('Mailing'),
570 'yname' => ts('Statistics'),
571 'xLabelAngle' => 20,
572 'tip' => array(),
573 );
574
575 $plotRate = $plotCount = TRUE;
576 foreach ($rows as $row) {
577 $chartInfo['values'][$row['civicrm_mailing_name']] = array();
578 if ($plotCount) {
579 foreach ($criteria['count'] as $criteriaName => $label) {
580 if (isset($row[$criteriaName])) {
581 $chartInfo['values'][$row['civicrm_mailing_name']][$label] = $row[$criteriaName];
582 $chartInfo['tip'][$label] = "{$label} #val#";
583 $plotRate = FALSE;
584 }
585 elseif (isset($criteria['count'][$criteriaName])) {
586 unset($criteria['count'][$criteriaName]);
587 }
588 }
589 }
590 if ($plotRate) {
591 foreach ($criteria['rate'] as $criteriaName => $label) {
592 if (isset($row[$criteria])) {
593 $chartInfo['values'][$row['civicrm_mailing_name']][$label] = $row[$criteriaName];
594 $chartInfo['tip'][$label] = "{$label} #val#";
595 $plotCount = FALSE;
596 }
597 elseif (isset($criteria['rate'][$criteriaName])) {
598 unset($criteria['rate'][$criteriaName]);
599 }
600 }
601 }
602 }
603
604 if ($plotCount) {
605 $criteria = $criteria['count'];
606 }
607 else {
608 $criteria = $criteria['rate'];
609 }
610
611 $chartInfo['criteria'] = array_values($criteria);
612
613 // dynamically set the graph size
614 $chartInfo['xSize'] = ((count($rows) * 125) + (count($rows) * count($criteria) * 40));
615
616 // build the chart.
617 CRM_Utils_OpenFlashChart::buildChart($chartInfo, $this->_params['charts']);
618 $this->assign('chartType', $this->_params['charts']);
619 }
620
621 /**
622 * Alter display of rows.
623 *
624 * Iterate through the rows retrieved via SQL and make changes for display purposes,
625 * such as rendering contacts as links.
626 *
627 * @param array $rows
628 * Rows generated by SQL, with an array for each row.
629 */
630 public function alterDisplay(&$rows) {
631 $entryFound = FALSE;
632 foreach ($rows as $rowNum => $row) {
633 // CRM-16506
634 if (array_key_exists('civicrm_mailing_name', $row) &&
635 array_key_exists('civicrm_mailing_id', $row)
636 ) {
637 $rows[$rowNum]['civicrm_mailing_name_link'] = CRM_Report_Utils_Report::getNextUrl('mailing/detail',
638 'reset=1&force=1&mailing_id_op=eq&mailing_id_value=' . $row['civicrm_mailing_id'],
639 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
640 );
641 $rows[$rowNum]['civicrm_mailing_name_hover'] = ts('View Mailing details for this mailing');
642 $entryFound = TRUE;
643 }
644 // skip looking further in rows, if first row itself doesn't
645 // have the column we need
646 if (!$entryFound) {
647 break;
648 }
649 }
650 }
651
652 }