Merge pull request #4892 from colemanw/INFRA-132
[civicrm-core.git] / CRM / Mailing / Form / Group.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * Choose include / exclude groups and mailings
38 *
39 */
40class CRM_Mailing_Form_Group extends CRM_Contact_Form_Task {
41
42 /**
100fef9d 43 * The mailing ID of the mailing if we are resuming a mailing
6a488035
TO
44 *
45 * @var integer
46 */
47 protected $_mailingID;
48
49 /**
100fef9d 50 * Set variables up before form is built
6a488035
TO
51 *
52 * @return void
6a488035
TO
53 */
54 public function preProcess() {
55 if (CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") {
baccef84 56 CRM_Core_Error::fatal(ts('The <a href="%1">default mailbox</a> has not been configured. You will find <a href="%2">more info in our online user and administrator guide.</a>', array(1 => CRM_Utils_System::url('civicrm/admin/mailSettings', 'reset=1'), 2 => "http://book.civicrm.org/user/advanced-configuration/email-system-configuration/")));
6a488035
TO
57 }
58
59 $this->_mailingID = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE, NULL);
60
61 // when user come from search context.
62 $this->_searchBasedMailing = CRM_Contact_Form_Search::isSearchContext($this->get('context'));
63 if ($this->_searchBasedMailing) {
64 $searchParams = $this->controller->exportValues();
65 // number of records that were selected - All or Few.
66 $this->_resultSelectOption = $searchParams['radio_ts'];
67 if (CRM_Utils_Array::value('task', $searchParams) == 20) {
68 parent::preProcess();
69 }
70 }
71
72 $session = CRM_Core_Session::singleton();
73 if ($this->_searchBasedMailing) {
74 $config = CRM_Core_Config::singleton();
75 $path = CRM_Utils_Array::value($config->userFrameworkURLVar, $_GET);
76 $qfKey = CRM_Utils_Array::value('qfKey', $_GET);
77 if ($qfKey) {
78 $session->pushUserContext(CRM_Utils_System::url($path, "qfKey=$qfKey"));
79 }
80 else {
81 $session->pushUserContext(CRM_Utils_System::url('civicrm/mailing', 'reset=1'));
82 }
83 }
84 elseif (strpos($session->readUserContext(), 'civicrm/mailing') === FALSE) {
85 // use previous context unless mailing is not schedule, CRM-4290
86 $session->pushUserContext(CRM_Utils_System::url('civicrm/mailing', 'reset=1'));
87 }
88 }
89
90 /**
c490a46a 91 * Set default values for the form.
6a488035
TO
92 * the default values are retrieved from the database
93 *
6a488035 94 *
355ba699 95 * @return void
6a488035 96 */
00be9182 97 public function setDefaultValues() {
6a488035
TO
98 $continue = CRM_Utils_Request::retrieve('continue', 'String', $this, FALSE, NULL);
99
100 $defaults = array();
9d76357a
DG
101 $defaults['dedupe_email'] = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
102 'dedupe_email_default', NULL, FALSE
103 );
6a488035
TO
104 if ($this->_mailingID) {
105 // check that the user has permission to access mailing id
106 CRM_Mailing_BAO_Mailing::checkPermission($this->_mailingID);
107
108 $mailing = new CRM_Mailing_DAO_Mailing();
109 $mailing->id = $this->_mailingID;
110 $mailing->addSelect('name', 'campaign_id');
111 $mailing->find(TRUE);
112
113 $defaults['name'] = $mailing->name;
114 if (!$continue) {
115 $defaults['name'] = ts('Copy of %1', array(1 => $mailing->name));
116 }
117 else {
118 // CRM-7590, reuse same mailing ID if we are continuing
119 $this->set('mailing_id', $this->_mailingID);
120 }
121
122 $defaults['campaign_id'] = $mailing->campaign_id;
123 $defaults['dedupe_email'] = $mailing->dedupe_email;
bac4cd35 124 $defaults['location_type_id'] = $mailing->location_type_id;
125 $defaults['email_selection_method'] = $mailing->email_selection_method;
6a488035 126
04124b30 127 $dao = new CRM_Mailing_DAO_MailingGroup();
6a488035
TO
128
129 $mailingGroups = array(
35f7561f 130 'civicrm_group' => array(),
21dfd5f5 131 'civicrm_mailing' => array(),
6a488035
TO
132 );
133 $dao->mailing_id = $this->_mailingID;
134 $dao->find();
135 while ($dao->fetch()) {
136 // account for multi-lingual
137 // CRM-11431
138 $entityTable = 'civicrm_group';
139 if (substr($dao->entity_table, 0, 15) == 'civicrm_mailing') {
140 $entityTable = 'civicrm_mailing';
141 }
142 $mailingGroups[$entityTable][$dao->group_type][] = $dao->entity_id;
143 }
144
f0bdcffd 145 $defaults['includeGroups'] = CRM_Utils_Array::value('include', $mailingGroups['civicrm_group']);
345f886d 146 $defaults['excludeGroups'] = CRM_Utils_Array::value('exclude', $mailingGroups['civicrm_group']);
6a488035
TO
147
148 if (!empty($mailingGroups['civicrm_mailing'])) {
575ff9b8 149 $defaults['includeMailings'] = CRM_Utils_Array::value('include', $mailingGroups['civicrm_mailing']);
150 $defaults['excludeMailings'] = CRM_Utils_Array::value('exclude', $mailingGroups['civicrm_mailing']);
6a488035
TO
151 }
152 }
153
154 //when the context is search hide the mailing recipients.
155 $showHide = new CRM_Core_ShowHideBlocks();
156 $showGroupSelector = TRUE;
157 if ($this->_searchBasedMailing) {
158 $showGroupSelector = FALSE;
159 $formElements = array('includeGroups', 'excludeGroups', 'includeMailings', 'excludeMailings');
160 $formValues = $this->controller->exportValues($this->_name);
161 foreach ($formElements as $element) {
162 if (!empty($formValues[$element])) {
163 $showGroupSelector = TRUE;
164 break;
165 }
166 }
167 }
168
169 if ($showGroupSelector) {
170 $showHide->addShow("id-additional");
171 $showHide->addHide("id-additional-show");
172 }
173 else {
174 $showHide->addShow("id-additional-show");
175 $showHide->addHide("id-additional");
176 }
177 $showHide->addToTemplate();
178
179 return $defaults;
180 }
181
182 /**
c490a46a 183 * Build the form object
6a488035 184 *
355ba699 185 * @return void
6a488035
TO
186 */
187 public function buildQuickForm() {
188
189 //get the context
190 $context = $this->get('context');
191 if ($this->_searchBasedMailing) {
192 $context = 'search';
193 }
194 $this->assign('context', $context);
195
196 $this->add('text', 'name', ts('Name Your Mailing'),
197 CRM_Core_DAO::getAttribute('CRM_Mailing_DAO_Mailing', 'name'),
198 TRUE
199 );
200
201 $hiddenMailingGroup = NULL;
202 $campaignId = NULL;
203
204 //CRM-7362 --add campaigns.
205 if ($this->_mailingID) {
206 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_Mailing', $this->_mailingID, 'campaign_id');
207 $hiddenMailingGroup = CRM_Mailing_BAO_Mailing::hiddenMailingGroup($this->_mailingID);
208 }
209 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
210
211 //dedupe on email option
212 $this->addElement('checkbox', 'dedupe_email', ts('Remove duplicate emails?'));
213
bac4cd35 214 // location types
215 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('id' => 'display_name'));
f008d1d2 216 $this->addElement('select', 'location_type_id', ts("Location Type"), array('' => ts('Automatic')) + $locationTypes);
bac4cd35 217
218 $methods = CRM_Core_SelectValues::emailSelectMethods();
219 $this->addElement('select', 'email_selection_method', ts("Email Selection Method"), $methods);
220
6a488035 221 //get the mailing groups.
24431f7b 222 $groups = CRM_Core_PseudoConstant::nestedGroup('Mailing');
6a488035
TO
223 if ($hiddenMailingGroup) {
224 $groups[$hiddenMailingGroup] =
225 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $hiddenMailingGroup, 'title');
226 }
227
228 $mailings = CRM_Mailing_PseudoConstant::completed();
229 if (!$mailings) {
230 $mailings = array();
231 }
232
233 // run the groups through a hook so users can trim it if needed
234 CRM_Utils_Hook::mailingGroups($this, $groups, $mailings);
235
236 //when the context is search add base group's.
237 if ($this->_searchBasedMailing) {
238 //get the static groups
239 $staticGroups = CRM_Core_PseudoConstant::staticGroup(FALSE, 'Mailing');
240 $this->add('select', 'baseGroup',
241 ts('Unsubscription Group'),
242 array(
24431f7b 243 '' => ts('- select -')) + CRM_Contact_BAO_Group::getGroupsHierarchy($staticGroups, NULL, '&nbsp;&nbsp;', TRUE),
3e8871b9
CW
244 TRUE,
245 array('class' => 'crm-select2 huge')
6a488035
TO
246 );
247 }
248
1e5616ba
CW
249 $select2style = array(
250 'multiple' => TRUE,
251 'style' => 'width: 100%; max-width: 60em;',
252 'class' => 'crm-select2',
253 'placeholder' => ts('- select -'),
6a488035
TO
254 );
255
1e5616ba
CW
256 $this->add('select', 'includeGroups',
257 ts('Include Group(s)'),
6a488035 258 $groups,
1e5616ba
CW
259 !$this->_searchBasedMailing,
260 $select2style
6a488035
TO
261 );
262
1e5616ba
CW
263 $this->add('select', 'excludeGroups',
264 ts('Exclude Group(s)'),
265 $groups,
266 FALSE,
267 $select2style
268 );
6a488035 269
1e5616ba 270 $this->add('select', 'includeMailings',
6a488035
TO
271 ts('INCLUDE Recipients of These Mailing(s)') . ' ',
272 $mailings,
1e5616ba
CW
273 FALSE,
274 $select2style
6a488035 275 );
1e5616ba 276 $this->add('select', 'excludeMailings',
6a488035
TO
277 ts('EXCLUDE Recipients of These Mailing(s)') . ' ',
278 $mailings,
1e5616ba
CW
279 FALSE,
280 $select2style
6a488035
TO
281 );
282
6a488035
TO
283 $this->addFormRule(array('CRM_Mailing_Form_Group', 'formRule'));
284
285 $buttons = array(
35f7561f 286 array(
f212d37d
CW
287 'type' => 'next',
288 'name' => ts('Next'),
6a488035
TO
289 'spacing' => '&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;',
290 'isDefault' => TRUE,
291 ),
292 array(
293 'type' => 'submit',
294 'name' => ts('Save & Continue Later'),
295 ),
296 array(
297 'type' => 'cancel',
298 'name' => ts('Cancel'),
299 ),
300 );
301
302 $this->addButtons($buttons);
303
304 $this->assign('groupCount', count($groups));
305 $this->assign('mailingCount', count($mailings));
22e263ad 306 if (count($groups) == 0 && count($mailings) == 0 && !$this->_searchBasedMailing) {
f598ae72
E
307 CRM_Core_Error::statusBounce("To send a mailing, you must have a valid group of recipients - either at least one group that's a Mailing List or at least one previous mailing or start from a search");
308 }
6a488035
TO
309 }
310
311 public function postProcess() {
312 $values = $this->controller->exportValues($this->_name);
313
314 //build hidden smart group. when user want to send mailing
315 //through search contact-> more action -> send Mailing. CRM-3711
316 $groups = array();
317 if ($this->_searchBasedMailing && $this->_contactIds) {
318 $session = CRM_Core_Session::singleton();
319
320 if ($this->_resultSelectOption == 'ts_sel') {
321 // create a static grp if only a subset of result set was selected:
322
323 $randID = md5(time());
324 $grpTitle = "Hidden Group {$randID}";
325 $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
326
327 if (!$grpID) {
328 $groupParams = array(
329 'title' => $grpTitle,
330 'is_active' => 1,
331 'is_hidden' => 1,
332 'group_type' => array('2' => 1),
333 );
334
335 $group = CRM_Contact_BAO_Group::create($groupParams);
336 $grpID = $group->id;
337
338 CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
339
340 $newGroupTitle = "Hidden Group {$grpID}";
341 $groupParams = array(
342 'id' => $grpID,
343 'name' => CRM_Utils_String::titleToVar($newGroupTitle),
344 'title' => $newGroupTitle,
345 'group_type' => array('2' => 1),
346 );
347 $group = CRM_Contact_BAO_Group::create($groupParams);
348 }
349
350 // note at this point its a static group
351 $smartGroupId = $grpID;
352 }
353 else {
354 //get the hidden smart group id.
355 $ssId = $this->get('ssID');
35f7561f
TO
356 $hiddenSmartParams = array(
357 'group_type' => array('2' => 1),
6a488035
TO
358 'form_values' => $this->get('formValues'),
359 'saved_search_id' => $ssId,
360 'search_custom_id' => $this->get('customSearchID'),
361 'search_context' => $this->get('context'),
362 );
363
364 list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
365
366 //set the saved search id.
367 if (!$ssId) {
368 if ($savedSearchId) {
369 $this->set('ssID', $savedSearchId);
370 }
371 else {
372 CRM_Core_Error::fatal();
373 }
374 }
375 }
376
377 //get the base group for this mailing, CRM-3711
378 $groups['base'] = array($values['baseGroup']);
379 $values['includeGroups'][] = $smartGroupId;
380 }
381
382 foreach (
bac4cd35 383 array('name', 'group_id', 'search_id', 'search_args', 'campaign_id', 'dedupe_email', 'location_type_id', 'email_selection_method') as $n
6a488035 384 ) {
a7488080 385 if (!empty($values[$n])) {
6a488035
TO
386 $params[$n] = $values[$n];
387 }
388 }
389
6a488035
TO
390 $qf_Group_submit = $this->controller->exportValue($this->_name, '_qf_Group_submit');
391 $this->set('name', $params['name']);
392
393 $inGroups = $values['includeGroups'];
394 $outGroups = $values['excludeGroups'];
395 $inMailings = $values['includeMailings'];
396 $outMailings = $values['excludeMailings'];
397
398 if (is_array($inGroups)) {
399 foreach ($inGroups as $key => $id) {
400 if ($id) {
401 $groups['include'][] = $id;
402 }
403 }
404 }
405 if (is_array($outGroups)) {
406 foreach ($outGroups as $key => $id) {
407 if ($id) {
408 $groups['exclude'][] = $id;
409 }
410 }
411 }
412
413 $mailings = array();
414 if (is_array($inMailings)) {
415 foreach ($inMailings as $key => $id) {
416 if ($id) {
417 $mailings['include'][] = $id;
418 }
419 }
420 }
421 if (is_array($outMailings)) {
422 foreach ($outMailings as $key => $id) {
423 if ($id) {
424 $mailings['exclude'][] = $id;
425 }
426 }
427 }
428
429 $session = CRM_Core_Session::singleton();
430 $params['groups'] = $groups;
431 $params['mailings'] = $mailings;
432 $ids = array();
433 if ($this->get('mailing_id')) {
434
435 // don't create a new mailing if already exists
436 $ids['mailing_id'] = $this->get('mailing_id');
437
438 $groupTableName = CRM_Contact_BAO_Group::getTableName();
439 $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName();
440
441 // delete previous includes/excludes, if mailing already existed
442 foreach (array('groups', 'mailings') as $entity) {
04124b30 443 $mg = new CRM_Mailing_DAO_MailingGroup();
6a488035
TO
444 $mg->mailing_id = $ids['mailing_id'];
445 $mg->entity_table = ($entity == 'groups') ? $groupTableName : $mailingTableName;
446 $mg->find();
447 while ($mg->fetch()) {
448 $mg->delete();
449 }
450 }
451 }
452 else {
453 // new mailing, so lets set the created_id
454 $session = CRM_Core_Session::singleton();
455 $params['created_id'] = $session->get('userID');
456 $params['created_date'] = date('YmdHis');
457 }
6a488035
TO
458 $mailing = CRM_Mailing_BAO_Mailing::create($params, $ids);
459 $this->set('mailing_id', $mailing->id);
460
461 $dedupeEmail = FALSE;
462 if (isset($params['dedupe_email'])) {
463 $dedupeEmail = $params['dedupe_email'];
464 }
465
1365ea2f
BS
466 // mailing id should be added to the form object
467 $this->_mailingID = $mailing->id;
468
6a488035
TO
469 // also compute the recipients and store them in the mailing recipients table
470 CRM_Mailing_BAO_Mailing::getRecipients(
471 $mailing->id,
472 $mailing->id,
473 NULL,
474 NULL,
475 TRUE,
476 $dedupeEmail
477 );
478
479 $count = CRM_Mailing_BAO_Recipients::mailingSize($mailing->id);
480 $this->set('count', $count);
481 $this->assign('count', $count);
482 $this->set('groups', $groups);
483 $this->set('mailings', $mailings);
484
485 if ($qf_Group_submit) {
486 //when user perform mailing from search context
487 //redirect it to search result CRM-3711.
488 $ssID = $this->get('ssID');
489 $context = $this->get('context');
490 if ($ssID && $this->_searchBasedMailing) {
491 if ($this->_action == CRM_Core_Action::BASIC) {
492 $fragment = 'search';
493 }
494 elseif ($this->_action == CRM_Core_Action::PROFILE) {
495 $fragment = 'search/builder';
496 }
497 elseif ($this->_action == CRM_Core_Action::ADVANCED) {
498 $fragment = 'search/advanced';
499 }
500 else {
501 $fragment = 'search/custom';
502 }
503
504 $context = $this->get('context');
505 if (!CRM_Contact_Form_Search::isSearchContext($context)) {
506 $context = 'search';
507 }
508 $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}";
509
510 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
511 if (CRM_Utils_Rule::qfKey($qfKey)) {
512 $urlParams .= "&qfKey=$qfKey";
513 }
514
515 $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
516 $status = ts("You can continue later by clicking the 'Continue' action to resume working on it.<br />From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
517
518 // Redirect user to search.
519 $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams);
520 }
521 else {
522 $status = ts("Click the 'Continue' action to resume working on it.");
523 $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
524 }
525 CRM_Core_Session::setStatus($status, ts('Mailing Saved'), 'success');
526 return $this->controller->setDestination($url);
527 }
528 }
529
530 /**
531 * Display Name of the form
532 *
6a488035
TO
533 *
534 * @return string
535 */
536 public function getTitle() {
537 return ts('Select Recipients');
538 }
539
540 /**
100fef9d 541 * Global validation rules for the form
6a488035 542 *
90c8230e
TO
543 * @param array $fields
544 * Posted values of the form.
6a488035
TO
545 *
546 * @return array list of errors to be posted back to the form
547 * @static
6a488035 548 */
00be9182 549 public static function formRule($fields) {
6a488035
TO
550 $errors = array();
551 if (isset($fields['includeGroups']) &&
552 is_array($fields['includeGroups']) &&
553 isset($fields['excludeGroups']) &&
554 is_array($fields['excludeGroups'])
555 ) {
556 $checkGroups = array();
557 $checkGroups = array_intersect($fields['includeGroups'], $fields['excludeGroups']);
558 if (!empty($checkGroups)) {
559 $errors['excludeGroups'] = ts('Cannot have same groups in Include Group(s) and Exclude Group(s).');
560 }
561 }
562
563 if (isset($fields['includeMailings']) &&
564 is_array($fields['includeMailings']) &&
565 isset($fields['excludeMailings']) &&
566 is_array($fields['excludeMailings'])
567 ) {
568 $checkMailings = array();
569 $checkMailings = array_intersect($fields['includeMailings'], $fields['excludeMailings']);
570 if (!empty($checkMailings)) {
571 $errors['excludeMailings'] = ts('Cannot have same mail in Include mailing(s) and Exclude mailing(s).');
572 }
573 }
574
575 if (!empty($fields['search_id']) &&
576 empty($fields['group_id'])
577 ) {
578 $errors['group_id'] = ts('You must select a group to filter on');
579 }
580
581 if (empty($fields['search_id']) &&
582 !empty($fields['group_id'])
583 ) {
584 $errors['search_id'] = ts('You must select a search to filter');
585 }
586
bac4cd35 587 if (!empty($fields['location_type_id'])) {
588 if ($fields['email_selection_method'] == 'automatic') {
589 $errors['location_type_id'] = ts("If 'Email Selection Method' is automatic, you are not allowed to choose any 'Location Type'");
590 }
591 }
592 elseif ($fields['email_selection_method'] != 'automatic') {
593 $errors['email_selection_method'] = ts("If 'Location Type' is not selected, you must set the 'Email Selection Method' to automatic as well.");
594 }
595
6a488035
TO
596 return empty($errors) ? TRUE : $errors;
597 }
598}