Merge pull request #11691 from JKingsnorth/CRM-21773
[civicrm-core.git] / CRM / Admin / Form / ScheduleReminders.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33
34 /**
35 * This class generates form components for Scheduling Reminders.
36 */
37 class CRM_Admin_Form_ScheduleReminders extends CRM_Admin_Form {
38
39 /**
40 * Scheduled Reminder ID.
41 */
42 protected $_id = NULL;
43
44 public $_freqUnits;
45
46 /**
47 * Build the form object.
48 */
49 public function buildQuickForm() {
50 parent::buildQuickForm();
51 $this->_mappingID = $mappingID = NULL;
52 $providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
53 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
54
55 //CRM-16777: Don't provide access to administer schedule reminder page, with user that does not have 'administer CiviCRM' permission
56 if (empty($this->_context) && !CRM_Core_Permission::check('administer CiviCRM')) {
57 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
58 }
59 //CRM-16777: When user have ACLs 'edit' permission for specific event, do not give access to add, delete & updtae
60 //schedule reminder for other events.
61 else {
62 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
63 if (!CRM_Event_BAO_Event::checkPermission($this->_compId, CRM_Core_Permission::EDIT)) {
64 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
65 }
66 }
67
68 if ($this->_action & (CRM_Core_Action::DELETE)) {
69 $reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
70 if ($this->_context == 'event') {
71 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
72 }
73 $this->assign('reminderName', $reminderName);
74 return;
75 }
76 elseif ($this->_action & (CRM_Core_Action::UPDATE)) {
77 $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
78 if ($this->_context == 'event') {
79 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
80 }
81 }
82 elseif (!empty($this->_context)) {
83 if ($this->_context == 'event') {
84 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
85 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_compId, 'is_template');
86 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
87 'id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
88 )));
89 if ($mapping) {
90 $this->_mappingID = $mapping->getId();
91 }
92 else {
93 CRM_Core_Error::fatal('Could not find mapping for event scheduled reminders.');
94 }
95 }
96 }
97
98 if (!empty($_POST) && !empty($_POST['entity']) && empty($this->_context)) {
99 $mappingID = $_POST['entity'][0];
100 }
101 elseif ($this->_mappingID) {
102 $mappingID = $this->_mappingID;
103 if ($this->_context == 'event') {
104 $this->add('hidden', 'mappingID', $mappingID);
105 }
106 }
107
108 $this->add(
109 'text',
110 'title',
111 ts('Title'),
112 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'title'),
113 TRUE
114 );
115
116 $mappings = CRM_Core_BAO_ActionSchedule::getMappings();
117 $selectedMapping = $mappings[$mappingID ? $mappingID : 1];
118 $entityRecipientLabels = $selectedMapping->getRecipientTypes() + CRM_Core_BAO_ActionSchedule::getAdditionalRecipients();
119 $this->assign('entityMapping', json_encode(
120 CRM_Utils_Array::collectMethod('getEntity', $mappings)
121 ));
122 $this->assign('recipientMapping', json_encode(
123 array_combine(array_keys($entityRecipientLabels), array_keys($entityRecipientLabels))
124 ));
125
126 if (empty($this->_context)) {
127 $sel = &$this->add(
128 'hierselect',
129 'entity',
130 ts('Entity'),
131 array(
132 'name' => 'entity[0]',
133 'style' => 'vertical-align: top;',
134 )
135 );
136 $sel->setOptions(array(
137 CRM_Utils_Array::collectMethod('getLabel', $mappings),
138 CRM_Core_BAO_ActionSchedule::getAllEntityValueLabels(),
139 CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels(),
140 ));
141
142 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
143 // make second selector a multi-select -
144 $sel->_elements[1]->setMultiple(TRUE);
145 $sel->_elements[1]->setSize(5);
146 }
147
148 if (is_a($sel->_elements[2], 'HTML_QuickForm_select')) {
149 // make third selector a multi-select -
150 $sel->_elements[2]->setMultiple(TRUE);
151 $sel->_elements[2]->setSize(5);
152 }
153 }
154 else {
155 // Dig deeper - this code is sublimely stupid.
156 $allEntityStatusLabels = CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels();
157 $options = $allEntityStatusLabels[$this->_mappingID][0];
158 $attributes = array('multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]);
159 unset($options[0]);
160 $this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes);
161 $this->assign('context', $this->_context);
162 }
163
164 //get the frequency units.
165 $this->_freqUnits = CRM_Core_SelectValues::getRecurringFrequencyUnits();
166
167 //reminder_interval
168 $this->add('number', 'start_action_offset', ts('When'), array('class' => 'six', 'min' => 0));
169 $this->addRule('start_action_offset', ts('Value should be a positive number'), 'positiveInteger');
170
171 $isActive = ts('Send email');
172 $recordActivity = ts('Record activity for automated email');
173 if ($providersCount) {
174 $this->assign('sms', $providersCount);
175 $isActive = ts('Send email or SMS');
176 $recordActivity = ts('Record activity for automated email or SMS');
177 $options = CRM_Core_OptionGroup::values('msg_mode');
178 $this->add('select', 'mode', ts('Send as'), $options);
179
180 $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
181
182 $providerSelect = array();
183 foreach ($providers as $provider) {
184 $providerSelect[$provider['id']] = $provider['title'];
185 }
186 $this->add('select', 'sms_provider_id', ts('SMS Provider'), $providerSelect, TRUE);
187 }
188
189 foreach ($this->_freqUnits as $val => $label) {
190 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
191 }
192
193 $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing'));
194
195 //reminder_frequency
196 $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
197
198 $condition = array(
199 'before' => ts('before'),
200 'after' => ts('after'),
201 );
202 //reminder_action
203 $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
204
205 $this->add('select', 'start_action_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
206
207 $this->addElement('checkbox', 'record_activity', $recordActivity);
208
209 $this->addElement('checkbox', 'is_repeat', ts('Repeat'),
210 NULL, array('onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);")
211 );
212
213 $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
214 $this->add('number', 'repetition_frequency_interval', ts('every'), array('class' => 'six', 'min' => 0));
215 $this->addRule('repetition_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
216
217 $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
218 $this->add('number', 'end_frequency_interval', ts('until'), array('class' => 'six', 'min' => 0));
219 $this->addRule('end_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
220
221 $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
222 $this->add('select', 'end_date', ts('Date Field'), $selectedMapping->getDateFields(), TRUE);
223
224 $this->add('text', 'from_name', ts('From Name'));
225 $this->add('text', 'from_email', ts('From Email'));
226
227 $recipientListingOptions = array();
228
229 if ($mappingID) {
230 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
231 'id' => $mappingID,
232 )));
233 }
234
235 $limitOptions = array('' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include'));
236
237 $recipientLabels = array('activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients'));
238 $this->assign('recipientLabels', $recipientLabels);
239
240 $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, array('onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"));
241
242 $this->add('select', 'recipient', $recipientLabels['other'], $entityRecipientLabels,
243 FALSE, array('onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);")
244 );
245
246 if (!empty($this->_submitValues['recipient_listing'])) {
247 if (!empty($this->_context)) {
248 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_mappingID, $this->_submitValues['recipient']);
249 }
250 else {
251 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($_POST['entity'][0], $_POST['recipient']);
252 }
253 }
254 elseif (!empty($this->_values['recipient_listing'])) {
255 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
256 }
257
258 $this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE,
259 array('multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE));
260
261 $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), array('multiple' => TRUE, 'create' => TRUE));
262
263 $this->add('select', 'group_id', ts('Group'),
264 CRM_Core_PseudoConstant::nestedGroup('Mailing'), FALSE, array('class' => 'crm-select2 huge')
265 );
266
267 // multilingual only options
268 $multilingual = CRM_Core_I18n::isMultilingual();
269 if ($multilingual) {
270 $smarty = CRM_Core_Smarty::singleton();
271 $smarty->assign('multilingual', $multilingual);
272
273 $languages = CRM_Core_I18n::languages(TRUE);
274 $languageFilter = $languages + array(CRM_Core_I18n::NONE => ts('Contacts with no preferred language'));
275 $element = $this->add('select', 'filter_contact_language', ts('Recipients language'), $languageFilter, FALSE,
276 array('multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE));
277
278 $communicationLanguage = array(
279 '' => ts('System default language'),
280 CRM_Core_I18n::AUTO => ts('Follow recipient preferred language'),
281 );
282 $communicationLanguage = $communicationLanguage + $languages;
283 $this->add('select', 'communication_language', ts('Communication language'), $communicationLanguage);
284 }
285
286 CRM_Mailing_BAO_Mailing::commonCompose($this);
287
288 $this->add('text', 'subject', ts('Subject'),
289 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject')
290 );
291
292 $this->add('checkbox', 'is_active', $isActive);
293
294 $this->addFormRule(array('CRM_Admin_Form_ScheduleReminders', 'formRule'), $this);
295
296 $this->setPageTitle(ts('Scheduled Reminder'));
297 }
298
299 /**
300 * Global form rule.
301 *
302 * @param array $fields
303 * The input form values.
304 * @param array $files
305 * @param CRM_Admin_Form_ScheduleReminders $self
306 *
307 * @return array|bool
308 * True if no errors, else array of errors
309 */
310 public static function formRule($fields, $files, $self) {
311 $errors = array();
312 if ((array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0) ||
313 (array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0)
314 ) {
315 $errors['entity'] = ts('Please select appropriate value');
316 }
317
318 if (!empty($fields['is_active']) &&
319 CRM_Utils_System::isNull($fields['subject'])
320 ) {
321 $errors['subject'] = ts('Subject is a required field.');
322 }
323 if (!empty($fields['is_active']) &&
324 CRM_Utils_System::isNull(trim(strip_tags($fields['html_message'])))
325 ) {
326 $errors['html_message'] = ts('The HTML message is a required field.');
327 }
328
329 if (empty($self->_context) && CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
330 $errors['entity'] = ts('Please select entity value');
331 }
332
333 if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
334 if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('Ymd'))) {
335 $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
336 }
337 }
338
339 $recipientKind = array(
340 'participant_role' => array(
341 'name' => 'participant role',
342 'target_id' => 'recipient_listing',
343 ),
344 'manual' => array(
345 'name' => 'recipient',
346 'target_id' => 'recipient_manual_id',
347 ),
348 );
349 if ($fields['limit_to'] != '' && array_key_exists($fields['recipient'], $recipientKind) && empty($fields[$recipientKind[$fields['recipient']]['target_id']])) {
350 $errors[$recipientKind[$fields['recipient']]['target_id']] = ts('If "Also include" or "Limit to" are selected, you must specify at least one %1', array(1 => $recipientKind[$fields['recipient']]['name']));
351 }
352
353 $actionSchedule = $self->parseActionSchedule($fields);
354 if ($actionSchedule->mapping_id) {
355 $mapping = CRM_Core_BAO_ActionSchedule::getMapping($actionSchedule->mapping_id);
356 CRM_Utils_Array::extend($errors, $mapping->validateSchedule($actionSchedule));
357 }
358
359 if (!empty($errors)) {
360 return $errors;
361 }
362
363 return empty($errors) ? TRUE : $errors;
364 }
365
366 /**
367 * @return int
368 */
369 public function setDefaultValues() {
370 if ($this->_action & CRM_Core_Action::ADD) {
371 $defaults['is_active'] = 1;
372 $defaults['mode'] = 'Email';
373 $defaults['record_activity'] = 1;
374 }
375 else {
376 $defaults = $this->_values;
377 $entityValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('entity_value', $defaults));
378 $entityStatus = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('entity_status', $defaults));
379 if (empty($this->_context)) {
380 $defaults['entity'][0] = CRM_Utils_Array::value('mapping_id', $defaults);
381 $defaults['entity'][1] = $entityValue;
382 $defaults['entity'][2] = $entityStatus;
383 }
384 else {
385 $defaults['entity'] = $entityStatus;
386 }
387 if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $defaults)) {
388 list($date, $time) = CRM_Utils_Date::setDateDefaults($absoluteDate);
389 $defaults['absolute_date'] = $date;
390 }
391
392 if ($recipientListing = CRM_Utils_Array::value('recipient_listing', $defaults)) {
393 $defaults['recipient_listing'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
394 $recipientListing
395 );
396 }
397 $defaults['text_message'] = CRM_Utils_Array::value('body_text', $defaults);
398 $defaults['html_message'] = CRM_Utils_Array::value('body_html', $defaults);
399 $defaults['sms_text_message'] = CRM_Utils_Array::value('sms_body_text', $defaults);
400 $defaults['template'] = CRM_Utils_Array::value('msg_template_id', $defaults);
401 $defaults['SMStemplate'] = CRM_Utils_Array::value('sms_template_id', $defaults);
402 if (!empty($defaults['group_id'])) {
403 $defaults['recipient'] = 'group';
404 }
405 elseif (!empty($defaults['recipient_manual'])) {
406 $defaults['recipient'] = 'manual';
407 $defaults['recipient_manual_id'] = $defaults['recipient_manual'];
408 }
409 if ($contactLanguage = CRM_Utils_Array::value('filter_contact_language', $defaults)) {
410 $defaults['filter_contact_language'] = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contactLanguage);
411 }
412 }
413
414 return $defaults;
415 }
416
417 /**
418 * Process the form submission.
419 */
420 public function postProcess() {
421 if ($this->_action & CRM_Core_Action::DELETE) {
422 // delete reminder
423 CRM_Core_BAO_ActionSchedule::del($this->_id);
424 CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success');
425 if ($this->_context == 'event' && $this->_compId) {
426 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
427 "reset=1&action=browse&id={$this->_compId}&component={$this->_context}&setTab=1"
428 );
429 $session = CRM_Core_Session::singleton();
430 $session->pushUserContext($url);
431 }
432 return;
433 }
434 $values = $this->controller->exportValues($this->getName());
435 $bao = $this->parseActionSchedule($values)->save();
436
437 // we need to set this on the form so that hooks can identify the created entity
438 $this->set('id', $bao->id);
439 $bao->free();
440
441 $status = ts("Your new Reminder titled %1 has been saved.",
442 array(1 => "<strong>{$values['title']}</strong>")
443 );
444
445 if ($this->_action) {
446 if ($this->_action & CRM_Core_Action::UPDATE) {
447 $status = ts("Your Reminder titled %1 has been updated.",
448 array(1 => "<strong>{$values['title']}</strong>")
449 );
450 }
451
452 if ($this->_context == 'event' && $this->_compId) {
453 $url = CRM_Utils_System::url('civicrm/event/manage/reminder', "reset=1&action=browse&id={$this->_compId}&component={$this->_context}&setTab=1");
454 $session = CRM_Core_Session::singleton();
455 $session->pushUserContext($url);
456 }
457 }
458 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
459 }
460
461 /**
462 * @param array $values
463 * The submitted form values.
464 * @return CRM_Core_DAO_ActionSchedule
465 */
466 public function parseActionSchedule($values) {
467 $params = array();
468
469 $keys = array(
470 'title',
471 'subject',
472 'absolute_date',
473 'group_id',
474 'record_activity',
475 'limit_to',
476 'mode',
477 'sms_provider_id',
478 'from_name',
479 'from_email',
480 );
481 foreach ($keys as $key) {
482 $params[$key] = CRM_Utils_Array::value($key, $values);
483 }
484
485 $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0);
486
487 $moreKeys = array(
488 'start_action_offset',
489 'start_action_unit',
490 'start_action_condition',
491 'start_action_date',
492 'repetition_frequency_unit',
493 'repetition_frequency_interval',
494 'end_frequency_unit',
495 'end_frequency_interval',
496 'end_action',
497 'end_date',
498 );
499
500 if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) {
501 $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate);
502 }
503 else {
504 $params['absolute_date'] = 'null';
505 }
506 foreach ($moreKeys as $mkey) {
507 if ($params['absolute_date'] != 'null' && CRM_Utils_String::startsWith($mkey, 'start_action')) {
508 $params[$mkey] = 'null';
509 continue;
510 }
511 $params[$mkey] = CRM_Utils_Array::value($mkey, $values);
512 }
513
514 $params['body_text'] = CRM_Utils_Array::value('text_message', $values);
515 $params['sms_body_text'] = CRM_Utils_Array::value('sms_text_message', $values);
516 $params['body_html'] = CRM_Utils_Array::value('html_message', $values);
517
518 if (CRM_Utils_Array::value('recipient', $values) == 'manual') {
519 $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values);
520 $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null';
521 }
522 elseif (CRM_Utils_Array::value('recipient', $values) == 'group') {
523 $params['group_id'] = $values['group_id'];
524 $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null';
525 }
526 elseif (isset($values['recipient_listing']) && isset($values['limit_to']) && !CRM_Utils_System::isNull($values['recipient_listing']) && !CRM_Utils_System::isNull($values['limit_to'])) {
527 $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
528 $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
529 CRM_Utils_Array::value('recipient_listing', $values)
530 );
531 $params['group_id'] = $params['recipient_manual'] = 'null';
532 }
533 else {
534 $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
535 $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
536 }
537
538 if (!empty($this->_mappingID) && !empty($this->_compId)) {
539 $params['mapping_id'] = $this->_mappingID;
540 $params['entity_value'] = $this->_compId;
541 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']);
542 }
543 else {
544 $params['mapping_id'] = $values['entity'][0];
545 if ($params['mapping_id'] == 1) {
546 $params['limit_to'] = 1;
547 }
548
549 $entity_value = CRM_Utils_Array::value(1, $values['entity'], array());
550 $entity_status = CRM_Utils_Array::value(2, $values['entity'], array());
551 $params['entity_value'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_value);
552 $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_status);
553 }
554
555 $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0);
556
557 if (CRM_Utils_Array::value('is_repeat', $values) == 0) {
558 $params['repetition_frequency_unit'] = 'null';
559 $params['repetition_frequency_interval'] = 'null';
560 $params['end_frequency_unit'] = 'null';
561 $params['end_frequency_interval'] = 'null';
562 $params['end_action'] = 'null';
563 $params['end_date'] = 'null';
564 }
565
566 // multilingual options
567 $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, array());
568 $params['filter_contact_language'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['filter_contact_language']);
569 $params['communication_language'] = CRM_Utils_Array::value('communication_language', $values, NULL);
570
571 if ($this->_action & CRM_Core_Action::UPDATE) {
572 $params['id'] = $this->_id;
573 }
574 elseif ($this->_action & CRM_Core_Action::ADD) {
575 // we do this only once, so name never changes
576 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64);
577 }
578
579 $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
580
581 if ($params['mode'] == 'Email' || empty($params['sms_provider_id'])) {
582 unset($modePrefixes['SMS']);
583 }
584 elseif ($params['mode'] == 'SMS') {
585 unset($modePrefixes['Mail']);
586 }
587
588 //TODO: handle postprocessing of SMS and/or Email info based on $modePrefixes
589
590 $composeFields = array(
591 'template',
592 'saveTemplate',
593 'updateTemplate',
594 'saveTemplateName',
595 );
596 $msgTemplate = NULL;
597 //mail template is composed
598
599 foreach ($modePrefixes as $prefix) {
600 $composeParams = array();
601 foreach ($composeFields as $key) {
602 $key = $prefix . $key;
603 if (!empty($values[$key])) {
604 $composeParams[$key] = $values[$key];
605 }
606 }
607
608 if (!empty($composeParams[$prefix . 'updateTemplate'])) {
609 $templateParams = array('is_active' => TRUE);
610 if ($prefix == 'SMS') {
611 $templateParams += array(
612 'msg_text' => $params['sms_body_text'],
613 'is_sms' => TRUE,
614 );
615 }
616 else {
617 $templateParams += array(
618 'msg_text' => $params['body_text'],
619 'msg_html' => $params['body_html'],
620 'msg_subject' => $params['subject'],
621 );
622 }
623 $templateParams['id'] = $values[$prefix . 'template'];
624
625 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
626 }
627
628 if (!empty($composeParams[$prefix . 'saveTemplate'])) {
629 $templateParams = array('is_active' => TRUE);
630 if ($prefix == 'SMS') {
631 $templateParams += array(
632 'msg_text' => $params['sms_body_text'],
633 'is_sms' => TRUE,
634 );
635 }
636 else {
637 $templateParams += array(
638 'msg_text' => $params['body_text'],
639 'msg_html' => $params['body_html'],
640 'msg_subject' => $params['subject'],
641 );
642 }
643 $templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName'];
644
645 $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
646 }
647
648 if ($prefix == 'SMS') {
649 if (isset($msgTemplate->id)) {
650 $params['sms_template_id'] = $msgTemplate->id;
651 }
652 else {
653 $params['sms_template_id'] = CRM_Utils_Array::value('SMStemplate', $values);
654 }
655 }
656 else {
657 if (isset($msgTemplate->id)) {
658 $params['msg_template_id'] = $msgTemplate->id;
659 }
660 else {
661 $params['msg_template_id'] = CRM_Utils_Array::value('template', $values);
662 }
663 }
664 }
665
666 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
667 $actionSchedule->copyValues($params);
668 return $actionSchedule;
669 }
670
671 /**
672 * List available tokens for this form.
673 *
674 * @return array
675 */
676 public function listTokens() {
677 $tokens = CRM_Core_SelectValues::contactTokens();
678 $tokens = array_merge(CRM_Core_SelectValues::activityTokens(), $tokens);
679 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
680 $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens);
681 $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
682 return $tokens;
683 }
684
685 }