--CRM-16506, fixed formatting
[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-2015 |
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-2015
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Mailing_Summary extends CRM_Report_Form {
36
37 protected $_summary = NULL;
38
39 # just a toggle we use to build the from
40 protected $_mailingidField = FALSE;
41
42 protected $_customGroupExtends = array();
43
44 protected $_add2groupSupported = FALSE;
45
46 public $_drilldownReport = array('contact/detail' => 'Link to Detail Report');
47
48 protected $_charts = array(
49 '' => 'Tabular',
50 'bar_3dChart' => 'Bar Chart',
51 );
52
53 public $campaignEnabled = FALSE;
54
55 /**
56 */
57 /**
58 */
59 public function __construct() {
60 $this->_columns = array();
61
62 $this->_columns['civicrm_mailing'] = array(
63 'dao' => 'CRM_Mailing_DAO_Mailing',
64 'fields' => array(
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' => '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' => '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' => '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' => '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' => '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' => '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 ),
251 );
252 $config = CRM_Core_Config::singleton();
253 $this->campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
254 if ($this->campaignEnabled) {
255 $this->_columns['civicrm_campaign'] = array(
256 'dao' => 'CRM_Campaign_DAO_Campaign',
257 'fields' => array(
258 'title' => array(
259 'title' => ts('Campaign Name'),
260 ),
261 ),
262 'filters' => array(
263 'title' => array(
264 'type' => CRM_Utils_Type::T_STRING,
265 ),
266 ),
267 );
268 }
269 parent::__construct();
270 }
271
272 /**
273 * @return array
274 */
275 public function mailing_select() {
276
277 $data = array();
278
279 $mailing = new CRM_Mailing_BAO_Mailing();
280 $query = "SELECT name FROM civicrm_mailing WHERE sms_provider_id IS NULL";
281 $mailing->query($query);
282
283 while ($mailing->fetch()) {
284 $data[mysql_real_escape_string($mailing->name)] = $mailing->name;
285 }
286
287 return $data;
288 }
289
290 public function preProcess() {
291 $this->assign('chartSupported', TRUE);
292 parent::preProcess();
293 }
294
295 /**
296 * manipulate the select function to query count functions.
297 */
298 public function select() {
299
300 $count_tables = array(
301 'civicrm_mailing_event_queue',
302 'civicrm_mailing_event_delivered',
303 'civicrm_mailing_event_opened',
304 'civicrm_mailing_event_bounce',
305 'civicrm_mailing_event_trackable_url_open',
306 'civicrm_mailing_event_unsubscribe',
307 );
308
309 $select = array();
310 $this->_columnHeaders = array();
311 foreach ($this->_columns as $tableName => $table) {
312 if (array_key_exists('fields', $table)) {
313 foreach ($table['fields'] as $fieldName => $field) {
314 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
315
316 # for statistics
317 if (!empty($field['statistics'])) {
318 switch ($field['statistics']['calc']) {
319 case 'PERCENTAGE':
320 $base_table_column = explode('.', $field['statistics']['base']);
321 $top_table_column = explode('.', $field['statistics']['top']);
322
323 $select[] = "CONCAT(round(
324 count(DISTINCT {$this->_columns[$top_table_column[0]]['fields'][$top_table_column[1]]['dbAlias']}) /
325 count(DISTINCT {$this->_columns[$base_table_column[0]]['fields'][$base_table_column[1]]['dbAlias']}) * 100, 2
326 ), '%') as {$tableName}_{$fieldName}";
327 break;
328 }
329 }
330 else {
331 if (in_array($tableName, $count_tables)) {
332 $select[] = "count(DISTINCT {$field['dbAlias']}) as {$tableName}_{$fieldName}";
333 }
334 else {
335 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
336 }
337 }
338 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
339 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
340 }
341 }
342 }
343 }
344
345 $this->_select = "SELECT " . implode(', ', $select) . " ";
346 //print_r($this->_select);
347 }
348
349 public function from() {
350
351 $this->_from = "
352 FROM civicrm_mailing {$this->_aliases['civicrm_mailing']}
353 LEFT JOIN civicrm_mailing_job {$this->_aliases['civicrm_mailing_job']}
354 ON {$this->_aliases['civicrm_mailing']}.id = {$this->_aliases['civicrm_mailing_job']}.mailing_id
355 LEFT JOIN civicrm_mailing_event_queue {$this->_aliases['civicrm_mailing_event_queue']}
356 ON {$this->_aliases['civicrm_mailing_event_queue']}.job_id = {$this->_aliases['civicrm_mailing_job']}.id
357 LEFT JOIN civicrm_mailing_event_bounce {$this->_aliases['civicrm_mailing_event_bounce']}
358 ON {$this->_aliases['civicrm_mailing_event_bounce']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
359 LEFT JOIN civicrm_mailing_event_delivered {$this->_aliases['civicrm_mailing_event_delivered']}
360 ON {$this->_aliases['civicrm_mailing_event_delivered']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
361 AND {$this->_aliases['civicrm_mailing_event_bounce']}.id IS null
362 LEFT JOIN civicrm_mailing_event_opened {$this->_aliases['civicrm_mailing_event_opened']}
363 ON {$this->_aliases['civicrm_mailing_event_opened']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
364 LEFT JOIN civicrm_mailing_event_trackable_url_open {$this->_aliases['civicrm_mailing_event_trackable_url_open']}
365 ON {$this->_aliases['civicrm_mailing_event_trackable_url_open']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id
366 LEFT JOIN civicrm_mailing_event_unsubscribe {$this->_aliases['civicrm_mailing_event_unsubscribe']}
367 ON {$this->_aliases['civicrm_mailing_event_unsubscribe']}.event_queue_id = {$this->_aliases['civicrm_mailing_event_queue']}.id";
368
369 if ($this->campaignEnabled) {
370 $this->_from .= "
371 LEFT JOIN civicrm_campaign {$this->_aliases['civicrm_campaign']}
372 ON {$this->_aliases['civicrm_campaign']}.id = {$this->_aliases['civicrm_mailing']}.campaign_id";
373 }
374
375 // need group by and order by
376
377 //print_r($this->_from);
378 }
379
380 public function where() {
381 $clauses = array();
382 //to avoid the sms listings
383 $clauses[] = "{$this->_aliases['civicrm_mailing']}.sms_provider_id IS NULL";
384
385 foreach ($this->_columns as $tableName => $table) {
386 if (array_key_exists('filters', $table)) {
387 foreach ($table['filters'] as $fieldName => $field) {
388 $clause = NULL;
389 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
390 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
391 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
392 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
393
394 $clause = $this->dateClause($this->_aliases[$tableName] . '.' . $field['name'], $relative, $from, $to, $field['type']);
395 }
396 else {
397 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
398
399 if ($op) {
400 if ($fieldName == 'relationship_type_id') {
401 $clause = "{$this->_aliases['civicrm_relationship']}.relationship_type_id=" . $this->relationshipId;
402 }
403 else {
404 $clause = $this->whereClause($field,
405 $op,
406 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
407 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
408 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
409 );
410 }
411 }
412 }
413
414 if (!empty($clause)) {
415 $clauses[] = $clause;
416 }
417 }
418 }
419 }
420
421 if (empty($clauses)) {
422 $this->_where = "WHERE ( 1 )";
423 }
424 else {
425 $this->_where = "WHERE " . implode(' AND ', $clauses);
426 }
427
428 // if ( $this->_aclWhere ) {
429 // $this->_where .= " AND {$this->_aclWhere} ";
430 // }
431 }
432
433 public function groupBy() {
434 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_mailing']}.id";
435 }
436
437 public function orderBy() {
438 $this->_orderBy = " ORDER BY {$this->_aliases['civicrm_mailing_job']}.end_date DESC ";
439 }
440
441 public function postProcess() {
442
443 $this->beginPostProcess();
444
445 // get the acl clauses built before we assemble the query
446 $this->buildACLClause(CRM_Utils_Array::value('civicrm_contact', $this->_aliases));
447
448 $sql = $this->buildQuery(TRUE);
449
450 // print_r($sql);
451
452 $rows = $graphRows = array();
453 $this->buildRows($sql, $rows);
454
455 $this->formatDisplay($rows);
456 $this->doTemplateAssignment($rows);
457 $this->endPostProcess($rows);
458 }
459
460 /**
461 * @return array
462 */
463 public static function getChartCriteria() {
464 return array(
465 'count' => array(
466 'civicrm_mailing_event_delivered_delivered_count' => ts('Delivered'),
467 'civicrm_mailing_event_bounce_bounce_count' => ts('Bounce'),
468 'civicrm_mailing_event_opened_open_count' => ts('Total Opens'),
469 'civicrm_mailing_event_opened_unique_open_count' => ts('Unique Opens'),
470 'civicrm_mailing_event_trackable_url_open_click_count' => ts('Clicks'),
471 'civicrm_mailing_event_unsubscribe_unsubscribe_count' => ts('Unsubscribe'),
472 ),
473 'rate' => array(
474 'civicrm_mailing_event_delivered_accepted_rate' => ts('Accepted Rate'),
475 'civicrm_mailing_event_bounce_bounce_rate' => ts('Bounce Rate'),
476 'civicrm_mailing_event_opened_open_rate' => ts('Total Open Rate'),
477 'civicrm_mailing_event_opened_unique_open_rate' => ts('Unique Open Rate'),
478 'civicrm_mailing_event_trackable_url_open_CTR' => ts('Click through Rate'),
479 'civicrm_mailing_event_trackable_url_open_CTO' => ts('Click to Open Rate'),
480 ),
481 );
482 }
483
484 /**
485 * @param $fields
486 * @param $files
487 * @param $self
488 *
489 * @return array
490 */
491 public function formRule($fields, $files, $self) {
492 $errors = array();
493
494 if (empty($fields['charts'])) {
495 return $errors;
496 }
497
498 $criteria = self::getChartCriteria();
499 $isError = TRUE;
500 foreach ($fields['fields'] as $fld => $isActive) {
501 if (in_array($fld, array(
502 'delivered_count',
503 'bounce_count',
504 'open_count',
505 'click_count',
506 'unsubscribe_count',
507 'accepted_rate',
508 'bounce_rate',
509 'open_rate',
510 'CTR',
511 'CTO',
512 'unique_open_rate',
513 'unique_open_count',
514 ))) {
515 $isError = FALSE;
516 }
517 }
518
519 if ($isError) {
520 $errors['_qf_default'] = ts('For Chart view, please select at least one field from %1 OR %2.', array(
521 1 => implode(', ', $criteria['count']),
522 2 => implode(', ', $criteria['rate']),
523 ));
524 }
525
526 return $errors;
527 }
528
529 /**
530 * @param $rows
531 */
532 public function buildChart(&$rows) {
533 if (empty($rows)) {
534 return;
535 }
536
537 $criteria = self::getChartCriteria();
538
539 $chartInfo = array(
540 'legend' => ts('Mail Summary'),
541 'xname' => ts('Mailing'),
542 'yname' => ts('Statistics'),
543 'xLabelAngle' => 20,
544 'tip' => array(),
545 );
546
547 $plotRate = $plotCount = TRUE;
548 foreach ($rows as $row) {
549 $chartInfo['values'][$row['civicrm_mailing_name']] = array();
550 if ($plotCount) {
551 foreach ($criteria['count'] as $criteria => $label) {
552 if (isset($row[$criteria])) {
553 $chartInfo['values'][$row['civicrm_mailing_name']][$label] = $row[$criteria];
554 $chartInfo['tip'][$label] = "{$label} #val#";
555 $plotRate = FALSE;
556 }
557 elseif (isset($criteria['count'][$criteria])) {
558 unset($criteria['count'][$criteria]);
559 }
560 }
561 }
562 if ($plotRate) {
563 foreach ($criteria['rate'] as $criteria => $label) {
564 if (isset($row[$criteria])) {
565 $chartInfo['values'][$row['civicrm_mailing_name']][$label] = $row[$criteria];
566 $chartInfo['tip'][$label] = "{$label} #val#";
567 $plotCount = FALSE;
568 }
569 elseif (isset($criteria['rate'][$criteria])) {
570 unset($criteria['rate'][$criteria]);
571 }
572 }
573 }
574 }
575
576 if ($plotCount) {
577 $criteria = $criteria['count'];
578 }
579 else {
580 $criteria = $criteria['rate'];
581 }
582
583 $chartInfo['criteria'] = array_values($criteria);
584
585 // dynamically set the graph size
586 $chartInfo['xSize'] = ((count($rows) * 125) + (count($rows) * count($criteria) * 40));
587
588 // build the chart.
589 CRM_Utils_OpenFlashChart::buildChart($chartInfo, $this->_params['charts']);
590 $this->assign('chartType', $this->_params['charts']);
591 }
592
593 /**
594 * Alter display of rows.
595 *
596 * Iterate through the rows retrieved via SQL and make changes for display purposes,
597 * such as rendering contacts as links.
598 *
599 * @param array $rows
600 * Rows generated by SQL, with an array for each row.
601 */
602 public function alterDisplay(&$rows) {
603 $entryFound = FALSE;
604 foreach ($rows as $rowNum => $row) {
605 // make count columns point to detail report
606 // convert display name to links
607 if (array_key_exists('civicrm_contact_display_name', $row) &&
608 array_key_exists('civicrm_contact_id', $row)
609 ) {
610 $url = CRM_Report_Utils_Report::getNextUrl('contact/detail',
611 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
612 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
613 );
614 $rows[$rowNum]['civicrm_contact_display_name_link'] = $url;
615 $rows[$rowNum]['civicrm_contact_display_name_hover'] = ts("View Contact details for this contact.");
616 $entryFound = TRUE;
617 }
618
619 // handle country
620 if (array_key_exists('civicrm_address_country_id', $row)) {
621 if ($value = $row['civicrm_address_country_id']) {
622 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
623 }
624 $entryFound = TRUE;
625 }
626 if (array_key_exists('civicrm_address_state_province_id', $row)) {
627 if ($value = $row['civicrm_address_state_province_id']) {
628 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
629 }
630 $entryFound = TRUE;
631 }
632
633 // skip looking further in rows, if first row itself doesn't
634 // have the column we need
635 if (!$entryFound) {
636 break;
637 }
638 }
639 }
640
641 }