Merge pull request #7965 from eileenmcnaughton/comments
[civicrm-core.git] / CRM / Mailing / BAO / Query.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 */
33 class CRM_Mailing_BAO_Query {
34
35 static $_mailingFields = NULL;
36
37 /**
38 * @return array|null
39 */
40 public static function &getFields() {
41 if (!self::$_mailingFields) {
42 self::$_mailingFields = array();
43 $_mailingFields['mailing_id'] = array(
44 'name' => 'mailing_id',
45 'title' => 'Mailing ID',
46 'where' => 'civicrm_mailing.id',
47 );
48 }
49 return self::$_mailingFields;
50 }
51
52 /**
53 * If mailings are involved, add the specific Mailing fields
54 *
55 * @param $query
56 */
57 public static function select(&$query) {
58 // if Mailing mode add mailing id
59 if ($query->_mode & CRM_Contact_BAO_Query::MODE_MAILING) {
60 $query->_select['mailing_id'] = "civicrm_mailing.id as mailing_id";
61 $query->_element['mailing_id'] = 1;
62
63 // base table is contact, so join recipients to it
64 $query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients']
65 = " INNER JOIN civicrm_mailing_recipients ON civicrm_mailing_recipients.contact_id = contact_a.id ";
66
67 $query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
68
69 // get mailing name
70 if (!empty($query->_returnProperties['mailing_name'])) {
71 $query->_select['mailing_name'] = "civicrm_mailing.name as mailing_name";
72 $query->_element['mailing_name'] = 1;
73 }
74
75 // get mailing subject
76 if (!empty($query->_returnProperties['mailing_subject'])) {
77 $query->_select['mailing_subject'] = "civicrm_mailing.subject as mailing_subject";
78 $query->_element['mailing_subject'] = 1;
79 }
80
81 // get mailing status
82 if (!empty($query->_returnProperties['mailing_job_status'])) {
83 $query->_tables['civicrm_mailing_job'] = $query->_whereTables['civicrm_mailing_job']
84 = " LEFT JOIN civicrm_mailing_job ON civicrm_mailing_job.mailing_id = civicrm_mailing.id AND civicrm_mailing_job.parent_id IS NULL AND civicrm_mailing_job.is_test != 1 ";
85 $query->_select['mailing_job_status'] = "civicrm_mailing_job.status as mailing_job_status";
86 $query->_element['mailing_job_status'] = 1;
87 }
88
89 // get email on hold
90 if (!empty($query->_returnProperties['email_on_hold'])) {
91 $query->_select['email_on_hold'] = "recipient_email.on_hold as email_on_hold";
92 $query->_element['email_on_hold'] = 1;
93 $query->_tables['recipient_email'] = $query->_whereTables['recipient_email'] = 1;
94 }
95
96 // get recipient email
97 if (!empty($query->_returnProperties['email'])) {
98 $query->_select['email'] = "recipient_email.email as email";
99 $query->_element['email'] = 1;
100 $query->_tables['recipient_email'] = $query->_whereTables['recipient_email'] = 1;
101 }
102
103 // get user opt out
104 if (!empty($query->_returnProperties['contact_opt_out'])) {
105 $query->_select['contact_opt_out'] = "contact_a.is_opt_out as contact_opt_out";
106 $query->_element['contact_opt_out'] = 1;
107 }
108
109 // mailing job end date / completed date
110 if (!empty($query->_returnProperties['mailing_job_end_date'])) {
111 $query->_tables['civicrm_mailing_job'] = $query->_whereTables['civicrm_mailing_job']
112 = " LEFT JOIN civicrm_mailing_job ON civicrm_mailing_job.mailing_id = civicrm_mailing.id AND civicrm_mailing_job.parent_id IS NULL AND civicrm_mailing_job.is_test != 1 ";
113 $query->_select['mailing_job_end_date'] = "civicrm_mailing_job.end_date as mailing_job_end_date";
114 $query->_element['mailing_job_end_date'] = 1;
115 }
116
117 if (!empty($query->_returnProperties['mailing_recipients_id'])) {
118 $query->_select['mailing_recipients_id'] = " civicrm_mailing_recipients.id as mailing_recipients_id";
119 $query->_element['mailing_recipients_id'] = 1;
120 }
121 }
122
123 if (CRM_Utils_Array::value('mailing_campaign_id', $query->_returnProperties)) {
124 $query->_select['mailing_campaign_id'] = 'civicrm_mailing.campaign_id as mailing_campaign_id';
125 $query->_element['mailing_campaign_id'] = 1;
126 $query->_tables['civicrm_campaign'] = 1;
127 }
128 }
129
130 /**
131 * @param $query
132 */
133 public static function where(&$query) {
134 $grouping = NULL;
135 foreach (array_keys($query->_params) as $id) {
136 if (empty($query->_params[$id][0])) {
137 continue;
138 }
139 if (substr($query->_params[$id][0], 0, 8) == 'mailing_') {
140 if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
141 $query->_useDistinct = TRUE;
142 }
143 $grouping = $query->_params[$id][3];
144 self::whereClauseSingle($query->_params[$id], $query);
145 }
146 }
147 }
148
149 /**
150 * @param string $name
151 * @param $mode
152 * @param $side
153 *
154 * @return null|string
155 */
156 public static function from($name, $mode, $side) {
157 $from = NULL;
158
159 switch ($name) {
160 case 'civicrm_mailing_recipients':
161 $from = " $side JOIN civicrm_mailing_recipients ON civicrm_mailing_recipients.contact_id = contact_a.id";
162 break;
163
164 case 'civicrm_mailing_event_queue':
165 // this is tightly binded so as to do a check WRT actual job recipients ('child' type jobs)
166 $from = " INNER JOIN civicrm_mailing_event_queue ON
167 civicrm_mailing_event_queue.contact_id = civicrm_mailing_recipients.contact_id
168 AND civicrm_mailing_event_queue.job_id = civicrm_mailing_job.id AND civicrm_mailing_job.job_type = 'child'";
169 break;
170
171 case 'civicrm_mailing':
172 $from = " $side JOIN civicrm_mailing ON civicrm_mailing.id = civicrm_mailing_recipients.mailing_id ";
173 break;
174
175 case 'civicrm_mailing_job':
176 $from = " $side JOIN civicrm_mailing_job ON civicrm_mailing_job.mailing_id = civicrm_mailing.id AND civicrm_mailing_job.is_test != 1 ";
177 break;
178
179 case 'civicrm_mailing_event_bounce':
180 case 'civicrm_mailing_event_delivered':
181 case 'civicrm_mailing_event_opened':
182 case 'civicrm_mailing_event_reply':
183 case 'civicrm_mailing_event_unsubscribe':
184 case 'civicrm_mailing_event_forward':
185 case 'civicrm_mailing_event_trackable_url_open':
186 $from = " $side JOIN $name ON $name.event_queue_id = civicrm_mailing_event_queue.id";
187 break;
188
189 case 'recipient_email':
190 $from = " $side JOIN civicrm_email recipient_email ON recipient_email.id = civicrm_mailing_recipients.email_id";
191 break;
192 }
193
194 return $from;
195 }
196
197 /**
198 * @param $mode
199 * @param bool $includeCustomFields
200 *
201 * @return array|null
202 */
203 public static function defaultReturnProperties(
204 $mode,
205 $includeCustomFields = TRUE
206 ) {
207
208 $properties = NULL;
209 if ($mode & CRM_Contact_BAO_Query::MODE_MAILING) {
210 $properties = array(
211 'mailing_id' => 1,
212 'mailing_campaign_id' => 1,
213 'mailing_name' => 1,
214 'sort_name' => 1,
215 'email' => 1,
216 'mailing_subject' => 1,
217 'email_on_hold' => 1,
218 'contact_opt_out' => 1,
219 'mailing_job_status' => 1,
220 'mailing_job_end_date' => 1,
221 'contact_type' => 1,
222 'contact_sub_type' => 1,
223 'mailing_recipients_id' => 1,
224 );
225 }
226 return $properties;
227 }
228
229 /**
230 * @param $values
231 * @param $query
232 */
233 public static function whereClauseSingle(&$values, &$query) {
234 list($name, $op, $value, $grouping, $wildcard) = $values;
235
236 $fields = array();
237 $fields = self::getFields();
238
239 switch ($name) {
240 case 'mailing_id':
241 $selectedMailings = array_flip($value);
242 $value = "(" . implode(',', $value) . ")";
243 $op = 'IN';
244 $query->_where[$grouping][] = "civicrm_mailing.id $op $value";
245
246 $mailings = CRM_Mailing_BAO_Mailing::getMailingsList();
247 foreach ($selectedMailings as $id => $dnc) {
248 $selectedMailings[$id] = $mailings[$id];
249 }
250 $selectedMailings = implode(' or ', $selectedMailings);
251
252 $query->_qill[$grouping][] = "Mailing Name $op \"$selectedMailings\"";
253 $query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
254 $query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
255 return;
256
257 case 'mailing_name':
258 $value = strtolower(addslashes($value));
259 if ($wildcard) {
260 $value = "%$value%";
261 $op = 'LIKE';
262 }
263 $query->_where[$grouping][] = "LOWER(civicrm_mailing.name) $op '$value'";
264 $query->_qill[$grouping][] = "Mailing Namename $op \"$value\"";
265 $query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
266 $query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
267 return;
268
269 case 'mailing_date':
270 case 'mailing_date_low':
271 case 'mailing_date_high':
272 // process to / from date
273 $query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
274 $query->_tables['civicrm_mailing_event_queue'] = $query->_whereTables['civicrm_mailing_event_queue'] = 1;
275 $query->_tables['civicrm_mailing_job'] = $query->_whereTables['civicrm_mailing_job'] = 1;
276 $query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
277 $query->dateQueryBuilder($values,
278 'civicrm_mailing_job', 'mailing_date', 'start_date', 'Mailing Delivery Date'
279 );
280 return;
281
282 case 'mailing_delivery_status':
283 $options = CRM_Mailing_PseudoConstant::yesNoOptions('delivered');
284
285 list($name, $op, $value, $grouping, $wildcard) = $values;
286 if ($value == 'Y') {
287 self::mailingEventQueryBuilder($query, $values,
288 'civicrm_mailing_event_delivered',
289 'mailing_delivery_status',
290 ts('Mailing Delivery'),
291 $options
292 );
293 }
294 elseif ($value == 'N') {
295 $options['Y'] = $options['N'];
296 $values = array($name, $op, 'Y', $grouping, $wildcard);
297 self::mailingEventQueryBuilder($query, $values,
298 'civicrm_mailing_event_bounce',
299 'mailing_delivery_status',
300 ts('Mailing Delivery'),
301 $options
302 );
303 }
304 return;
305
306 case 'mailing_bounce_types':
307 $op = 'IN';
308 $values = array($name, $op, $value, $grouping, $wildcard);
309 self::mailingEventQueryBuilder($query, $values,
310 'civicrm_mailing_event_bounce',
311 'bounce_type_id',
312 ts('Bounce type(s)'),
313 CRM_Core_PseudoConstant::get('CRM_Mailing_Event_DAO_Bounce', 'bounce_type_id', array(
314 'keyColumn' => 'id',
315 'labelColumn' => 'name',
316 ))
317 );
318 return;
319
320 case 'mailing_open_status':
321 self::mailingEventQueryBuilder($query, $values,
322 'civicrm_mailing_event_opened', 'mailing_open_status', ts('Mailing: Trackable Opens'), CRM_Mailing_PseudoConstant::yesNoOptions('open')
323 );
324 return;
325
326 case 'mailing_click_status':
327 self::mailingEventQueryBuilder($query, $values,
328 'civicrm_mailing_event_trackable_url_open', 'mailing_click_status', ts('Mailing: Trackable URL Clicks'), CRM_Mailing_PseudoConstant::yesNoOptions('click')
329 );
330 return;
331
332 case 'mailing_reply_status':
333 self::mailingEventQueryBuilder($query, $values,
334 'civicrm_mailing_event_reply', 'mailing_reply_status', ts('Mailing: Trackable Replies'), CRM_Mailing_PseudoConstant::yesNoOptions('reply')
335 );
336 return;
337
338 case 'mailing_optout':
339 $valueTitle = array(1 => ts('Opt-out Requests'));
340 // include opt-out events only
341 $query->_where[$grouping][] = "civicrm_mailing_event_unsubscribe.org_unsubscribe = 1";
342 self::mailingEventQueryBuilder($query, $values,
343 'civicrm_mailing_event_unsubscribe', 'mailing_unsubscribe',
344 ts('Mailing: '), $valueTitle
345 );
346 return;
347
348 case 'mailing_unsubscribe':
349 $valueTitle = array(1 => ts('Unsubscribe Requests'));
350 // exclude opt-out events
351 $query->_where[$grouping][] = "civicrm_mailing_event_unsubscribe.org_unsubscribe = 0";
352 self::mailingEventQueryBuilder($query, $values,
353 'civicrm_mailing_event_unsubscribe', 'mailing_unsubscribe',
354 ts('Mailing: '), $valueTitle
355 );
356 return;
357
358 case 'mailing_forward':
359 $valueTitle = array('Y' => ts('Forwards'));
360 // since its a checkbox
361 $values[2] = 'Y';
362 self::mailingEventQueryBuilder($query, $values,
363 'civicrm_mailing_event_forward', 'mailing_forward',
364 ts('Mailing: '), $valueTitle
365 );
366 return;
367
368 case 'mailing_job_status':
369 if (!empty($value)) {
370 if ($value != 'Scheduled' && $value != 'Canceled') {
371 $query->_tables['civicrm_mailing_event_queue'] = $query->_whereTables['civicrm_mailing_event_queue'] = 1;
372 }
373 $query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
374 $query->_tables['civicrm_mailing_job'] = $query->_whereTables['civicrm_mailing_job'] = 1;
375 $query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
376
377 $query->_where[$grouping][] = " civicrm_mailing_job.status = '{$value}' ";
378 $query->_qill[$grouping][] = "Mailing Job Status IS \"$value\"";
379 }
380 return;
381
382 case 'mailing_campaign_id':
383 $name = 'campaign_id';
384 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_mailing.$name", $op, $value, 'Integer');
385 list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Mailing_DAO_Mailing', $name, $value, $op);
386 $query->_qill[$grouping][] = ts('Campaign %1 %2', array(1 => $op, 2 => $value));
387 $query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
388 $query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
389 return;
390 }
391 }
392
393 /**
394 * Add all the elements shared between Mailing search and advnaced search.
395 *
396 *
397 * @param CRM_Core_Form $form
398 */
399 public static function buildSearchForm(&$form) {
400 // mailing selectors
401 $mailings = CRM_Mailing_BAO_Mailing::getMailingsList();
402
403 if (!empty($mailings)) {
404 $form->add('select', 'mailing_id', ts('Mailing Name(s)'), $mailings, FALSE,
405 array('id' => 'mailing_id', 'multiple' => 'multiple', 'class' => 'crm-select2')
406 );
407 }
408
409 CRM_Core_Form_Date::buildDateRange($form, 'mailing_date', 1, '_low', '_high', ts('From'), FALSE);
410 $form->addElement('hidden', 'mailing_date_range_error');
411 $form->addFormRule(array('CRM_Mailing_BAO_Query', 'formRule'), $form);
412
413 $mailingJobStatuses = array(
414 '' => ts('- select -'),
415 'Complete' => 'Complete',
416 'Scheduled' => 'Scheduled',
417 'Running' => 'Running',
418 'Canceled' => 'Canceled',
419 );
420 $form->addElement('select', 'mailing_job_status', ts('Mailing Job Status'), $mailingJobStatuses, FALSE);
421
422 $mailingBounceTypes = CRM_Core_PseudoConstant::get(
423 'CRM_Mailing_Event_DAO_Bounce', 'bounce_type_id',
424 array('keyColumn' => 'id', 'labelColumn' => 'name')
425 );
426 $form->add('select', 'mailing_bounce_types', ts('Bounce Types'), $mailingBounceTypes, FALSE,
427 array('id' => 'mailing_bounce_types', 'multiple' => 'multiple', 'class' => 'crm-select2')
428 );
429
430 // event filters
431 $form->addRadio('mailing_delivery_status', ts('Delivery Status'), CRM_Mailing_PseudoConstant::yesNoOptions('delivered'), array('allowClear' => TRUE));
432 $form->addRadio('mailing_open_status', ts('Trackable Opens'), CRM_Mailing_PseudoConstant::yesNoOptions('open'), array('allowClear' => TRUE));
433 $form->addRadio('mailing_click_status', ts('Trackable URLs'), CRM_Mailing_PseudoConstant::yesNoOptions('click'), array('allowClear' => TRUE));
434 $form->addRadio('mailing_reply_status', ts('Trackable Replies'), CRM_Mailing_PseudoConstant::yesNoOptions('reply'), array('allowClear' => TRUE));
435
436 $form->add('checkbox', 'mailing_unsubscribe', ts('Unsubscribe Requests'));
437 $form->add('checkbox', 'mailing_optout', ts('Opt-out Requests'));
438 $form->add('checkbox', 'mailing_forward', ts('Forwards'));
439 // Campaign select field
440 CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'mailing_campaign_id');
441
442 $form->assign('validCiviMailing', TRUE);
443 }
444
445 /**
446 * @param $row
447 * @param int $id
448 */
449 public static function searchAction(&$row, $id) {
450 }
451
452 /**
453 * @param $tables
454 */
455 public static function tableNames(&$tables) {
456 }
457
458 /**
459 * Filter query results based on which contacts do (not) have a particular mailing event in their history.
460 *
461 * @param $query
462 * @param $values
463 * @param string $tableName
464 * @param string $fieldName
465 * @param $fieldTitle
466 *
467 * @param $valueTitles
468 */
469 public static function mailingEventQueryBuilder(&$query, &$values, $tableName, $fieldName, $fieldTitle, &$valueTitles) {
470 list($name, $op, $value, $grouping, $wildcard) = $values;
471
472 if (empty($value) || $value == 'A') {
473 // don't do any filtering
474 return;
475 }
476
477 if ($value == 'Y') {
478 $query->_where[$grouping][] = $tableName . ".id is not null ";
479 }
480 elseif ($value == 'N') {
481 $query->_where[$grouping][] = $tableName . ".id is null ";
482 }
483
484 if (is_array($value)) {
485 $query->_where[$grouping][] = "$tableName.$fieldName $op (" . implode(',', $value) . ")";
486 $query->_qill[$grouping][] = "$fieldTitle $op " . implode(', ', array_intersect_key($valueTitles, array_flip($value)));
487 }
488 else {
489 $query->_qill[$grouping][] = $fieldTitle . ' - ' . $valueTitles[$value];
490 }
491
492 $query->_tables['civicrm_mailing'] = $query->_whereTables['civicrm_mailing'] = 1;
493 $query->_tables['civicrm_mailing_job'] = $query->_whereTables['civicrm_mailing_job'] = 1;
494 $query->_tables['civicrm_mailing_event_queue'] = $query->_whereTables['civicrm_mailing_event_queue'] = 1;
495 $query->_tables['civicrm_mailing_recipients'] = $query->_whereTables['civicrm_mailing_recipients'] = 1;
496 $query->_tables[$tableName] = $query->_whereTables[$tableName] = 1;
497 }
498
499 /**
500 * Check if the values in the date range are in correct chronological order.
501 *
502 * @param array $fields
503 * @param array $files
504 * @param CRM_Core_Form $form
505 *
506 * @return bool|array
507 */
508 public static function formRule($fields, $files, $form) {
509 $errors = array();
510
511 if (empty($fields['mailing_date_high']) || empty($fields['mailing_date_low'])) {
512 return TRUE;
513 }
514
515 CRM_Utils_Rule::validDateRange($fields, 'mailing_date', $errors, ts('Mailing Date'));
516
517 return empty($errors) ? TRUE : $errors;
518 }
519
520 }