support for multiple recurring activities
[civicrm-core.git] / CRM / Activity / Form / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for Activity
38 *
39 */
40 class CRM_Activity_Form_Activity extends CRM_Contact_Form_Task {
41
42 /**
43 * The id of the object being edited / created
44 *
45 * @var int
46 */
47 public $_activityId;
48
49 /**
50 * Store activity ids when multiple activities are created
51 *
52 * @var int
53 */
54 public $_activityIds = array();
55
56 /**
57 * The id of activity type
58 *
59 * @var int
60 */
61 public $_activityTypeId;
62
63 /**
64 * The name of activity type
65 *
66 * @var string
67 */
68 public $_activityTypeName;
69
70 /**
71 * The id of currently viewed contact
72 *
73 * @var int
74 */
75 public $_currentlyViewedContactId;
76
77 /**
78 * The id of source contact and target contact
79 *
80 * @var int
81 */
82 protected $_sourceContactId;
83 protected $_targetContactId;
84 protected $_asigneeContactId;
85
86 protected $_single;
87
88 public $_context;
89 public $_compContext;
90 public $_action;
91 public $_activityTypeFile;
92
93 /**
94 * The id of the logged in user, used when add / edit
95 *
96 * @var int
97 */
98 public $_currentUserId;
99
100 /**
101 * The array of form field attributes
102 *
103 * @var array
104 */
105 public $_fields;
106
107 /**
108 * The the directory inside CRM, to include activity type file from
109 *
110 * @var string
111 */
112 protected $_crmDir = 'Activity';
113
114 /**
115 * Survey activity
116 *
117 * @var boolean
118 */
119 protected $_isSurveyActivity;
120
121 protected $_values = array();
122
123 protected $unsavedWarn = TRUE;
124
125 /**
126 * The _fields var can be used by sub class to set/unset/edit the
127 * form fields based on their requirement
128 */
129 public function setFields() {
130 $this->_fields = array(
131 'subject' => array(
132 'type' => 'text',
133 'label' => ts('Subject'),
134 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
135 'subject'
136 ),
137 ),
138 'duration' => array(
139 'type' => 'text',
140 'label' => ts('Duration'),
141 'attributes' => array('size' => 4, 'maxlength' => 8),
142 'required' => FALSE,
143 ),
144 'location' => array(
145 'type' => 'text',
146 'label' => ts('Location'),
147 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity', 'location'),
148 'required' => FALSE,
149 ),
150 'details' => array(
151 'type' => 'wysiwyg',
152 'label' => ts('Details'),
153 // forces a smaller edit window
154 'attributes' => array('rows' => 4, 'cols' => 60),
155 'required' => FALSE,
156 ),
157 'status_id' => array(
158 'type' => 'select',
159 'required' => TRUE,
160 ),
161 'priority_id' => array(
162 'type' => 'select',
163 'required' => TRUE,
164 ),
165 'source_contact_id' => array(
166 'type' => 'entityRef',
167 'label' => ts('Added By'),
168 'required' => FALSE,
169 ),
170 'target_contact_id' => array(
171 'type' => 'entityRef',
172 'label' => ts('With Contact'),
173 'attributes' => array('multiple' => TRUE, 'create' => TRUE),
174 ),
175 'assignee_contact_id' => array(
176 'type' => 'entityRef',
177 'label' => ts('Assigned to'),
178 'attributes' => array(
179 'multiple' => TRUE,
180 'create' => TRUE,
181 'api' => array('params' => array('is_deceased' => 0)),
182 ),
183 ),
184 'followup_assignee_contact_id' => array(
185 'type' => 'entityRef',
186 'label' => ts('Assigned to'),
187 'attributes' => array(
188 'multiple' => TRUE,
189 'create' => TRUE,
190 'api' => array('params' => array('is_deceased' => 0)),
191 ),
192 ),
193 'followup_activity_type_id' => array(
194 'type' => 'select',
195 'label' => ts('Followup Activity'),
196 'attributes' => array('' => '- ' . ts('select activity') . ' -') + CRM_Core_PseudoConstant::ActivityType(FALSE),
197 'extra' => array('class' => 'crm-select2'),
198 ),
199 // Add optional 'Subject' field for the Follow-up Activiity, CRM-4491
200 'followup_activity_subject' => array(
201 'type' => 'text',
202 'label' => ts('Subject'),
203 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
204 'subject'
205 ),
206 ),
207 );
208
209 if (($this->_context == 'standalone') &&
210 ($printPDF = CRM_Utils_Array::key('Print PDF Letter', $this->_fields['followup_activity_type_id']['attributes']))
211 ) {
212 unset($this->_fields['followup_activity_type_id']['attributes'][$printPDF]);
213 }
214 }
215
216 /**
217 * Build the form object
218 *
219 * @return void
220 */
221 public function preProcess() {
222 $this->_cdType = CRM_Utils_Array::value('type', $_GET);
223 $this->assign('cdType', FALSE);
224 if ($this->_cdType) {
225 $this->assign('cdType', TRUE);
226 return CRM_Custom_Form_CustomData::preProcess($this);
227 }
228 CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
229 $this->_atypefile = CRM_Utils_Array::value('atypefile', $_GET);
230 $this->assign('atypefile', FALSE);
231 if ($this->_atypefile) {
232 $this->assign('atypefile', TRUE);
233 }
234
235 $session = CRM_Core_Session::singleton();
236 $this->_currentUserId = $session->get('userID');
237
238 $this->_currentlyViewedContactId = $this->get('contactId');
239 if (!$this->_currentlyViewedContactId) {
240 $this->_currentlyViewedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
241 }
242 $this->assign('contactId', $this->_currentlyViewedContactId);
243
244 //give the context.
245 if (!isset($this->_context)) {
246 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
247 if (CRM_Contact_Form_Search::isSearchContext($this->_context)) {
248 $this->_context = 'search';
249 }
250 elseif (!in_array($this->_context, array('dashlet', 'dashletFullscreen'))
251 && $this->_currentlyViewedContactId
252 ) {
253 $this->_context = 'activity';
254 }
255 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
256 }
257
258 $this->assign('context', $this->_context);
259
260 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this);
261
262 if ($this->_action & CRM_Core_Action::DELETE) {
263 if (!CRM_Core_Permission::check('delete activities')) {
264 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
265 }
266 }
267
268 //CRM-6957
269 //when we come from contact search, activity id never comes.
270 //so don't try to get from object, it might gives you wrong one.
271
272 // if we're not adding new one, there must be an id to
273 // an activity we're trying to work on.
274 if ($this->_action != CRM_Core_Action::ADD &&
275 get_class($this->controller) != 'CRM_Contact_Controller_Search'
276 ) {
277 $this->_activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
278 }
279
280 $this->_activityTypeId = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
281 $this->assign('atype', $this->_activityTypeId);
282
283 $this->assign('activityId', $this->_activityId);
284
285 //check for required permissions, CRM-6264
286 if ($this->_activityId &&
287 in_array($this->_action, array(
288 CRM_Core_Action::UPDATE,
289 CRM_Core_Action::VIEW,
290 )) &&
291 !CRM_Activity_BAO_Activity::checkPermission($this->_activityId, $this->_action)
292 ) {
293 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
294 }
295 if (($this->_action & CRM_Core_Action::VIEW) &&
296 CRM_Activity_BAO_Activity::checkPermission($this->_activityId, CRM_Core_Action::UPDATE)
297 ) {
298 $this->assign('permission', 'edit');
299 }
300
301 if (!$this->_activityTypeId && $this->_activityId) {
302 $this->_activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
303 $this->_activityId,
304 'activity_type_id'
305 );
306 }
307
308 //Assigning Activity type name
309 if ($this->_activityTypeId) {
310 $activityTName = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, 'AND v.value = ' . $this->_activityTypeId, 'name');
311 if ($activityTName[$this->_activityTypeId]) {
312 $this->_activityTypeName = $activityTName[$this->_activityTypeId];
313 $this->assign('activityTName', $activityTName[$this->_activityTypeId]);
314 }
315 }
316
317 // Set title
318 if (isset($activityTName)) {
319 $activityName = CRM_Utils_Array::value($this->_activityTypeId, $activityTName);
320 $this->assign('pageTitle', ts('%1 Activity', array(1 => $activityName)));
321
322 if ($this->_currentlyViewedContactId) {
323 $displayName = CRM_Contact_BAO_Contact::displayName($this->_currentlyViewedContactId);
324 // Check if this is default domain contact CRM-10482
325 if (CRM_Contact_BAO_Contact::checkDomainContact($this->_currentlyViewedContactId)) {
326 $displayName .= ' (' . ts('default organization') . ')';
327 }
328 CRM_Utils_System::setTitle($displayName . ' - ' . $activityName);
329 }
330 else {
331 CRM_Utils_System::setTitle(ts('%1 Activity', array(1 => $activityName)));
332 }
333 }
334
335 //check the mode when this form is called either single or as
336 //search task action
337 if ($this->_activityTypeId ||
338 $this->_context == 'standalone' ||
339 $this->_currentlyViewedContactId
340 ) {
341 $this->_single = TRUE;
342 $this->assign('urlPath', 'civicrm/activity');
343 }
344 else {
345 //set the appropriate action
346 $url = CRM_Utils_System::currentPath();
347 $urlArray = explode('/', $url);
348 $searchPath = array_pop($urlArray);
349 $searchType = 'basic';
350 $this->_action = CRM_Core_Action::BASIC;
351 switch ($searchPath) {
352 case 'basic':
353 $searchType = $searchPath;
354 $this->_action = CRM_Core_Action::BASIC;
355 break;
356
357 case 'advanced':
358 $searchType = $searchPath;
359 $this->_action = CRM_Core_Action::ADVANCED;
360 break;
361
362 case 'builder':
363 $searchType = $searchPath;
364 $this->_action = CRM_Core_Action::PROFILE;
365 break;
366
367 case 'custom':
368 $this->_action = CRM_Core_Action::COPY;
369 $searchType = $searchPath;
370 break;
371 }
372
373 parent::preProcess();
374 $this->_single = FALSE;
375
376 $this->assign('urlPath', "civicrm/contact/search/$searchType");
377 $this->assign('urlPathVar', "_qf_Activity_display=true&qfKey={$this->controller->_key}");
378 }
379
380 $this->assign('single', $this->_single);
381 $this->assign('action', $this->_action);
382
383 if ($this->_action & CRM_Core_Action::VIEW) {
384 // get the tree of custom fields
385 $this->_groupTree = &CRM_Core_BAO_CustomGroup::getTree('Activity', $this,
386 $this->_activityId, 0, $this->_activityTypeId
387 );
388 }
389
390 if ($this->_activityTypeId) {
391 //set activity type name and description to template
392 list($this->_activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($this->_activityTypeId);
393 $this->assign('activityTypeName', $this->_activityTypeName);
394 $this->assign('activityTypeDescription', $activityTypeDescription);
395 }
396
397 // set user context
398 $urlParams = $urlString = NULL;
399 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
400 if (!$qfKey) {
401 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
402 }
403
404 //validate the qfKey
405 if (!CRM_Utils_Rule::qfKey($qfKey)) {
406 $qfKey = NULL;
407 }
408
409 if ($this->_context == 'fulltext') {
410 $keyName = '&qfKey';
411 $urlParams = 'force=1';
412 $urlString = 'civicrm/contact/search/custom';
413 if ($this->_action == CRM_Core_Action::UPDATE) {
414 $keyName = '&key';
415 $urlParams .= '&context=fulltext&action=view';
416 $urlString = 'civicrm/contact/view/activity';
417 }
418 if ($qfKey) {
419 $urlParams .= "$keyName=$qfKey";
420 }
421 $this->assign('searchKey', $qfKey);
422 }
423 elseif (in_array($this->_context, array(
424 'standalone',
425 'home',
426 'dashlet',
427 'dashletFullscreen',
428 ))
429 ) {
430 $urlParams = 'reset=1';
431 $urlString = 'civicrm/dashboard';
432 }
433 elseif ($this->_context == 'search') {
434 $urlParams = 'force=1';
435 if ($qfKey) {
436 $urlParams .= "&qfKey=$qfKey";
437 }
438 $path = CRM_Utils_System::currentPath();
439 if ($this->_compContext == 'advanced') {
440 $urlString = 'civicrm/contact/search/advanced';
441 }
442 elseif ($path == 'civicrm/group/search'
443 || $path == 'civicrm/contact/search'
444 || $path == 'civicrm/contact/search/advanced'
445 || $path == 'civicrm/contact/search/custom'
446 || $path == 'civicrm/group/search'
447 ) {
448 $urlString = $path;
449 }
450 else {
451 $urlString = 'civicrm/activity/search';
452 }
453 $this->assign('searchKey', $qfKey);
454 }
455 elseif ($this->_context != 'caseActivity') {
456 $urlParams = "action=browse&reset=1&cid={$this->_currentlyViewedContactId}&selectedChild=activity";
457 $urlString = 'civicrm/contact/view';
458 }
459
460 if ($urlString) {
461 $session->pushUserContext(CRM_Utils_System::url($urlString, $urlParams));
462 }
463
464 // hack to retrieve activity type id from post variables
465 if (!$this->_activityTypeId) {
466 $this->_activityTypeId = CRM_Utils_Array::value('activity_type_id', $_POST);
467 }
468
469 // when custom data is included in this page
470 if (!empty($_POST['hidden_custom'])) {
471 // we need to set it in the session for the below code to work
472 // CRM-3014
473 //need to assign custom data subtype to the template
474 $this->set('type', 'Activity');
475 $this->set('subType', $this->_activityTypeId);
476 $this->set('entityId', $this->_activityId);
477 CRM_Custom_Form_CustomData::preProcess($this);
478 CRM_Custom_Form_CustomData::buildQuickForm($this);
479 CRM_Custom_Form_CustomData::setDefaultValues($this);
480 }
481
482 // add attachments part
483 CRM_Core_BAO_File::buildAttachment($this, 'civicrm_activity', $this->_activityId, NULL, TRUE);
484
485 // figure out the file name for activity type, if any
486 if ($this->_activityTypeId &&
487 $this->_activityTypeFile = CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, $this->_crmDir)
488 ) {
489 $this->assign('activityTypeFile', $this->_activityTypeFile);
490 $this->assign('crmDir', $this->_crmDir);
491 }
492
493 $this->setFields();
494
495 if ($this->_activityTypeFile) {
496 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
497 $className::preProcess($this);
498 }
499
500 $this->_values = $this->get('values');
501 if (!is_array($this->_values)) {
502 $this->_values = array();
503 if (isset($this->_activityId) && $this->_activityId) {
504 $params = array('id' => $this->_activityId);
505 CRM_Activity_BAO_Activity::retrieve($params, $this->_values);
506 }
507 $this->set('values', $this->_values);
508 }
509
510 if ($this->_action & CRM_Core_Action::UPDATE) {
511 CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
512 }
513 }
514
515 /**
516 * Set default values for the form. For edit/view mode
517 * the default values are retrieved from the database
518 *
519 *
520 * @return void
521 */
522 public function setDefaultValues() {
523 if ($this->_cdType) {
524 return CRM_Custom_Form_CustomData::setDefaultValues($this);
525 }
526
527 $defaults = $this->_values;
528 // if we're editing...
529 if (isset($this->_activityId)) {
530 if (empty($defaults['activity_date_time'])) {
531 list($defaults['activity_date_time'], $defaults['activity_date_time_time']) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
532 }
533 elseif ($this->_action & CRM_Core_Action::UPDATE) {
534 $this->assign('current_activity_date_time', $defaults['activity_date_time']);
535 list($defaults['activity_date_time'],
536 $defaults['activity_date_time_time']
537 ) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
538 list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
539 $recurringEntityDefaults = array();
540 $recurringEntityDefaults = CRM_Core_Form_RecurringEntity::setDefaultValues();
541 $defaults = array_merge($defaults, $recurringEntityDefaults);
542 }
543
544 if ($this->_context != 'standalone') {
545 $this->assign('target_contact_value',
546 CRM_Utils_Array::value('target_contact_value', $defaults)
547 );
548 $this->assign('assignee_contact_value',
549 CRM_Utils_Array::value('assignee_contact_value', $defaults)
550 );
551 }
552
553 // Fixme: why are we getting the wrong keys from upstream?
554 $defaults['target_contact_id'] = CRM_Utils_Array::value('target_contact', $defaults);
555 $defaults['assignee_contact_id'] = CRM_Utils_Array::value('assignee_contact', $defaults);
556
557 // set default tags if exists
558 $defaults['tag'] = CRM_Core_BAO_EntityTag::getTag($this->_activityId, 'civicrm_activity');
559 }
560 else {
561 // if it's a new activity, we need to set default values for associated contact fields
562 $this->_sourceContactId = $this->_currentUserId;
563 $this->_targetContactId = $this->_currentlyViewedContactId;
564
565 $defaults['source_contact_id'] = $this->_sourceContactId;
566 $defaults['target_contact_id'] = $this->_targetContactId;
567
568 list($defaults['activity_date_time'], $defaults['activity_date_time_time'])
569 = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
570 }
571
572 if ($this->_activityTypeId) {
573 $defaults['activity_type_id'] = $this->_activityTypeId;
574 }
575
576 if (!$this->_single && !empty($this->_contactIds)) {
577 $defaults['target_contact_id'] = $this->_contactIds;
578 }
579
580 // CRM-15472 - 50 is around the practial limit of how many items a select2 entityRef can handle
581 if (!empty($defaults['target_contact_id'])) {
582 $count = count(is_array($defaults['target_contact_id']) ? $defaults['target_contact_id'] : explode(',', $defaults['target_contact_id']));
583 if ($count > 50) {
584 $this->freeze(array('target_contact_id'));
585 }
586 }
587
588 if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) {
589 $this->assign('delName', CRM_Utils_Array::value('subject', $defaults));
590 }
591
592 if ($this->_activityTypeFile) {
593 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
594 $defaults += $className::setDefaultValues($this);
595 }
596 if (empty($defaults['priority_id'])) {
597 $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
598 $defaults['priority_id'] = array_search('Normal', $priority);
599 }
600 if (empty($defaults['status_id'])) {
601 $defaults['status_id'] = CRM_Core_OptionGroup::getDefaultValue('activity_status');
602 }
603 return $defaults;
604 }
605
606 public function buildQuickForm() {
607 if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) {
608 //enable form element (ActivityLinks sets this true)
609 $this->assign('suppressForm', FALSE);
610
611 $button = ts('Delete');
612 if ($this->_action & CRM_Core_Action::RENEW) {
613 $button = ts('Restore');
614 }
615 $this->addButtons(array(
616 array(
617 'type' => 'next',
618 'name' => $button,
619 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
620 'isDefault' => TRUE,
621 ),
622 array(
623 'type' => 'cancel',
624 'name' => ts('Cancel'),
625 ),
626 ));
627 return;
628 }
629
630 if ($this->_cdType) {
631 return CRM_Custom_Form_CustomData::buildQuickForm($this);
632 }
633
634 //build other activity links
635 CRM_Activity_Form_ActivityLinks::commonBuildQuickForm($this);
636
637 //enable form element (ActivityLinks sets this true)
638 $this->assign('suppressForm', FALSE);
639
640 $element = &$this->add('select', 'activity_type_id', ts('Activity Type'),
641 $this->_fields['followup_activity_type_id']['attributes'],
642 FALSE, array(
643 'onchange' => "CRM.buildCustomData( 'Activity', this.value );",
644 'class' => 'crm-select2',
645 )
646 );
647
648 //freeze for update mode.
649 if ($this->_action & CRM_Core_Action::UPDATE) {
650 $element->freeze();
651 }
652
653 //Call to RecurringEntity buildQuickForm for add/update mode
654 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
655 CRM_Core_Form_RecurringEntity::buildQuickForm($this);
656 }
657
658 foreach ($this->_fields as $field => $values) {
659 if (!empty($this->_fields[$field])) {
660 $attribute = CRM_Utils_Array::value('attributes', $values);
661 $required = !empty($values['required']);
662
663 if ($values['type'] == 'wysiwyg') {
664 $this->addWysiwyg($field, $values['label'], $attribute, $required);
665 }
666 elseif ($values['type'] == 'select' && empty($attribute)) {
667 $this->addSelect($field, array('entity' => 'activity'), $required);
668 }
669 elseif ($values['type'] == 'entityRef') {
670 $this->addEntityRef($field, $values['label'], $attribute, $required);
671 }
672 else {
673 $this->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array::value('extra', $values));
674 }
675 }
676 }
677
678 //CRM-7362 --add campaigns.
679 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
680
681 //add engagement level CRM-7775
682 $buildEngagementLevel = FALSE;
683 if (CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
684 CRM_Campaign_BAO_Campaign::accessCampaign()
685 ) {
686 $buildEngagementLevel = TRUE;
687 $this->addSelect('engagement_level', array('entity' => 'activity'));
688 $this->addRule('engagement_level',
689 ts('Please enter the engagement index as a number (integers only).'),
690 'positiveInteger'
691 );
692 }
693 $this->assign('buildEngagementLevel', $buildEngagementLevel);
694
695 // check for survey activity
696 $this->_isSurveyActivity = FALSE;
697
698 if ($this->_activityId && CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
699 CRM_Campaign_BAO_Campaign::accessCampaign()
700 ) {
701
702 $this->_isSurveyActivity = CRM_Campaign_BAO_Survey::isSurveyActivity($this->_activityId);
703 if ($this->_isSurveyActivity) {
704 $surveyId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
705 $this->_activityId,
706 'source_record_id'
707 );
708 $responseOptions = CRM_Campaign_BAO_Survey::getResponsesOptions($surveyId);
709 if ($responseOptions) {
710 $this->add('select', 'result', ts('Result'),
711 array('' => ts('- select -')) + array_combine($responseOptions, $responseOptions)
712 );
713 }
714 $surveyTitle = NULL;
715 if ($surveyId) {
716 $surveyTitle = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'title');
717 }
718 $this->assign('surveyTitle', $surveyTitle);
719 }
720 }
721 $this->assign('surveyActivity', $this->_isSurveyActivity);
722
723 // this option should be available only during add mode
724 if ($this->_action != CRM_Core_Action::UPDATE) {
725 $this->add('advcheckbox', 'is_multi_activity', ts('Create a separate activity for each contact.'));
726 }
727
728 $this->addRule('duration',
729 ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger'
730 );
731 $this->addDateTime('activity_date_time', ts('Date'), TRUE, array('formatType' => 'activityDateTime'));
732
733 //add followup date
734 $this->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
735
736 // Only admins and case-workers can change the activity source
737 if (!CRM_Core_Permission::check('administer CiviCRM') && $this->_context != 'caseActivity') {
738 $this->getElement('source_contact_id')->freeze();
739 }
740
741 //need to assign custom data type and subtype to the template
742 $this->assign('customDataType', 'Activity');
743 $this->assign('customDataSubType', $this->_activityTypeId);
744 $this->assign('entityID', $this->_activityId);
745
746 CRM_Core_BAO_Tag::getTags('civicrm_activity', $tags, NULL,
747 '&nbsp;&nbsp;', TRUE);
748
749 if (!empty($tags)) {
750 $this->add('select', 'tag', ts('Tags'), $tags, FALSE,
751 array('id' => 'tags', 'multiple' => 'multiple', 'class' => 'crm-select2 huge')
752 );
753 }
754
755 // we need to hide activity tagset for special activities
756 $specialActivities = array('Open Case');
757
758 if (!in_array($this->_activityTypeName, $specialActivities)) {
759 // build tag widget
760 $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
761 CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', $this->_activityId);
762 }
763
764 // if we're viewing, we're assigning different buttons than for adding/editing
765 if ($this->_action & CRM_Core_Action::VIEW) {
766 if (isset($this->_groupTree)) {
767 CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $this->_groupTree);
768 }
769 // form should be frozen for view mode
770 $this->freeze();
771
772 $buttons = array();
773 $buttons[] = array(
774 'type' => 'cancel',
775 'name' => ts('Done'),
776 );
777 $this->addButtons($buttons);
778 }
779 else {
780 $message = array(
781 'completed' => ts('Are you sure? This is a COMPLETED activity with the DATE in the FUTURE. Click Cancel to change the date / status. Otherwise, click OK to save.'),
782 'scheduled' => ts('Are you sure? This is a SCHEDULED activity with the DATE in the PAST. Click Cancel to change the date / status. Otherwise, click OK to save.'),
783 );
784 $js = array('onclick' => "return activityStatus(" . json_encode($message) . ");");
785 $this->addButtons(array(
786 array(
787 'type' => 'upload',
788 'name' => ts('Save'),
789 'js' => $js,
790 'isDefault' => TRUE,
791 ),
792 array(
793 'type' => 'cancel',
794 'name' => ts('Cancel'),
795 ),
796 )
797 );
798 }
799
800 if ($this->_activityTypeFile) {
801 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
802
803 $className::buildQuickForm($this);
804 $this->addFormRule(array($className, 'formRule'), $this);
805 }
806
807 $this->addFormRule(array('CRM_Activity_Form_Activity', 'formRule'), $this);
808
809 if (CRM_Core_BAO_Setting::getItem(
810 CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
811 'activity_assignee_notification'
812 )
813 ) {
814 $this->assign('activityAssigneeNotification', TRUE);
815 }
816 else {
817 $this->assign('activityAssigneeNotification', FALSE);
818 }
819 }
820
821 /**
822 * Global form rule
823 *
824 * @param array $fields
825 * The input form values.
826 * @param array $files
827 * The uploaded files if any.
828 * @param $self
829 *
830 * @return bool|array
831 * true if no errors, else array of errors
832 */
833 public static function formRule($fields, $files, $self) {
834 // skip form rule if deleting
835 if (CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Delete') {
836 return TRUE;
837 }
838 $errors = array();
839 if (!$self->_single && !$fields['activity_type_id']) {
840 $errors['activity_type_id'] = ts('Activity Type is a required field');
841 }
842
843 //Activity type is mandatory if creating new activity, CRM-4515
844 if (array_key_exists('activity_type_id', $fields) && empty($fields['activity_type_id'])) {
845 $errors['activity_type_id'] = ts('Activity Type is required field.');
846 }
847
848 if (CRM_Utils_Array::value('activity_type_id', $fields) == 3 &&
849 CRM_Utils_Array::value('status_id', $fields) == 1
850 ) {
851 $errors['status_id'] = ts('You cannot record scheduled email activity.');
852 }
853 elseif (CRM_Utils_Array::value('activity_type_id', $fields) == 4 &&
854 CRM_Utils_Array::value('status_id', $fields) == 1
855 ) {
856 $errors['status_id'] = ts('You cannot record scheduled SMS activity.');
857 }
858
859 if (!empty($fields['followup_activity_type_id']) && empty($fields['followup_date'])) {
860 $errors['followup_date_time'] = ts('Followup date is a required field.');
861 }
862 //Activity type is mandatory if subject or follow-up date is specified for an Follow-up activity, CRM-4515
863 if ((!empty($fields['followup_activity_subject']) || !empty($fields['followup_date'])) && empty($fields['followup_activity_type_id'])) {
864 $errors['followup_activity_subject'] = ts('Follow-up Activity type is a required field.');
865 }
866 return $errors;
867 }
868
869 /**
870 * Process the form submission
871 *
872 *
873 * @param array $params
874 * @return array|null
875 */
876 public function postProcess($params = NULL) {
877 if ($this->_action & CRM_Core_Action::DELETE) {
878 $deleteParams = array('id' => $this->_activityId);
879 $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($this->_activityId);
880 CRM_Activity_BAO_Activity::deleteActivity($deleteParams, $moveToTrash);
881
882 // delete tags for the entity
883 $tagParams = array(
884 'entity_table' => 'civicrm_activity',
885 'entity_id' => $this->_activityId,
886 );
887
888 CRM_Core_BAO_EntityTag::del($tagParams);
889
890 CRM_Core_Session::setStatus(ts("Selected Activity has been deleted successfully."), ts('Record Deleted'), 'success');
891 return NULL;
892 }
893
894 // store the submitted values in an array
895 if (!$params) {
896 $params = $this->controller->exportValues($this->_name);
897 }
898
899 //set activity type id
900 if (empty($params['activity_type_id'])) {
901 $params['activity_type_id'] = $this->_activityTypeId;
902 }
903
904 if (!empty($params['hidden_custom']) &&
905 !isset($params['custom'])
906 ) {
907 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
908 $this->_activityTypeId
909 );
910 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
911 CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
912 NULL, NULL, TRUE
913 )
914 );
915 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
916 $customFields,
917 $this->_activityId,
918 'Activity'
919 );
920 }
921
922 // store the date with proper format
923 $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
924
925 // format params as arrays
926 foreach (array('target', 'assignee', 'followup_assignee') as $name) {
927 if (!empty($params["{$name}_contact_id"])) {
928 $params["{$name}_contact_id"] = explode(',', $params["{$name}_contact_id"]);
929 }
930 else {
931 $params["{$name}_contact_id"] = array();
932 }
933 }
934
935 // get ids for associated contacts
936 if (!$params['source_contact_id']) {
937 $params['source_contact_id'] = $this->_currentUserId;
938 }
939
940 if (isset($this->_activityId)) {
941 $params['id'] = $this->_activityId;
942 }
943
944 // add attachments as needed
945 CRM_Core_BAO_File::formatAttachment($params,
946 $params,
947 'civicrm_activity',
948 $this->_activityId
949 );
950
951 $activity = array();
952 if (!empty($params['is_multi_activity']) &&
953 !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])
954 ) {
955 $targetContacts = $params['target_contact_id'];
956 foreach ($targetContacts as $targetContactId) {
957 $params['target_contact_id'] = array($targetContactId);
958 // save activity
959 $activity[] = $this->processActivity($params);
960 }
961 }
962 else {
963 // save activity
964 $activity = $this->processActivity($params);
965 }
966
967 $activityIds = empty($this->_activityIds) ? array($this->_activityId) : $this->_activityIds;
968 foreach ($activityIds as $activityId) {
969 // set params for repeat configuration in create mode
970 $params['entity_id'] = $activityId;
971 $params['entity_table'] = 'civicrm_activity';
972 $scheduleReminderDetails = array();
973 if (!empty($params['entity_id']) && !empty($params['entity_table'])) {
974 $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($params['entity_id'], $params['entity_table']);
975 if ($checkParentExistsForThisId) {
976 $params['parent_entity_id'] = $checkParentExistsForThisId;
977 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $params['entity_table']);
978 }
979 else {
980 $params['parent_entity_id'] = $params['entity_id'];
981 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($params['entity_id'], $params['entity_table']);
982 }
983 if (property_exists($scheduleReminderDetails, 'id')) {
984 $params['schedule_reminder_id'] = $scheduleReminderDetails->id;
985 }
986 }
987 $params['dateColumns'] = array('activity_date_time');
988
989 // unset activity id
990 unset($params['id']);
991 $linkedEntities = array(
992 array(
993 'table' => 'civicrm_activity_contact',
994 'findCriteria' => array(
995 'activity_id' => $activityId,
996 ),
997 'linkedColumns' => array('activity_id'),
998 'isRecurringEntityRecord' => FALSE,
999 ),
1000 );
1001 CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_activity', $linkedEntities);
1002 }
1003
1004 return array('activity' => $activity);
1005 }
1006
1007 /**
1008 * Process activity creation
1009 *
1010 * @param array $params
1011 * Associated array of submitted values.
1012 *
1013 * @return self|null|object
1014 */
1015 protected function processActivity(&$params) {
1016 $activityAssigned = array();
1017 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1018 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1019 // format assignee params
1020 if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
1021 //skip those assignee contacts which are already assigned
1022 //while sending a copy.CRM-4509.
1023 $activityAssigned = array_flip($params['assignee_contact_id']);
1024 if ($this->_activityId) {
1025 $assigneeContacts = CRM_Activity_BAO_ActivityContact::getNames($this->_activityId, $assigneeID);
1026 $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
1027 }
1028 }
1029
1030 // call begin post process. Idea is to let injecting file do
1031 // any processing before the activity is added/updated.
1032 $this->beginPostProcess($params);
1033
1034 $activity = CRM_Activity_BAO_Activity::create($params);
1035
1036 // add tags if exists
1037 $tagParams = array();
1038 if (!empty($params['tag'])) {
1039 foreach ($params['tag'] as $tag) {
1040 $tagParams[$tag] = 1;
1041 }
1042 }
1043
1044 //save static tags
1045 CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);
1046
1047 //save free tags
1048 if (isset($params['activity_taglist']) && !empty($params['activity_taglist'])) {
1049 CRM_Core_Form_Tag::postProcess($params['activity_taglist'], $activity->id, 'civicrm_activity', $this);
1050 }
1051
1052 // call end post process. Idea is to let injecting file do any
1053 // processing needed, after the activity has been added/updated.
1054 $this->endPostProcess($params, $activity);
1055
1056 // CRM-9590
1057 if (!empty($params['is_multi_activity'])) {
1058 $this->_activityIds[] = $activity->id;
1059 }
1060 else {
1061 $this->_activityId = $activity->id;
1062 }
1063
1064 // create follow up activity if needed
1065 $followupStatus = '';
1066 $followupActivity = NULL;
1067 if (!empty($params['followup_activity_type_id'])) {
1068 $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
1069 $followupStatus = ts('A followup activity has been scheduled.');
1070 }
1071
1072 // send copy to assignee contacts.CRM-4509
1073 $mailStatus = '';
1074
1075 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1076 'activity_assignee_notification')
1077 ) {
1078 $activityIDs = array($activity->id);
1079 if ($followupActivity) {
1080 $activityIDs = array_merge($activityIDs, array($followupActivity->id));
1081 }
1082 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityIDs, TRUE, FALSE);
1083
1084 if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
1085 $mailToContacts = array();
1086
1087 //build an associative array with unique email addresses.
1088 foreach ($activityAssigned as $id => $dnc) {
1089 if (isset($id) && array_key_exists($id, $assigneeContacts)) {
1090 $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
1091 }
1092 }
1093
1094 if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
1095 //include attachments while sending a copy of activity.
1096 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
1097
1098 $ics = new CRM_Activity_BAO_ICalendar($activity);
1099 $ics->addAttachment($attachments, $mailToContacts);
1100
1101 // CRM-8400 add param with _currentlyViewedContactId for URL link in mail
1102 CRM_Case_BAO_Case::sendActivityCopy(NULL, $activity->id, $mailToContacts, $attachments, NULL);
1103
1104 $ics->cleanup();
1105
1106 $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
1107 }
1108 }
1109
1110 // Also send email to follow-up activity assignees if set
1111 if ($followupActivity) {
1112 $mailToFollowupContacts = array();
1113 foreach ($assigneeContacts as $values) {
1114 if ($values['activity_id'] == $followupActivity->id) {
1115 $mailToFollowupContacts[$values['email']] = $values;
1116 }
1117 }
1118
1119 if (!CRM_Utils_array::crmIsEmptyArray($mailToFollowupContacts)) {
1120 $ics = new CRM_Activity_BAO_ICalendar($followupActivity);
1121 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $followupActivity->id);
1122 $ics->addAttachment($attachments, $mailToFollowupContacts);
1123
1124 CRM_Case_BAO_Case::sendActivityCopy(NULL, $followupActivity->id, $mailToFollowupContacts, $attachments, NULL);
1125
1126 $ics->cleanup();
1127
1128 $mailStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
1129 }
1130 }
1131 }
1132
1133 // set status message
1134 $subject = '';
1135 if (!empty($params['subject'])) {
1136 $subject = "'" . $params['subject'] . "'";
1137 }
1138
1139 CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2 %3',
1140 array(
1141 1 => $subject,
1142 2 => $followupStatus,
1143 3 => $mailStatus,
1144 )
1145 ), ts('Saved'), 'success');
1146
1147 return $activity;
1148 }
1149
1150 /**
1151 * Shorthand for getting id by display name (makes code more readable)
1152 * @param $displayName
1153 * @return null|string
1154 */
1155 protected function _getIdByDisplayName($displayName) {
1156 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1157 $displayName,
1158 'id',
1159 'sort_name'
1160 );
1161 }
1162
1163 /**
1164 * Shorthand for getting display name by id (makes code more readable)
1165 * @param $id
1166 * @return null|string
1167 */
1168 protected function _getDisplayNameById($id) {
1169 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1170 $id,
1171 'sort_name',
1172 'id'
1173 );
1174 }
1175
1176 /**
1177 * Let injecting activity type file do any processing
1178 * needed, before the activity is added/updated
1179 *
1180 * @param array $params
1181 */
1182 public function beginPostProcess(&$params) {
1183 if ($this->_activityTypeFile) {
1184 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
1185 $className::beginPostProcess($this, $params);
1186 }
1187 }
1188
1189 /**
1190 * Let injecting activity type file do any processing
1191 * needed, after the activity has been added/updated
1192 *
1193 * @param array $params
1194 * @param $activity
1195 */
1196 public function endPostProcess(&$params, &$activity) {
1197 if ($this->_activityTypeFile) {
1198 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
1199 $className::endPostProcess($this, $params, $activity);
1200 }
1201 }
1202
1203 }