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