Merge commit '1ebbf8bfc16f4' into 4.5-missing-prs
[civicrm-core.git] / CRM / Admin / Form / ScheduleReminders.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright (C) 2011 Marty Wright |
7 | Licensed to CiviCRM under the Academic Free License version 3.0. |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36
37 /**
38 * This class generates form components for Scheduling Reminders
39 *
40 */
41 class CRM_Admin_Form_ScheduleReminders extends CRM_Admin_Form {
42
43 /**
44 * Scheduled Reminder ID
45 */
46 protected $_id = NULL;
47
48 public $_freqUnits;
49
50 /**
51 * Function to build the form
52 *
53 * @return void
54 * @access public
55 */
56 public function buildQuickForm() {
57 parent::buildQuickForm();
58 $this->_mappingID = $mappingID = NULL;
59 $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
60
61 if ($this->_action & (CRM_Core_Action::DELETE)) {
62 $reminderName =
63 CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
64 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
65 if ($this->_context == 'event') {
66 $this->_eventId = CRM_Utils_Request::retrieve('eventId', 'Integer', $this);
67 }
68 $this->assign('reminderName', $reminderName);
69 return;
70 }
71 elseif ($this->_action & (CRM_Core_Action::UPDATE)) {
72 $this->_mappingID =
73 CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
74 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
75 if ($this->_context == 'event') {
76 $this->_eventId = CRM_Utils_Request::retrieve('eventId', 'Integer', $this);
77 }
78 }
79
80 if (!empty($_POST) && !empty($_POST['entity'])) {
81 $mappingID = $_POST['entity'][0];
82 }
83 elseif ($this->_mappingID) {
84 $mappingID = $this->_mappingID;
85 }
86
87 $this->add(
88 'text',
89 'title',
90 ts('Title'),
91 array('size' => 45, 'maxlength' => 128),
92 TRUE
93 );
94
95 $selectionOptions = CRM_Core_BAO_ActionSchedule::getSelection($mappingID);
96 extract($selectionOptions);
97
98 if (empty($sel1)) {
99 CRM_Core_Error::fatal('Could not find mapping for scheduled reminders.');
100 }
101 $this->assign('entityMapping', json_encode($entityMapping));
102 $this->assign('recipientMapping', json_encode($recipientMapping));
103
104 $sel = & $this->add(
105 'hierselect',
106 'entity',
107 ts('Entity'),
108 array(
109 'name' => 'entity[0]',
110 'style' => 'vertical-align: top;',
111 ),
112 TRUE
113 );
114 $sel->setOptions(array($sel1, $sel2, $sel3));
115
116 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
117 // make second selector a multi-select -
118 $sel->_elements[1]->setMultiple(TRUE);
119 $sel->_elements[1]->setSize(5);
120 }
121
122 if (is_a($sel->_elements[2], 'HTML_QuickForm_select')) {
123 // make third selector a multi-select -
124 $sel->_elements[2]->setMultiple(TRUE);
125 $sel->_elements[2]->setSize(5);
126 }
127
128 //get the frequency units.
129 $this->_freqUnits = CRM_Core_SelectValues::getScheduleReminderFrequencyUnits();
130
131 //pass the mapping ID in UPDATE mode
132 $mappings = CRM_Core_BAO_ActionSchedule::getMapping($mappingID);
133
134 $numericOptions = CRM_Core_SelectValues::getNumericOptions(0, 30);
135
136 //reminder_interval
137 $this->add('select', 'start_action_offset', ts('When'), $numericOptions);
138 $isActive = ts('Send email');
139 $recordActivity = ts('Record activity for automated email');
140 if ($providersCount) {
141 $this->assign('sms', $providersCount);
142 $isActive = ts('Send email or SMS');
143 $recordActivity = ts('Record activity for automated email or SMS');
144 $options = CRM_Core_OptionGroup::values('msg_mode');
145 $this->add('select', 'mode', ts('Send as'), $options);
146
147 $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
148
149 $providerSelect = array();
150 foreach ($providers as $provider) {
151 $providerSelect[$provider['id']] = $provider['title'];
152 }
153 $this->add('select', 'sms_provider_id', ts('SMS Provider'), $providerSelect, TRUE);
154 }
155
156 foreach ($this->_freqUnits as $val => $label) {
157 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
158 }
159
160 $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing'));
161
162 //reminder_frequency
163 $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
164
165 $condition = array('before' => ts('before'),
166 'after' => ts('after'),
167 );
168 //reminder_action
169 $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
170
171 $this->add('select', 'start_action_date', ts('Date Field'), $sel4, TRUE);
172
173 $this->addElement('checkbox', 'record_activity', $recordActivity);
174
175 $this->addElement('checkbox', 'is_repeat', ts('Repeat'),
176 NULL, array('onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);")
177 );
178
179 $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
180 $this->add('select', 'repetition_frequency_interval', ts('every'), $numericOptions);
181 $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
182 $this->add('select', 'end_frequency_interval', ts('until'), $numericOptions);
183 $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
184 $this->add('select', 'end_date', ts('Date Field'), $sel4, TRUE);
185
186 $this->add('text', 'from_name', ts('From Name'));
187 $this->add('text', 'from_email', ts('From Email'));
188
189 $recipient = 'activity_contacts';
190 $recipientListingOptions = array();
191
192 if ($mappingID) {
193 $recipient = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping',
194 $mappingID,
195 'entity_recipient'
196 );
197 }
198
199 $limitOptions = array(1 => ts('Limit to'), 0 => ts('Also include'));
200 $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions);
201
202 $this->add('select', 'recipient', ts('Recipients'), $sel5[$recipient],
203 FALSE, array('onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);")
204 );
205
206 if (!empty($_POST['is_recipient_listing'])) {
207 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($_POST['entity'][0], $_POST['recipient']);
208 }
209 elseif (!empty($this->_values['recipient_listing'])) {
210 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
211 }
212 $this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE,
213 array('multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE));
214 $this->add('hidden', 'is_recipient_listing', (int) !empty($recipientListingOptions));
215
216 $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), array('multiple' => TRUE, 'create' => TRUE));
217
218 $this->add('select', 'group_id', ts('Group'),
219 CRM_Core_PseudoConstant::nestedGroup(), FALSE, array('class' => 'crm-select2 huge')
220 );
221
222 CRM_Mailing_BAO_Mailing::commonCompose($this);
223
224 $this->add('text', 'subject', ts('Subject'),
225 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject')
226 );
227
228 $this->add('checkbox', 'is_active', $isActive);
229
230 $this->addFormRule(array('CRM_Admin_Form_ScheduleReminders', 'formRule'));
231
232 $this->setPageTitle(ts('Scheduled Reminder'));
233 }
234 /**
235 * global form rule
236 *
237 * @param array $fields the input form values
238 *
239 * @return true if no errors, else array of errors
240 * @access public
241 * @static
242 */
243 static function formRule($fields) {
244 $errors = array();
245 if ((array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0) ||
246 (array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0)
247 ) {
248 $errors['entity'] = ts('Please select appropriate value');
249 }
250
251 if (array_key_exists(1, $fields['entity']) && !is_numeric($fields['entity'][1][0])) {
252 if (count($fields['entity'][1]) > 1) {
253 $errors['entity'] = ts('You may only select one contact field per reminder');
254 }
255 elseif (!(array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] > 0)) {
256 $errors['entity'] = ts('Please select whether the reminder is sent each year.');
257 }
258 }
259
260 if (!empty($fields['is_active']) && $fields['mode'] != 'SMS' &&
261 CRM_Utils_System::isNull($fields['subject'])
262 ) {
263 $errors['subject'] = ts('Subject is a required field.');
264 }
265
266 if (CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
267 $errors['entity'] = ts('Please select entity value');
268 }
269
270 if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
271 if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('Ymd'))) {
272 $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
273 }
274 }
275
276 if (!empty($errors)) {
277 return $errors;
278 }
279
280 return empty($errors) ? TRUE : $errors;
281 }
282
283 /**
284 * @return int
285 */
286 function setDefaultValues() {
287 if ($this->_action & CRM_Core_Action::ADD) {
288 $defaults['is_active'] = 1;
289 $defaults['mode'] = 'Email';
290 $defaults['record_activity'] = 1;
291 }
292 else {
293 $defaults = $this->_values;
294 $entityValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
295 CRM_Utils_Array::value('entity_value', $defaults)
296 );
297 $entityStatus = explode(CRM_Core_DAO::VALUE_SEPARATOR,
298 CRM_Utils_Array::value('entity_status', $defaults)
299 );
300 $defaults['entity'][0] = CRM_Utils_Array::value('mapping_id', $defaults);
301 $defaults['entity'][1] = $entityValue;
302 $defaults['entity'][2] = $entityStatus;
303 if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $defaults)) {
304 list($date, $time) = CRM_Utils_Date::setDateDefaults($absoluteDate);
305 $defaults['absolute_date'] = $date;
306 }
307
308 if ($recipientListing = CRM_Utils_Array::value('recipient_listing', $defaults)) {
309 $defaults['recipient_listing'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
310 $recipientListing
311 );
312 }
313 $defaults['text_message'] = CRM_Utils_Array::value('body_text', $defaults);
314 $defaults['html_message'] = CRM_Utils_Array::value('body_html', $defaults);
315 $defaults['sms_text_message'] = CRM_Utils_Array::value('sms_body_text', $defaults);
316 $defaults['template'] = CRM_Utils_Array::value('msg_template_id', $defaults);
317 $defaults['SMStemplate'] = CRM_Utils_Array::value('sms_template_id', $defaults);
318 if (!empty($defaults['group_id'])) {
319 $defaults['recipient'] = 'group';
320 }
321 elseif (!empty($defaults['recipient_manual'])) {
322 $defaults['recipient'] = 'manual';
323 $defaults['recipient_manual_id'] = $defaults['recipient_manual'];
324 }
325 }
326
327 return $defaults;
328 }
329
330 /**
331 * Function to process the form
332 *
333 * @access public
334 *
335 * @return void
336 */
337 public function postProcess() {
338 if ($this->_action & CRM_Core_Action::DELETE) {
339 // delete reminder
340 CRM_Core_BAO_ActionSchedule::del($this->_id);
341 CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success');
342 if ($this->_context == 'event' && $this->_eventId) {
343 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
344 "reset=1&action=update&id={$this->_eventId}"
345 );
346 $session = CRM_Core_Session::singleton();
347 $session->pushUserContext($url);
348 }
349 return;
350 }
351 $values = $this->controller->exportValues($this->getName());
352
353 $keys = array(
354 'title',
355 'subject',
356 'absolute_date',
357 'group_id',
358 'record_activity',
359 'limit_to',
360 'mode',
361 'sms_provider_id',
362 'from_name',
363 'from_email',
364 );
365 foreach ($keys as $key) {
366 $params[$key] = CRM_Utils_Array::value($key, $values);
367 }
368
369 $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0);
370
371 $moreKeys = array(
372 'start_action_offset',
373 'start_action_unit',
374 'start_action_condition',
375 'start_action_date',
376 'repetition_frequency_unit',
377 'repetition_frequency_interval',
378 'end_frequency_unit',
379 'end_frequency_interval',
380 'end_action',
381 'end_date',
382 );
383
384 if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) {
385 $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate);
386 $params['is_repeat'] = 0;
387 foreach ($moreKeys as $mkey) {
388 $params[$mkey] = 'null';
389 }
390 }
391 else {
392 $params['absolute_date'] = 'null';
393 foreach ($moreKeys as $mkey) {
394 $params[$mkey] = CRM_Utils_Array::value($mkey, $values);
395 }
396 }
397
398 $params['body_text'] = CRM_Utils_Array::value('text_message', $values);
399 $params['sms_body_text'] = CRM_Utils_Array::value('sms_text_message', $values);
400 $params['body_html'] = CRM_Utils_Array::value('html_message', $values);
401
402 if (CRM_Utils_Array::value('recipient', $values) == 'manual') {
403 $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values);
404 $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null';
405 }
406 elseif (CRM_Utils_Array::value('recipient', $values) == 'group') {
407 $params['group_id'] = $values['group_id'];
408 $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null';
409 }
410 elseif (!CRM_Utils_System::isNull($values['recipient_listing'])) {
411 $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
412 $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
413 CRM_Utils_Array::value('recipient_listing', $values)
414 );
415 $params['group_id'] = $params['recipient_manual'] = 'null';
416 }
417 else {
418 $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
419 $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
420 }
421
422 $params['mapping_id'] = $values['entity'][0];
423 $entity_value = $values['entity'][1];
424 $entity_status = $values['entity'][2];
425
426 foreach (array(
427 'entity_value', 'entity_status') as $key) {
428 $params[$key] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $$key);
429 }
430
431 $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0);
432
433 if (CRM_Utils_Array::value('is_repeat', $values) == 0) {
434 $params['repetition_frequency_unit'] = 'null';
435 $params['repetition_frequency_interval'] = 'null';
436 $params['end_frequency_unit'] = 'null';
437 $params['end_frequency_interval'] = 'null';
438 $params['end_action'] = 'null';
439 $params['end_date'] = 'null';
440 }
441
442 if ($this->_action & CRM_Core_Action::UPDATE) {
443 $params['id'] = $this->_id;
444 }
445 elseif ($this->_action & CRM_Core_Action::ADD) {
446 // we do this only once, so name never changes
447 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64);
448 }
449
450 $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
451
452 if ($params['mode'] == 'Email' || empty($params['sms_provider_id'])) {
453 unset($modePrefixes['SMS']);
454 }
455 elseif ($params['mode'] == 'SMS') {
456 unset($modePrefixes['Mail']);
457 }
458
459 //TODO: handle postprocessing of SMS and/or Email info based on $modePrefixes
460
461 $composeFields = array(
462 'template', 'saveTemplate',
463 'updateTemplate', 'saveTemplateName',
464 );
465 $msgTemplate = NULL;
466 //mail template is composed
467
468 foreach ($modePrefixes as $prefix) {
469 $composeParams = array();
470 foreach ($composeFields as $key) {
471 $key = $prefix . $key;
472 if (!empty($values[$key])) {
473 $composeParams[$key] = $values[$key];
474 }
475 }
476
477 if (!empty($composeParams[$prefix . 'updateTemplate'])) {
478 $templateParams = array('is_active' => TRUE);
479 if ($prefix == 'SMS') {
480 $templateParams += array(
481 'msg_text' => $params['sms_body_text'],
482 'is_sms' => TRUE,
483 );
484 }
485 else {
486 $templateParams += array(
487 'msg_text' => $params['body_text'],
488 'msg_html' => $params['body_html'],
489 'msg_subject' => $params['subject'],
490 );
491 }
492 $templateParams['id'] = $values[$prefix . 'template'];
493
494 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
495 }
496
497 if (!empty($composeParams[$prefix . 'saveTemplate'])) {
498 $templateParams = array('is_active' => TRUE);
499 if ($prefix == 'SMS') {
500 $templateParams += array(
501 'msg_text' => $params['sms_body_text'],
502 'is_sms' => TRUE,
503 );
504 }
505 else {
506 $templateParams += array(
507 'msg_text' => $params['body_text'],
508 'msg_html' => $params['body_html'],
509 'msg_subject' => $params['subject'],
510 );
511 }
512 $templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName'];
513
514 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
515 }
516
517 if ($prefix == 'SMS') {
518 if (isset($msgTemplate->id)) {
519 $params['sms_template_id'] = $msgTemplate->id;
520 }
521 else {
522 $params['sms_template_id'] = CRM_Utils_Array::value('SMStemplate', $values);
523 }
524 }
525 else {
526 if (isset($msgTemplate->id)) {
527 $params['msg_template_id'] = $msgTemplate->id;
528 }
529 else {
530 $params['msg_template_id'] = CRM_Utils_Array::value('template', $values);
531 }
532 }
533 }
534
535 $bao = CRM_Core_BAO_ActionSchedule::add($params);
536 // we need to set this on the form so that hooks can identify the created entity
537 $this->set('id', $bao->id);
538 $bao->free();
539
540 $status = ts("Your new Reminder titled %1 has been saved.",
541 array(1 => "<strong>{$values['title']}</strong>")
542 );
543 if ($this->_action & CRM_Core_Action::UPDATE) {
544 $status = ts("Your Reminder titled %1 has been updated.",
545 array(1 => "<strong>{$values['title']}</strong>")
546 );
547
548 if ($this->_context == 'event' && $this->_eventId) {
549 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
550 "reset=1&action=update&id={$this->_eventId}"
551 );
552 $session = CRM_Core_Session::singleton();
553 $session->pushUserContext($url);
554 }
555 }
556 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
557 }
558 }
559