Support custom fields CRM-12464
[civicrm-core.git] / CRM / Admin / Form / ScheduleReminders.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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-2013
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 None
54 * @access public
55 */
56 public function buildQuickForm() {
57 parent::buildQuickForm();
58 $this->_mappingID = $mappingID = NULL;
59
60 if ($this->_action & (CRM_Core_Action::DELETE)) {
61 $reminderName =
62 CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
63 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
64 if ($this->_context == 'event') {
65 $this->_eventId = CRM_Utils_Request::retrieve('eventId', 'Integer', $this);
66 }
67 $this->assign('reminderName', $reminderName);
68 return;
69 }
70 elseif ($this->_action & (CRM_Core_Action::UPDATE)) {
71 $this->_mappingID =
72 CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
73 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
74 if ($this->_context == 'event') {
75 $this->_eventId = CRM_Utils_Request::retrieve('eventId', 'Integer', $this);
76 }
77 }
78
79 if (!empty($_POST) && CRM_Utils_Array::value('entity', $_POST)) {
80 $mappingID = $_POST['entity'][0];
81 }
82 elseif ($this->_mappingID) {
83 $mappingID = $this->_mappingID;
84 }
85
86 $this->add(
87 'text',
88 'title',
89 ts('Title'),
90 array('size' => 45, 'maxlength' => 128),
91 TRUE
92 );
93
94 $selectionOptions = CRM_Core_BAO_ActionSchedule::getSelection($mappingID);
95 extract($selectionOptions);
96
97 if (empty($sel1)) {
98 CRM_Core_Error::fatal('Could not find mapping for scheduled reminders.');
99 }
100 $this->assign('entityMapping', json_encode($entityMapping));
101 $this->assign('recipientMapping', json_encode($recipientMapping));
102
103 $sel = &$this->add(
104 'hierselect',
105 'entity',
106 ts('Entity'),
107 array(
108 'name' => 'entity[0]',
109 'style' => 'vertical-align: top;',
110 ),
111 TRUE
112 );
113 $sel->setOptions(array($sel1, $sel2, $sel3));
114
115 if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
116 // make second selector a multi-select -
117 $sel->_elements[1]->setMultiple(TRUE);
118 $sel->_elements[1]->setSize(5);
119 }
120
121 if (is_a($sel->_elements[2], 'HTML_QuickForm_select')) {
122 // make third selector a multi-select -
123 $sel->_elements[2]->setMultiple(TRUE);
124 $sel->_elements[2]->setSize(5);
125 }
126
127 //get the frequency units.
128 $this->_freqUnits = array('hour' => 'hour') + CRM_Core_OptionGroup::values('recur_frequency_units');
129
130 //pass the mapping ID in UPDATE mode
131 $mappings = CRM_Core_BAO_ActionSchedule::getMapping($mappingID);
132
133 $numericOptions = CRM_Core_SelectValues::getNumericOptions(0, 30);
134
135 //reminder_interval
136 $this->add('select', 'start_action_offset', ts('When'), $numericOptions);
137
138 foreach ($this->_freqUnits as $val => $label) {
139 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
140 }
141
142 $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing'));
143
144 //reminder_frequency
145 $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
146
147 $condition = array('before' => ts('before'),
148 'after' => ts('after'),
149 );
150 //reminder_action
151 $this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
152
153 $this->add('select', 'start_action_date', ts('Date Field'), $sel4, TRUE);
154
155 $this->addElement('checkbox', 'record_activity', ts('Record activity for automated email'));
156
157 $this->addElement('checkbox', 'is_repeat', ts('Repeat'),
158 NULL, array('onclick' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);")
159 );
160
161 $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
162 $this->add('select', 'repetition_frequency_interval', ts('every'), $numericOptions);
163 $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
164 $this->add('select', 'end_frequency_interval', ts('until'), $numericOptions);
165 $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
166 $this->add('select', 'end_date', ts('Date Field'), $sel4, TRUE);
167
168 $recipient = 'activity_contacts';
169 $recipientListingOptions = array();
170
171 if ($mappingID) {
172 $recipient = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping',
173 $mappingID,
174 'entity_recipient'
175 );
176 }
177
178 $this->add('select', 'recipient', ts('Limit Recipients'), $sel5[$recipient],
179 FALSE, array('onClick' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);")
180 );
181
182 if (CRM_Utils_Array::value('is_recipient_listing', $_POST)) {
183 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($_POST['entity'][0], $_POST['recipient']);
184 }
185 elseif (CRM_Utils_Array::value('recipient_listing', $this->_values)) {
186 $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']);
187 }
188 $recipientListing = $this->add('select', 'recipient_listing', ts('Recipient Listing'), $recipientListingOptions);
189 $recipientListing->setMultiple(TRUE);
190 $this->add('hidden', 'is_recipient_listing', empty($recipientListingOptions) ? FALSE : TRUE, array('id' => 'is_recipient_listing'));
191
192 //autocomplete url
193 $dataUrl = CRM_Utils_System::url('civicrm/ajax/rest',
194 'className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&context=activity&reset=1',
195 FALSE, NULL, FALSE
196 );
197
198 $this->assign('dataUrl', $dataUrl);
199 //tokeninput url
200 $tokenUrl = CRM_Utils_System::url('civicrm/ajax/checkemail',
201 'noemail=1',
202 FALSE, NULL, FALSE
203 );
204 $this->assign('tokenUrl', $tokenUrl);
205 $this->add('text', 'recipient_manual_id', ts('Manual Recipients'));
206
207 $this->addElement('select', 'group_id', ts('Group'),
208 CRM_Core_PseudoConstant::staticGroup()
209 );
210
211 CRM_Mailing_BAO_Mailing::commonCompose($this);
212
213 $this->add('text', 'subject', ts('Subject'),
214 CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject')
215 );
216
217 $this->add('checkbox', 'is_active', ts('Send email'));
218
219 $this->addFormRule(array('CRM_Admin_Form_ScheduleReminders', 'formRule'));
220 }
221 /**
222 * global form rule
223 *
224 * @param array $fields the input form values
225 *
226 * @return true if no errors, else array of errors
227 * @access public
228 * @static
229 */
230 static function formRule($fields) {
231 $errors = array();
232 if ((array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] == 0) ||
233 (array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0)
234 ) {
235 $errors['entity'] = ts('Please select appropriate value');
236 }
237
238 if (CRM_Utils_Array::value('is_active', $fields) &&
239 CRM_Utils_System::isNull($fields['subject'])
240 ) {
241 $errors['subject'] = ts('Subject is a required field.');
242 }
243
244 if (CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
245 $errors['entity'] = ts('Please select entity value');
246 }
247
248 if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
249 if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('YmdHi00'))) {
250 $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
251 }
252 }
253
254 if (!empty($errors)) {
255 return $errors;
256 }
257
258 return empty($errors) ? TRUE : $errors;
259 }
260
261 function setDefaultValues() {
262 if ($this->_action & CRM_Core_Action::ADD) {
263 $defaults['is_active'] = 1;
264 $defaults['record_activity'] = 1;
265 }
266 else {
267 $defaults = $this->_values;
268 $entityValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
269 CRM_Utils_Array::value('entity_value', $defaults)
270 );
271 $entityStatus = explode(CRM_Core_DAO::VALUE_SEPARATOR,
272 CRM_Utils_Array::value('entity_status', $defaults)
273 );
274 $defaults['entity'][0] = CRM_Utils_Array::value('mapping_id', $defaults);
275 $defaults['entity'][1] = $entityValue;
276 $defaults['entity'][2] = $entityStatus;
277 if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $defaults)) {
278 list($date, $time) = CRM_Utils_Date::setDateDefaults($absoluteDate);
279 $defaults['absolute_date'] = $date;
280 }
281
282 if ($recipientListing = CRM_Utils_Array::value('recipient_listing', $defaults)) {
283 $defaults['recipient_listing'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
284 $recipientListing
285 );
286 }
287 $defaults['text_message'] = CRM_Utils_Array::value('body_text', $defaults);
288 $defaults['html_message'] = CRM_Utils_Array::value('body_html', $defaults);
289 $defaults['template'] = CRM_Utils_Array::value('msg_template_id', $defaults);
290 if (CRM_Utils_Array::value('group_id', $defaults)) {
291 $defaults['recipient'] = 'group';
292 }
293 elseif (CRM_Utils_Array::value('recipient_manual', $defaults)) {
294 $defaults['recipient'] = 'manual';
295 $recipients = array();
296 foreach (explode(',', $defaults['recipient_manual']) as $cid) {
297 $recipients[$cid] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
298 $cid,
299 'sort_name'
300 );
301 }
302 $this->assign('recipients', $recipients);
303 }
304 }
305
306 return $defaults;
307 }
308
309 /**
310 * Function to process the form
311 *
312 * @access public
313 *
314 * @return None
315 */
316 public function postProcess() {
317 if ($this->_action & CRM_Core_Action::DELETE) {
318 // delete reminder
319 CRM_Core_BAO_ActionSchedule::del($this->_id);
320 CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success');
321 if ($this->_context == 'event' && $this->_eventId) {
322 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
323 "reset=1&action=update&id={$this->_eventId}"
324 );
325 $session = CRM_Core_Session::singleton();
326 $session->pushUserContext($url);
327 }
328 return;
329 }
330 $values = $this->controller->exportValues($this->getName());
331
332 $keys = array(
333 'title',
334 'subject',
335 'absolute_date',
336 'group_id',
337 'record_activity'
338 );
339 foreach ($keys as $key) {
340 $params[$key] = CRM_Utils_Array::value($key, $values);
341 }
342
343 $moreKeys = array(
344 'start_action_offset', 'start_action_unit',
345 'start_action_condition', 'start_action_date',
346 'repetition_frequency_unit',
347 'repetition_frequency_interval',
348 'end_frequency_unit',
349 'end_frequency_interval',
350 'end_action', 'end_date',
351 );
352
353 if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) {
354 $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate);
355 foreach ($moreKeys as $mkey) {
356 $params[$mkey] = 'null';
357 }
358 }
359 else {
360 $params['absolute_date'] = 'null';
361 foreach ($moreKeys as $mkey) {
362 $params[$mkey] = CRM_Utils_Array::value($mkey, $values);
363 }
364 }
365
366 $params['body_text'] = CRM_Utils_Array::value('text_message', $values);
367 $params['body_html'] = CRM_Utils_Array::value('html_message', $values);
368
369 if (CRM_Utils_Array::value('recipient', $values) == 'manual') {
370 $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values);
371 $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null';
372 }
373 elseif (CRM_Utils_Array::value('recipient', $values) == 'group') {
374 $params['group_id'] = $values['group_id'];
375 $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null';
376 }
377 elseif (!CRM_Utils_System::isNull($values['recipient_listing'])) {
378 $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
379 $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
380 CRM_Utils_Array::value('recipient_listing', $values)
381 );
382 $params['group_id'] = $params['recipient_manual'] = 'null';
383 }
384 else {
385 $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
386 $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
387 }
388
389 $params['mapping_id'] = $values['entity'][0];
390 $entity_value = $values['entity'][1];
391 $entity_status = $values['entity'][2];
392
393 foreach (array(
394 'entity_value', 'entity_status') as $key) {
395 $params[$key] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $$key);
396 }
397
398 $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0);
399 $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0);
400
401 if (CRM_Utils_Array::value('is_repeat', $values) == 0) {
402 $params['repetition_frequency_unit'] = 'null';
403 $params['repetition_frequency_interval'] = 'null';
404 $params['end_frequency_unit'] = 'null';
405 $params['end_frequency_interval'] = 'null';
406 $params['end_action'] = 'null';
407 $params['end_date'] = 'null';
408 }
409
410 if ($this->_action & CRM_Core_Action::UPDATE) {
411 $params['id'] = $this->_id;
412 }
413 elseif ($this->_action & CRM_Core_Action::ADD) {
414 // we do this only once, so name never changes
415 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64);
416 }
417
418 $composeFields = array(
419 'template', 'saveTemplate',
420 'updateTemplate', 'saveTemplateName',
421 );
422 $msgTemplate = NULL;
423 //mail template is composed
424
425 $composeParams = array();
426 foreach ($composeFields as $key) {
427 if (CRM_Utils_Array::value($key, $values)) {
428 $composeParams[$key] = $values[$key];
429 }
430 }
431
432 if (CRM_Utils_Array::value('updateTemplate', $composeParams)) {
433 $templateParams = array(
434 'msg_text' => $params['body_text'],
435 'msg_html' => $params['body_html'],
436 'msg_subject' => $params['subject'],
437 'is_active' => TRUE,
438 );
439
440 $templateParams['id'] = $values['template'];
441
442 $msgTemplate = CRM_Core_BAO_MessageTemplates::add($templateParams);
443 }
444
445 if (CRM_Utils_Array::value('saveTemplate', $composeParams)) {
446 $templateParams = array(
447 'msg_text' => $params['body_text'],
448 'msg_html' => $params['body_html'],
449 'msg_subject' => $params['subject'],
450 'is_active' => TRUE,
451 );
452
453 $templateParams['msg_title'] = $composeParams['saveTemplateName'];
454
455 $msgTemplate = CRM_Core_BAO_MessageTemplates::add($templateParams);
456 }
457
458 if (isset($msgTemplate->id)) {
459 $params['msg_template_id'] = $msgTemplate->id;
460 }
461 else {
462 $params['msg_template_id'] = CRM_Utils_Array::value('template', $values);
463 }
464
465 CRM_Core_BAO_ActionSchedule::add($params, $ids);
466
467 $status = ts("Your new Reminder titled %1 has been saved.",
468 array(1 => "<strong>{$values['title']}</strong>")
469 );
470 if ($this->_action & CRM_Core_Action::UPDATE) {
471 $status = ts("Your Reminder titled %1 has been updated.",
472 array(1 => "<strong>{$values['title']}</strong>")
473 );
474
475 if ($this->_context == 'event' && $this->_eventId) {
476 $url = CRM_Utils_System::url('civicrm/event/manage/reminder',
477 "reset=1&action=update&id={$this->_eventId}"
478 );
479 $session = CRM_Core_Session::singleton();
480 $session->pushUserContext($url);
481 }
482 }
483 CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
484 }
485 }
486