3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class generates form components for Activity.
37 class CRM_Activity_Form_Activity
extends CRM_Contact_Form_Task
{
40 * The id of the object being edited / created
47 * Store activity ids when multiple activities are created.
51 public $_activityIds = [];
54 * The id of activity type.
58 public $_activityTypeId;
61 * The name of activity type.
65 public $_activityTypeName;
68 * The id of currently viewed contact.
72 public $_currentlyViewedContactId;
75 * The id of source contact and target contact.
79 protected $_sourceContactId;
80 protected $_targetContactId;
81 protected $_asigneeContactId;
88 public $_activityTypeFile;
91 * The id of the logged in user, used when add / edit
95 public $_currentUserId;
98 * The array of form field attributes.
105 * The the directory inside CRM, to include activity type file from
109 protected $_crmDir = 'Activity';
116 protected $_isSurveyActivity;
118 protected $_values = [];
120 protected $unsavedWarn = TRUE;
124 * Is it possible to create separate activities with this form?
126 * When TRUE, the form will ask whether the user wants to create separate
127 * activities (if the user has specified multiple contacts in the "with"
130 * When FALSE, the form will create one activity with all contacts together
131 * and won't ask the user anything.
133 * Note: This is a class property so that child classes can turn off this
134 * behavior (e.g. in CRM_Case_Form_Activity)
140 protected $supportsActivitySeparation = TRUE;
143 * Explicitly declare the entity api name.
147 public function getDefaultEntity() {
152 * The _fields var can be used by sub class to set/unset/edit the
153 * form fields based on their requirement
155 public function setFields() {
156 // Remove print document activity type
157 $unwanted = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, "AND v.name = 'Print PDF Letter'");
158 $activityTypes = array_diff_key(CRM_Core_PseudoConstant
::ActivityType(FALSE), $unwanted);
163 'label' => ts('Subject'),
164 'attributes' => CRM_Core_DAO
::getAttribute('CRM_Activity_DAO_Activity', 'activity_subject'),
168 'label' => ts('Duration'),
169 'attributes' => ['class' => 'four', 'min' => 1],
174 'label' => ts('Location'),
175 'attributes' => CRM_Core_DAO
::getAttribute('CRM_Activity_DAO_Activity', 'location'),
180 'label' => ts('Details'),
181 'attributes' => ['class' => 'huge'],
192 'source_contact_id' => [
193 'type' => 'entityRef',
194 'label' => ts('Added By'),
197 'target_contact_id' => [
198 'type' => 'entityRef',
199 'label' => ts('With Contact'),
200 'attributes' => ['multiple' => TRUE, 'create' => TRUE],
202 'assignee_contact_id' => [
203 'type' => 'entityRef',
204 'label' => ts('Assigned to'),
208 'api' => ['params' => ['is_deceased' => 0]],
211 'activity_date_time' => [
212 'type' => 'datepicker',
213 'label' => ts('Date'),
216 'followup_assignee_contact_id' => [
217 'type' => 'entityRef',
218 'label' => ts('Assigned to'),
222 'api' => ['params' => ['is_deceased' => 0]],
225 'followup_activity_type_id' => [
227 'label' => ts('Followup Activity'),
228 'attributes' => ['' => '- ' . ts('select activity') . ' -'] +
$activityTypes,
229 'extra' => ['class' => 'crm-select2'],
231 // Add optional 'Subject' field for the Follow-up Activiity, CRM-4491
232 'followup_activity_subject' => [
234 'label' => ts('Subject'),
235 'attributes' => CRM_Core_DAO
::getAttribute('CRM_Activity_DAO_Activity', 'subject'),
241 * Build the form object.
243 public function preProcess() {
244 CRM_Core_Form_RecurringEntity
::preProcess('civicrm_activity');
245 $this->_atypefile
= CRM_Utils_Array
::value('atypefile', $_GET);
246 $this->assign('atypefile', FALSE);
247 if ($this->_atypefile
) {
248 $this->assign('atypefile', TRUE);
251 $session = CRM_Core_Session
::singleton();
252 $this->_currentUserId
= CRM_Core_Session
::getLoggedInContactID();
254 $this->_currentlyViewedContactId
= $this->get('contactId');
255 if (!$this->_currentlyViewedContactId
) {
256 $this->_currentlyViewedContactId
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
258 $this->assign('contactId', $this->_currentlyViewedContactId
);
261 if (!isset($this->_context
)) {
262 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
263 if (CRM_Contact_Form_Search
::isSearchContext($this->_context
)) {
264 $this->_context
= 'search';
266 elseif (!in_array($this->_context
, ['dashlet', 'case', 'dashletFullscreen'])
267 && $this->_currentlyViewedContactId
269 $this->_context
= 'activity';
271 $this->_compContext
= CRM_Utils_Request
::retrieve('compContext', 'String', $this);
274 $this->assign('context', $this->_context
);
276 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String', $this);
278 if ($this->_action
& CRM_Core_Action
::DELETE
) {
279 if (!CRM_Core_Permission
::check('delete activities')) {
280 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
285 // When we come from contact search, activity id never comes.
286 // So don't try to get from object, it might gives you wrong one.
288 // if we're not adding new one, there must be an id to
289 // an activity we're trying to work on.
290 if ($this->_action
!= CRM_Core_Action
::ADD
&&
291 get_class($this->controller
) != 'CRM_Contact_Controller_Search'
293 $this->_activityId
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
296 $this->_activityTypeId
= CRM_Utils_Request
::retrieve('atype', 'Positive', $this);
297 $this->assign('atype', $this->_activityTypeId
);
299 $this->assign('activityId', $this->_activityId
);
301 // Check for required permissions, CRM-6264.
302 if ($this->_activityId
&&
303 in_array($this->_action
, [
304 CRM_Core_Action
::UPDATE
,
305 CRM_Core_Action
::VIEW
,
307 !CRM_Activity_BAO_Activity
::checkPermission($this->_activityId
, $this->_action
)
309 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
311 if (($this->_action
& CRM_Core_Action
::VIEW
) &&
312 CRM_Activity_BAO_Activity
::checkPermission($this->_activityId
, CRM_Core_Action
::UPDATE
)
314 $this->assign('permission', 'edit');
315 $this->assign('allow_edit_inbound_emails', CRM_Activity_BAO_Activity
::checkEditInboundEmailsPermissions());
318 if (!$this->_activityTypeId
&& $this->_activityId
) {
319 $this->_activityTypeId
= CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
325 // Assigning Activity type name.
326 if ($this->_activityTypeId
) {
327 $activityTName = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, 'AND v.value = ' . $this->_activityTypeId
, 'label');
328 if ($activityTName[$this->_activityTypeId
]) {
329 $this->_activityTypeName
= $activityTName[$this->_activityTypeId
];
330 $this->assign('activityTName', $activityTName[$this->_activityTypeId
]);
333 if (isset($activityTName)) {
334 $activityName = CRM_Utils_Array
::value($this->_activityTypeId
, $activityTName);
336 if ($this->_currentlyViewedContactId
) {
337 $displayName = CRM_Contact_BAO_Contact
::displayName($this->_currentlyViewedContactId
);
338 // Check if this is default domain contact CRM-10482.
339 if (CRM_Contact_BAO_Contact
::checkDomainContact($this->_currentlyViewedContactId
)) {
340 $displayName .= ' (' . ts('default organization') . ')';
342 CRM_Utils_System
::setTitle($displayName . ' - ' . $activityName);
345 CRM_Utils_System
::setTitle(ts('%1 Activity', [1 => $activityName]));
350 // Check the mode when this form is called either single or as
351 // search task action.
352 if ($this->_activityTypeId ||
353 $this->_context
== 'standalone' ||
354 $this->_currentlyViewedContactId
356 $this->_single
= TRUE;
357 $this->assign('urlPath', 'civicrm/activity');
360 // Set the appropriate action.
361 $url = CRM_Utils_System
::currentPath();
362 $urlArray = explode('/', $url);
363 $searchPath = array_pop($urlArray);
364 $searchType = 'basic';
365 $this->_action
= CRM_Core_Action
::BASIC
;
366 switch ($searchPath) {
368 $searchType = $searchPath;
369 $this->_action
= CRM_Core_Action
::BASIC
;
373 $searchType = $searchPath;
374 $this->_action
= CRM_Core_Action
::ADVANCED
;
378 $searchType = $searchPath;
379 $this->_action
= CRM_Core_Action
::PROFILE
;
383 $this->_action
= CRM_Core_Action
::COPY
;
384 $searchType = $searchPath;
388 parent
::preProcess();
389 $this->_single
= FALSE;
391 $this->assign('urlPath', "civicrm/contact/search/$searchType");
392 $this->assign('urlPathVar', "_qf_Activity_display=true&qfKey={$this->controller->_key}");
395 $this->assign('single', $this->_single
);
396 $this->assign('action', $this->_action
);
398 if ($this->_action
& CRM_Core_Action
::VIEW
) {
399 // Get the tree of custom fields.
400 $this->_groupTree
= CRM_Core_BAO_CustomGroup
::getTree('Activity', NULL,
401 $this->_activityId
, 0, $this->_activityTypeId
405 if ($this->_activityTypeId
) {
406 // Set activity type name and description to template.
407 list($this->_activityTypeName
, $activityTypeDescription) = CRM_Core_BAO_OptionValue
::getActivityTypeDetails($this->_activityTypeId
);
408 $this->assign('activityTypeName', $this->_activityTypeName
);
409 $this->assign('activityTypeDescription', $activityTypeDescription);
413 $urlParams = $urlString = NULL;
414 $qfKey = CRM_Utils_Request
::retrieve('key', 'String', $this);
416 $qfKey = CRM_Utils_Request
::retrieve('qfKey', 'String', $this);
419 // Validate the qfKey.
420 if (!CRM_Utils_Rule
::qfKey($qfKey)) {
424 if ($this->_context
== 'fulltext') {
426 $urlParams = 'force=1';
427 $urlString = 'civicrm/contact/search/custom';
428 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
430 $urlParams .= '&context=fulltext&action=view';
431 $urlString = 'civicrm/contact/view/activity';
434 $urlParams .= "$keyName=$qfKey";
436 $this->assign('searchKey', $qfKey);
438 elseif (in_array($this->_context
, [
445 $urlParams = 'reset=1';
446 $urlString = 'civicrm/dashboard';
448 elseif ($this->_context
== 'search') {
449 $urlParams = 'force=1';
451 $urlParams .= "&qfKey=$qfKey";
453 $path = CRM_Utils_System
::currentPath();
454 if ($this->_compContext
== 'advanced') {
455 $urlString = 'civicrm/contact/search/advanced';
457 elseif ($path == 'civicrm/group/search'
458 ||
$path == 'civicrm/contact/search'
459 ||
$path == 'civicrm/contact/search/advanced'
460 ||
$path == 'civicrm/contact/search/custom'
461 ||
$path == 'civicrm/group/search'
466 $urlString = 'civicrm/activity/search';
468 $this->assign('searchKey', $qfKey);
470 elseif ($this->_context
!= 'caseActivity') {
471 $urlParams = "action=browse&reset=1&cid={$this->_currentlyViewedContactId}&selectedChild=activity";
472 $urlString = 'civicrm/contact/view';
476 $session->pushUserContext(CRM_Utils_System
::url($urlString, $urlParams));
479 // hack to retrieve activity type id from post variables
480 if (!$this->_activityTypeId
) {
481 $this->_activityTypeId
= CRM_Utils_Array
::value('activity_type_id', $_POST);
484 // when custom data is included in this page
485 if (!empty($_POST['hidden_custom'])) {
486 // We need to set it in the session for the code below to work.
488 // Need to assign custom data subtype to the template.
489 $this->set('type', 'Activity');
490 $this->set('subType', $this->_activityTypeId
);
491 $this->set('entityId', $this->_activityId
);
492 CRM_Custom_Form_CustomData
::preProcess($this, NULL, $this->_activityTypeId
, 1, 'Activity', $this->_activityId
);
493 CRM_Custom_Form_CustomData
::buildQuickForm($this);
494 CRM_Custom_Form_CustomData
::setDefaultValues($this);
497 // add attachments part
498 CRM_Core_BAO_File
::buildAttachment($this, 'civicrm_activity', $this->_activityId
, NULL, TRUE);
500 // figure out the file name for activity type, if any
501 if ($this->_activityTypeId
&&
502 $this->_activityTypeFile
= CRM_Activity_BAO_Activity
::getFileForActivityTypeId($this->_activityTypeId
, $this->_crmDir
)
504 $this->assign('activityTypeFile', $this->_activityTypeFile
);
505 $this->assign('crmDir', $this->_crmDir
);
510 if ($this->_activityTypeFile
) {
511 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
512 $className::preProcess($this);
515 $this->_values
= $this->get('values');
516 if (!is_array($this->_values
)) {
518 if (isset($this->_activityId
) && $this->_activityId
) {
519 $params = ['id' => $this->_activityId
];
520 CRM_Activity_BAO_Activity
::retrieve($params, $this->_values
);
523 $this->set('values', $this->_values
);
526 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
527 // We filter out alternatives, in case this is a stored e-mail, before sending to front-end
528 if (isset($this->_values
['details'])) {
529 $this->_values
['details'] = CRM_Utils_String
::stripAlternatives($this->_values
['details']) ?
: '';
532 if ($this->_activityTypeName
=== 'Inbound Email' &&
533 !CRM_Core_Permission
::check('edit inbound email basic information and content')
535 $this->_fields
['details']['type'] = 'static';
538 CRM_Core_Form_RecurringEntity
::preProcess('civicrm_activity');
541 if ($this->_action
& CRM_Core_Action
::VIEW
) {
542 $url = CRM_Utils_System
::url(implode("/", $this->urlPath
), "reset=1&id={$this->_activityId}&action=view&cid={$this->_values['source_contact_id']}");
543 CRM_Utils_Recent
::add(CRM_Utils_Array
::value('subject', $this->_values
, ts('(no subject)')),
545 $this->_values
['id'],
547 $this->_values
['source_contact_id'],
548 $this->_values
['source_contact']
554 * Set default values for the form.
556 * For edit/view mode the default values are retrieved from the database.
560 public function setDefaultValues() {
562 $defaults = $this->_values + CRM_Core_Form_RecurringEntity
::setDefaultValues();
563 // if we're editing...
564 if (isset($this->_activityId
)) {
566 if ($this->_context
!= 'standalone') {
567 $this->assign('target_contact_value',
568 CRM_Utils_Array
::value('target_contact_value', $defaults)
570 $this->assign('assignee_contact_value',
571 CRM_Utils_Array
::value('assignee_contact_value', $defaults)
575 // Fixme: why are we getting the wrong keys from upstream?
576 $defaults['target_contact_id'] = CRM_Utils_Array
::value('target_contact', $defaults);
577 $defaults['assignee_contact_id'] = CRM_Utils_Array
::value('assignee_contact', $defaults);
579 // set default tags if exists
580 $defaults['tag'] = implode(',', CRM_Core_BAO_EntityTag
::getTag($this->_activityId
, 'civicrm_activity'));
583 // if it's a new activity, we need to set default values for associated contact fields
584 $this->_sourceContactId
= $this->_currentUserId
;
585 $this->_targetContactId
= $this->_currentlyViewedContactId
;
587 $defaults['source_contact_id'] = $this->_sourceContactId
;
588 $defaults['target_contact_id'] = $this->_targetContactId
;
591 if (empty($defaults['activity_date_time'])) {
592 $defaults['activity_date_time'] = date('Y-m-d H:i:s');
595 if ($this->_activityTypeId
) {
596 $defaults['activity_type_id'] = $this->_activityTypeId
;
599 if (!$this->_single
&& !empty($this->_contactIds
)) {
600 $defaults['target_contact_id'] = $this->_contactIds
;
603 // CRM-15472 - 50 is around the practical limit of how many items a select2 entityRef can handle
604 if ($this->_action
== CRM_Core_Action
::UPDATE
&& !empty($defaults['target_contact_id'])) {
605 $count = count(is_array($defaults['target_contact_id']) ?
$defaults['target_contact_id'] : explode(',', $defaults['target_contact_id']));
607 $this->freeze(['target_contact_id']);
611 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::RENEW
)) {
612 $this->assign('delName', CRM_Utils_Array
::value('subject', $defaults));
615 if ($this->_activityTypeFile
) {
616 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
617 $defaults +
= $className::setDefaultValues($this);
619 if (empty($defaults['priority_id'])) {
620 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
621 $defaults['priority_id'] = array_search('Normal', $priority);
623 if (empty($defaults['status_id'])) {
624 $defaults['status_id'] = CRM_Core_OptionGroup
::getDefaultValue('activity_status');
632 * @throws \CRM_Core_Exception
633 * @throws \CiviCRM_API3_Exception
635 public function buildQuickForm() {
636 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::RENEW
)) {
637 //enable form element (ActivityLinks sets this true)
638 $this->assign('suppressForm', FALSE);
640 $button = ts('Delete');
641 if ($this->_action
& CRM_Core_Action
::RENEW
) {
642 $button = ts('Restore');
648 'spacing' => ' ',
653 'name' => ts('Cancel'),
659 // Build other activity links.
660 CRM_Activity_Form_ActivityLinks
::commonBuildQuickForm($this);
662 // Enable form element (ActivityLinks sets this true).
663 $this->assign('suppressForm', FALSE);
665 $element = &$this->add('select', 'activity_type_id', ts('Activity Type'),
666 ['' => '- ' . ts('select') . ' -'] +
$this->_fields
['followup_activity_type_id']['attributes'],
668 'onchange' => "CRM.buildCustomData( 'Activity', this.value );",
669 'class' => 'crm-select2 required',
673 // Freeze for update mode.
674 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
678 // Call to RecurringEntity buildQuickForm for add/update mode.
679 if ($this->_action
& (CRM_Core_Action
::UPDATE | CRM_Core_Action
::ADD
)) {
680 CRM_Core_Form_RecurringEntity
::buildQuickForm($this);
683 foreach ($this->_fields
as $field => $values) {
684 if (!empty($this->_fields
[$field])) {
685 $attribute = CRM_Utils_Array
::value('attributes', $values);
686 $required = !empty($values['required']);
688 if ($values['type'] == 'select' && empty($attribute)) {
689 $this->addSelect($field, ['entity' => 'activity'], $required);
691 elseif ($values['type'] == 'entityRef') {
692 $this->addEntityRef($field, $values['label'], $attribute, $required);
695 $this->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array
::value('extra', $values));
700 // CRM-7362 --add campaigns.
701 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
703 // Add engagement level CRM-7775
704 $buildEngagementLevel = FALSE;
705 if (CRM_Campaign_BAO_Campaign
::isCampaignEnable() &&
706 CRM_Campaign_BAO_Campaign
::accessCampaign()
708 $buildEngagementLevel = TRUE;
709 $this->addSelect('engagement_level', ['entity' => 'activity']);
710 $this->addRule('engagement_level',
711 ts('Please enter the engagement index as a number (integers only).'),
715 $this->assign('buildEngagementLevel', $buildEngagementLevel);
717 // check for survey activity
718 $this->_isSurveyActivity
= FALSE;
720 if ($this->_activityId
&& CRM_Campaign_BAO_Campaign
::isCampaignEnable() &&
721 CRM_Campaign_BAO_Campaign
::accessCampaign()
724 $this->_isSurveyActivity
= CRM_Campaign_BAO_Survey
::isSurveyActivity($this->_activityId
);
725 if ($this->_isSurveyActivity
) {
726 $surveyId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
730 $responseOptions = CRM_Campaign_BAO_Survey
::getResponsesOptions($surveyId);
731 if ($responseOptions) {
732 $this->add('select', 'result', ts('Result'),
733 ['' => ts('- select -')] +
array_combine($responseOptions, $responseOptions)
738 $surveyTitle = CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'title');
740 $this->assign('surveyTitle', $surveyTitle);
743 $this->assign('surveyActivity', $this->_isSurveyActivity
);
745 // Add the "Activity Separation" field
746 $actionIsAdd = $this->_action
!= CRM_Core_Action
::UPDATE
;
747 $separationIsPossible = $this->supportsActivitySeparation
;
748 if ($actionIsAdd && $separationIsPossible) {
751 ts('Activity Separation'),
753 'separate' => ts('Create separate activities for each contact'),
754 'combined' => ts('Create one activity with all contacts together'),
759 $this->addRule('duration',
760 ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger'
763 // Add followup date.
764 $this->add('datepicker', 'followup_date', ts('in'));
766 // Only admins and case-workers can change the activity source
767 if (!CRM_Core_Permission
::check('administer CiviCRM') && $this->_context
!= 'caseActivity') {
768 $this->getElement('source_contact_id')->freeze();
771 //need to assign custom data type and subtype to the template
772 $this->assign('customDataType', 'Activity');
773 $this->assign('customDataSubType', $this->_activityTypeId
);
774 $this->assign('entityID', $this->_activityId
);
776 $tags = CRM_Core_BAO_Tag
::getColorTags('civicrm_activity');
779 $this->add('select2', 'tag', ts('Tags'), $tags, FALSE, [
781 'placeholder' => ts('- select -'),
786 // we need to hide activity tagset for special activities
787 $specialActivities = ['Open Case'];
789 if (!in_array($this->_activityTypeName
, $specialActivities)) {
791 $parentNames = CRM_Core_BAO_Tag
::getTagSet('civicrm_activity');
792 CRM_Core_Form_Tag
::buildQuickForm($this, $parentNames, 'civicrm_activity', $this->_activityId
);
795 // if we're viewing, we're assigning different buttons than for adding/editing
796 if ($this->_action
& CRM_Core_Action
::VIEW
) {
797 if (isset($this->_groupTree
)) {
798 CRM_Core_BAO_CustomGroup
::buildCustomDataView($this, $this->_groupTree
, FALSE, NULL, NULL, NULL, $this->_activityId
);
800 // form should be frozen for view mode
806 'name' => ts('Done'),
814 'name' => ts('Save'),
816 'submitOnce' => TRUE,
820 'name' => ts('Cancel'),
825 if ($this->_activityTypeFile
) {
826 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
828 $className::buildQuickForm($this);
829 $this->addFormRule([$className, 'formRule'], $this);
832 $this->addFormRule(['CRM_Activity_Form_Activity', 'formRule'], $this);
834 $doNotNotifyAssigneeFor = (array) Civi
::settings()
835 ->get('do_not_notify_assignees_for');
836 if (($this->_activityTypeId
&& in_array($this->_activityTypeId
, $doNotNotifyAssigneeFor)) ||
!Civi
::settings()
837 ->get('activity_assignee_notification')) {
838 $this->assign('activityAssigneeNotification', FALSE);
841 $this->assign('activityAssigneeNotification', TRUE);
843 $this->assign('doNotNotifyAssigneeFor', $doNotNotifyAssigneeFor);
849 * @param array $fields
850 * The input form values.
851 * @param array $files
852 * The uploaded files if any.
856 * true if no errors, else array of errors
858 public static function formRule($fields, $files, $self) {
859 // skip form rule if deleting
860 if (CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Delete') {
864 if ((array_key_exists('activity_type_id', $fields) ||
!$self->_single
) && empty($fields['activity_type_id'])) {
865 $errors['activity_type_id'] = ts('Activity Type is a required field');
868 if (CRM_Utils_Array
::value('activity_type_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email')
869 && CRM_Utils_Array
::value('status_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled')) {
870 $errors['status_id'] = ts('You cannot record scheduled email activity.');
872 elseif (CRM_Utils_Array
::value('activity_type_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS')
873 && CRM_Utils_Array
::value('status_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled')) {
874 $errors['status_id'] = ts('You cannot record scheduled SMS activity.');
877 if (!empty($fields['followup_activity_type_id']) && empty($fields['followup_date'])) {
878 $errors['followup_date'] = ts('Followup date is a required field.');
880 // Activity type is mandatory if subject or follow-up date is specified for an Follow-up activity, CRM-4515.
881 if ((!empty($fields['followup_activity_subject']) ||
!empty($fields['followup_date'])) && empty($fields['followup_activity_type_id'])) {
882 $errors['followup_activity_subject'] = ts('Follow-up Activity type is a required field.');
885 // Check that a value has been set for the "activity separation" field if needed
886 $separationIsPossible = $self->supportsActivitySeparation
;
887 $actionIsAdd = $self->_action
== CRM_Core_Action
::ADD
;
888 $hasMultipleTargetContacts = !empty($fields['target_contact_id']) && strpos($fields['target_contact_id'], ',') !== FALSE;
889 $separationFieldIsEmpty = empty($fields['separation']);
890 if ($separationIsPossible && $actionIsAdd && $hasMultipleTargetContacts && $separationFieldIsEmpty) {
891 $errors['separation'] = ts('Activity Separation is a required field.');
898 * Process the form submission.
901 * @param array $params
904 * @throws \CiviCRM_API3_Exception
906 public function postProcess($params = NULL) {
907 if ($this->_action
& CRM_Core_Action
::DELETE
) {
908 $deleteParams = ['id' => $this->_activityId
];
909 $moveToTrash = CRM_Case_BAO_Case
::isCaseActivity($this->_activityId
);
910 CRM_Activity_BAO_Activity
::deleteActivity($deleteParams, $moveToTrash);
912 // delete tags for the entity
914 'entity_table' => 'civicrm_activity',
915 'entity_id' => $this->_activityId
,
918 CRM_Core_BAO_EntityTag
::del($tagParams);
920 CRM_Core_Session
::setStatus(ts("Selected Activity has been deleted successfully."), ts('Record Deleted'), 'success');
924 // store the submitted values in an array
926 $params = $this->controller
->exportValues($this->_name
);
929 // Set activity type id.
930 if (empty($params['activity_type_id'])) {
931 $params['activity_type_id'] = $this->_activityTypeId
;
934 if (!empty($params['hidden_custom']) &&
935 !isset($params['custom'])
937 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
938 $this->_activityTypeId
940 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
941 CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
945 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
951 // format params as arrays
952 foreach (['target', 'assignee', 'followup_assignee'] as $name) {
953 if (!empty($params["{$name}_contact_id"])) {
954 $params["{$name}_contact_id"] = explode(',', $params["{$name}_contact_id"]);
957 $params["{$name}_contact_id"] = [];
961 // get ids for associated contacts
962 if (!$params['source_contact_id']) {
963 $params['source_contact_id'] = $this->_currentUserId
;
966 if (isset($this->_activityId
)) {
967 $params['id'] = $this->_activityId
;
970 // add attachments as needed
971 CRM_Core_BAO_File
::formatAttachment($params,
977 $params['is_multi_activity'] = CRM_Utils_Array
::value('separation', $params) == 'separate';
980 if (!empty($params['is_multi_activity']) &&
981 !CRM_Utils_Array
::crmIsEmptyArray($params['target_contact_id'])
983 $targetContacts = $params['target_contact_id'];
984 foreach ($targetContacts as $targetContactId) {
985 $params['target_contact_id'] = [$targetContactId];
987 $activity[] = $this->processActivity($params);
992 $activity = $this->processActivity($params);
995 $activityIds = empty($this->_activityIds
) ?
[$this->_activityId
] : $this->_activityIds
;
996 foreach ($activityIds as $activityId) {
997 // set params for repeat configuration in create mode
998 $params['entity_id'] = $activityId;
999 $params['entity_table'] = 'civicrm_activity';
1000 if (!empty($params['entity_id']) && !empty($params['entity_table'])) {
1001 $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity
::getParentFor($params['entity_id'], $params['entity_table']);
1002 if ($checkParentExistsForThisId) {
1003 $params['parent_entity_id'] = $checkParentExistsForThisId;
1004 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity
::getReminderDetailsByEntityId($checkParentExistsForThisId, $params['entity_table']);
1007 $params['parent_entity_id'] = $params['entity_id'];
1008 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity
::getReminderDetailsByEntityId($params['entity_id'], $params['entity_table']);
1010 if (property_exists($scheduleReminderDetails, 'id')) {
1011 $params['schedule_reminder_id'] = $scheduleReminderDetails->id
;
1014 $params['dateColumns'] = ['activity_date_time'];
1016 // Set default repetition start if it was not provided.
1017 if (empty($params['repetition_start_date'])) {
1018 $params['repetition_start_date'] = $params['activity_date_time'];
1021 // unset activity id
1022 unset($params['id']);
1025 'table' => 'civicrm_activity_contact',
1027 'activity_id' => $activityId,
1029 'linkedColumns' => ['activity_id'],
1030 'isRecurringEntityRecord' => FALSE,
1033 CRM_Core_Form_RecurringEntity
::postProcess($params, 'civicrm_activity', $linkedEntities);
1036 return ['activity' => $activity];
1040 * Process activity creation.
1042 * @param array $params
1043 * Associated array of submitted values.
1045 * @return self|null|object
1047 protected function processActivity(&$params) {
1048 $activityAssigned = [];
1049 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1050 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1051 // format assignee params
1052 if (!CRM_Utils_Array
::crmIsEmptyArray($params['assignee_contact_id'])) {
1053 //skip those assignee contacts which are already assigned
1054 //while sending a copy.CRM-4509.
1055 $activityAssigned = array_flip($params['assignee_contact_id']);
1056 if ($this->_activityId
) {
1057 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::getNames($this->_activityId
, $assigneeID);
1058 $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
1062 // call begin post process. Idea is to let injecting file do
1063 // any processing before the activity is added/updated.
1064 $this->beginPostProcess($params);
1066 $activity = CRM_Activity_BAO_Activity
::create($params);
1068 // add tags if exists
1070 if (!empty($params['tag'])) {
1071 if (!is_array($params['tag'])) {
1072 $params['tag'] = explode(',', $params['tag']);
1075 $tagParams = array_fill_keys($params['tag'], 1);
1078 // Save static tags.
1079 CRM_Core_BAO_EntityTag
::create($tagParams, 'civicrm_activity', $activity->id
);
1082 if (isset($params['activity_taglist']) && !empty($params['activity_taglist'])) {
1083 CRM_Core_Form_Tag
::postProcess($params['activity_taglist'], $activity->id
, 'civicrm_activity', $this);
1086 // call end post process. Idea is to let injecting file do any
1087 // processing needed, after the activity has been added/updated.
1088 $this->endPostProcess($params, $activity);
1091 if (!empty($params['is_multi_activity'])) {
1092 $this->_activityIds
[] = $activity->id
;
1095 $this->_activityId
= $activity->id
;
1098 // create follow up activity if needed
1099 $followupStatus = '';
1100 $followupActivity = NULL;
1101 if (!empty($params['followup_activity_type_id'])) {
1102 $followupActivity = CRM_Activity_BAO_Activity
::createFollowupActivity($activity->id
, $params);
1103 $followupStatus = ts('A followup activity has been scheduled.');
1106 // send copy to assignee contacts.CRM-4509
1109 if (Civi
::settings()->get('activity_assignee_notification')
1110 && !in_array($activity->activity_type_id
, Civi
::settings()
1111 ->get('do_not_notify_assignees_for'))) {
1112 $activityIDs = [$activity->id
];
1113 if ($followupActivity) {
1114 $activityIDs = array_merge($activityIDs, [$followupActivity->id
]);
1116 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames($activityIDs, TRUE, FALSE);
1118 if (!CRM_Utils_Array
::crmIsEmptyArray($params['assignee_contact_id'])) {
1119 $mailToContacts = [];
1121 // Build an associative array with unique email addresses.
1122 foreach ($activityAssigned as $id => $dnc) {
1123 if (isset($id) && array_key_exists($id, $assigneeContacts)) {
1124 $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
1128 $sent = CRM_Activity_BAO_Activity
::sendToAssignee($activity, $mailToContacts);
1130 $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
1134 // Also send email to follow-up activity assignees if set
1135 if ($followupActivity) {
1136 $mailToFollowupContacts = [];
1137 foreach ($assigneeContacts as $values) {
1138 if ($values['activity_id'] == $followupActivity->id
) {
1139 $mailToFollowupContacts[$values['email']] = $values;
1143 $sentFollowup = CRM_Activity_BAO_Activity
::sendToAssignee($followupActivity, $mailToFollowupContacts);
1144 if ($sentFollowup) {
1145 $mailStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
1150 // set status message
1152 if (!empty($params['subject'])) {
1153 $subject = "'" . $params['subject'] . "'";
1156 CRM_Core_Session
::setStatus(ts('Activity %1 has been saved. %2 %3',
1159 2 => $followupStatus,
1162 ), ts('Saved'), 'success');
1168 * Shorthand for getting id by display name (makes code more readable)
1169 * @param $displayName
1170 * @return null|string
1172 protected function _getIdByDisplayName($displayName) {
1173 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1181 * Shorthand for getting display name by id (makes code more readable)
1183 * @return null|string
1185 protected function _getDisplayNameById($id) {
1186 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
1194 * Let injecting activity type file do any processing.
1195 * needed, before the activity is added/updated
1197 * @param array $params
1199 public function beginPostProcess(&$params) {
1200 if ($this->_activityTypeFile
) {
1201 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
1202 $className::beginPostProcess($this, $params);
1207 * Let injecting activity type file do any processing
1208 * needed, after the activity has been added/updated
1210 * @param array $params
1213 public function endPostProcess(&$params, &$activity) {
1214 if ($this->_activityTypeFile
) {
1215 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
1216 $className::endPostProcess($this, $params, $activity);