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