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