Merge pull request #13003 from agh1/obsoleteIcons
[civicrm-core.git] / CRM / Activity / Form / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33
34 /**
35 * This class generates form components for Activity.
36 */
37 class 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', 'Alphanumeric', $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 $this->assign('allow_edit_inbound_emails', CRM_Activity_BAO_Activity::checkEditInboundEmailsPermissions());
312 }
313
314 if (!$this->_activityTypeId && $this->_activityId) {
315 $this->_activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
316 $this->_activityId,
317 'activity_type_id'
318 );
319 }
320
321 // Assigning Activity type name.
322 if ($this->_activityTypeId) {
323 $activityTName = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, 'AND v.value = ' . $this->_activityTypeId, 'label');
324 if ($activityTName[$this->_activityTypeId]) {
325 $this->_activityTypeName = $activityTName[$this->_activityTypeId];
326 $this->assign('activityTName', $activityTName[$this->_activityTypeId]);
327 }
328 }
329
330 // Set title.
331 if (isset($activityTName)) {
332 $activityName = CRM_Utils_Array::value($this->_activityTypeId, $activityTName);
333 $this->assign('pageTitle', ts('%1 Activity', array(1 => $activityName)));
334
335 if ($this->_currentlyViewedContactId) {
336 $displayName = CRM_Contact_BAO_Contact::displayName($this->_currentlyViewedContactId);
337 // Check if this is default domain contact CRM-10482.
338 if (CRM_Contact_BAO_Contact::checkDomainContact($this->_currentlyViewedContactId)) {
339 $displayName .= ' (' . ts('default organization') . ')';
340 }
341 CRM_Utils_System::setTitle($displayName . ' - ' . $activityName);
342 }
343 else {
344 CRM_Utils_System::setTitle(ts('%1 Activity', array(1 => $activityName)));
345 }
346 }
347
348 // Check the mode when this form is called either single or as
349 // search task action.
350 if ($this->_activityTypeId ||
351 $this->_context == 'standalone' ||
352 $this->_currentlyViewedContactId
353 ) {
354 $this->_single = TRUE;
355 $this->assign('urlPath', 'civicrm/activity');
356 }
357 else {
358 // Set the appropriate action.
359 $url = CRM_Utils_System::currentPath();
360 $urlArray = explode('/', $url);
361 $searchPath = array_pop($urlArray);
362 $searchType = 'basic';
363 $this->_action = CRM_Core_Action::BASIC;
364 switch ($searchPath) {
365 case 'basic':
366 $searchType = $searchPath;
367 $this->_action = CRM_Core_Action::BASIC;
368 break;
369
370 case 'advanced':
371 $searchType = $searchPath;
372 $this->_action = CRM_Core_Action::ADVANCED;
373 break;
374
375 case 'builder':
376 $searchType = $searchPath;
377 $this->_action = CRM_Core_Action::PROFILE;
378 break;
379
380 case 'custom':
381 $this->_action = CRM_Core_Action::COPY;
382 $searchType = $searchPath;
383 break;
384 }
385
386 parent::preProcess();
387 $this->_single = FALSE;
388
389 $this->assign('urlPath', "civicrm/contact/search/$searchType");
390 $this->assign('urlPathVar', "_qf_Activity_display=true&qfKey={$this->controller->_key}");
391 }
392
393 $this->assign('single', $this->_single);
394 $this->assign('action', $this->_action);
395
396 if ($this->_action & CRM_Core_Action::VIEW) {
397 // Get the tree of custom fields.
398 $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Activity', NULL,
399 $this->_activityId, 0, $this->_activityTypeId
400 );
401 }
402
403 if ($this->_activityTypeId) {
404 // Set activity type name and description to template.
405 list($this->_activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($this->_activityTypeId);
406 $this->assign('activityTypeName', $this->_activityTypeName);
407 $this->assign('activityTypeDescription', $activityTypeDescription);
408 }
409
410 // set user context
411 $urlParams = $urlString = NULL;
412 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
413 if (!$qfKey) {
414 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
415 }
416
417 // Validate the qfKey.
418 if (!CRM_Utils_Rule::qfKey($qfKey)) {
419 $qfKey = NULL;
420 }
421
422 if ($this->_context == 'fulltext') {
423 $keyName = '&qfKey';
424 $urlParams = 'force=1';
425 $urlString = 'civicrm/contact/search/custom';
426 if ($this->_action == CRM_Core_Action::UPDATE) {
427 $keyName = '&key';
428 $urlParams .= '&context=fulltext&action=view';
429 $urlString = 'civicrm/contact/view/activity';
430 }
431 if ($qfKey) {
432 $urlParams .= "$keyName=$qfKey";
433 }
434 $this->assign('searchKey', $qfKey);
435 }
436 elseif (in_array($this->_context, array(
437 'standalone',
438 'home',
439 'dashlet',
440 'dashletFullscreen',
441 ))
442 ) {
443 $urlParams = 'reset=1';
444 $urlString = 'civicrm/dashboard';
445 }
446 elseif ($this->_context == 'search') {
447 $urlParams = 'force=1';
448 if ($qfKey) {
449 $urlParams .= "&qfKey=$qfKey";
450 }
451 $path = CRM_Utils_System::currentPath();
452 if ($this->_compContext == 'advanced') {
453 $urlString = 'civicrm/contact/search/advanced';
454 }
455 elseif ($path == 'civicrm/group/search'
456 || $path == 'civicrm/contact/search'
457 || $path == 'civicrm/contact/search/advanced'
458 || $path == 'civicrm/contact/search/custom'
459 || $path == 'civicrm/group/search'
460 ) {
461 $urlString = $path;
462 }
463 else {
464 $urlString = 'civicrm/activity/search';
465 }
466 $this->assign('searchKey', $qfKey);
467 }
468 elseif ($this->_context != 'caseActivity') {
469 $urlParams = "action=browse&reset=1&cid={$this->_currentlyViewedContactId}&selectedChild=activity";
470 $urlString = 'civicrm/contact/view';
471 }
472
473 if ($urlString) {
474 $session->pushUserContext(CRM_Utils_System::url($urlString, $urlParams));
475 }
476
477 // hack to retrieve activity type id from post variables
478 if (!$this->_activityTypeId) {
479 $this->_activityTypeId = CRM_Utils_Array::value('activity_type_id', $_POST);
480 }
481
482 // when custom data is included in this page
483 if (!empty($_POST['hidden_custom'])) {
484 // We need to set it in the session for the code below to work.
485 // CRM-3014
486 // Need to assign custom data subtype to the template.
487 $this->set('type', 'Activity');
488 $this->set('subType', $this->_activityTypeId);
489 $this->set('entityId', $this->_activityId);
490 CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_activityTypeId, 1, 'Activity', $this->_activityId);
491 CRM_Custom_Form_CustomData::buildQuickForm($this);
492 CRM_Custom_Form_CustomData::setDefaultValues($this);
493 }
494
495 // add attachments part
496 CRM_Core_BAO_File::buildAttachment($this, 'civicrm_activity', $this->_activityId, NULL, TRUE);
497
498 // figure out the file name for activity type, if any
499 if ($this->_activityTypeId &&
500 $this->_activityTypeFile = CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, $this->_crmDir)
501 ) {
502 $this->assign('activityTypeFile', $this->_activityTypeFile);
503 $this->assign('crmDir', $this->_crmDir);
504 }
505
506 $this->setFields();
507
508 if ($this->_activityTypeFile) {
509 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
510 $className::preProcess($this);
511 }
512
513 $this->_values = $this->get('values');
514 if (!is_array($this->_values)) {
515 $this->_values = array();
516 if (isset($this->_activityId) && $this->_activityId) {
517 $params = array('id' => $this->_activityId);
518 CRM_Activity_BAO_Activity::retrieve($params, $this->_values);
519 }
520
521 $this->set('values', $this->_values);
522 }
523
524 if ($this->_action & CRM_Core_Action::UPDATE) {
525 // We filter out alternatives, in case this is a stored e-mail, before sending to front-end
526 $this->_values['details'] = CRM_Utils_String::stripAlternatives($this->_values['details']) ?: '';
527
528 if ($this->_activityTypeName === 'Inbound Email' &&
529 !CRM_Core_Permission::check('edit inbound email basic information and content')
530 ) {
531 $this->_fields['details']['type'] = 'static';
532 }
533
534 CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
535 }
536
537 if ($this->_action & CRM_Core_Action::VIEW) {
538 $url = CRM_Utils_System::url(implode("/", $this->urlPath), "reset=1&id={$this->_activityId}&action=view&cid={$this->_values['source_contact_id']}");
539 CRM_Utils_Recent::add($this->_values['subject'],
540 $url,
541 $this->_values['id'],
542 'Activity',
543 $this->_values['source_contact_id'],
544 $this->_values['source_contact']
545 );
546 }
547 }
548
549 /**
550 * Set default values for the form.
551 *
552 * For edit/view mode the default values are retrieved from the database.
553 *
554 * @return array
555 */
556 public function setDefaultValues() {
557
558 $defaults = $this->_values + CRM_Core_Form_RecurringEntity::setDefaultValues();
559 // if we're editing...
560 if (isset($this->_activityId)) {
561 if (empty($defaults['activity_date_time'])) {
562 list($defaults['activity_date_time'], $defaults['activity_date_time_time']) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
563 }
564 elseif ($this->_action & CRM_Core_Action::UPDATE) {
565 $this->assign('current_activity_date_time', $defaults['activity_date_time']);
566 list($defaults['activity_date_time'],
567 $defaults['activity_date_time_time']
568 ) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
569 list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
570 }
571
572 if ($this->_context != 'standalone') {
573 $this->assign('target_contact_value',
574 CRM_Utils_Array::value('target_contact_value', $defaults)
575 );
576 $this->assign('assignee_contact_value',
577 CRM_Utils_Array::value('assignee_contact_value', $defaults)
578 );
579 }
580
581 // Fixme: why are we getting the wrong keys from upstream?
582 $defaults['target_contact_id'] = CRM_Utils_Array::value('target_contact', $defaults);
583 $defaults['assignee_contact_id'] = CRM_Utils_Array::value('assignee_contact', $defaults);
584
585 // set default tags if exists
586 $defaults['tag'] = implode(',', CRM_Core_BAO_EntityTag::getTag($this->_activityId, 'civicrm_activity'));
587 }
588 else {
589 // if it's a new activity, we need to set default values for associated contact fields
590 $this->_sourceContactId = $this->_currentUserId;
591 $this->_targetContactId = $this->_currentlyViewedContactId;
592
593 $defaults['source_contact_id'] = $this->_sourceContactId;
594 $defaults['target_contact_id'] = $this->_targetContactId;
595
596 list($defaults['activity_date_time'], $defaults['activity_date_time_time'])
597 = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
598 }
599
600 if ($this->_activityTypeId) {
601 $defaults['activity_type_id'] = $this->_activityTypeId;
602 }
603
604 if (!$this->_single && !empty($this->_contactIds)) {
605 $defaults['target_contact_id'] = $this->_contactIds;
606 }
607
608 // CRM-15472 - 50 is around the practical limit of how many items a select2 entityRef can handle
609 if ($this->_action == 2 && !empty($defaults['target_contact_id'])) {
610 $count = count(is_array($defaults['target_contact_id']) ? $defaults['target_contact_id'] : explode(',', $defaults['target_contact_id']));
611 if ($count > 50) {
612 $this->freeze(array('target_contact_id'));
613 }
614 }
615
616 if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) {
617 $this->assign('delName', CRM_Utils_Array::value('subject', $defaults));
618 }
619
620 if ($this->_activityTypeFile) {
621 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
622 $defaults += $className::setDefaultValues($this);
623 }
624 if (empty($defaults['priority_id'])) {
625 $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
626 $defaults['priority_id'] = array_search('Normal', $priority);
627 }
628 if (empty($defaults['status_id'])) {
629 $defaults['status_id'] = CRM_Core_OptionGroup::getDefaultValue('activity_status');
630 }
631 return $defaults;
632 }
633
634 public function buildQuickForm() {
635 if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) {
636 //enable form element (ActivityLinks sets this true)
637 $this->assign('suppressForm', FALSE);
638
639 $button = ts('Delete');
640 if ($this->_action & CRM_Core_Action::RENEW) {
641 $button = ts('Restore');
642 }
643 $this->addButtons(array(
644 array(
645 'type' => 'next',
646 'name' => $button,
647 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
648 'isDefault' => TRUE,
649 ),
650 array(
651 'type' => 'cancel',
652 'name' => ts('Cancel'),
653 ),
654 ));
655 return;
656 }
657
658 // Build other activity links.
659 CRM_Activity_Form_ActivityLinks::commonBuildQuickForm($this);
660
661 // Enable form element (ActivityLinks sets this true).
662 $this->assign('suppressForm', FALSE);
663
664 $element = &$this->add('select', 'activity_type_id', ts('Activity Type'),
665 array('' => '- ' . ts('select') . ' -') + $this->_fields['followup_activity_type_id']['attributes'],
666 FALSE, array(
667 'onchange' => "CRM.buildCustomData( 'Activity', this.value );",
668 'class' => 'crm-select2 required',
669 )
670 );
671
672 // Freeze for update mode.
673 if ($this->_action & CRM_Core_Action::UPDATE) {
674 $element->freeze();
675 }
676
677 // Call to RecurringEntity buildQuickForm for add/update mode.
678 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
679 CRM_Core_Form_RecurringEntity::buildQuickForm($this);
680 }
681
682 foreach ($this->_fields as $field => $values) {
683 if (!empty($this->_fields[$field])) {
684 $attribute = CRM_Utils_Array::value('attributes', $values);
685 $required = !empty($values['required']);
686
687 if ($values['type'] == 'select' && empty($attribute)) {
688 $this->addSelect($field, array('entity' => 'activity'), $required);
689 }
690 elseif ($values['type'] == 'entityRef') {
691 $this->addEntityRef($field, $values['label'], $attribute, $required);
692 }
693 else {
694 $this->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array::value('extra', $values));
695 }
696 }
697 }
698
699 // CRM-7362 --add campaigns.
700 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
701
702 // Add engagement level CRM-7775
703 $buildEngagementLevel = FALSE;
704 if (CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
705 CRM_Campaign_BAO_Campaign::accessCampaign()
706 ) {
707 $buildEngagementLevel = TRUE;
708 $this->addSelect('engagement_level', array('entity' => 'activity'));
709 $this->addRule('engagement_level',
710 ts('Please enter the engagement index as a number (integers only).'),
711 'positiveInteger'
712 );
713 }
714 $this->assign('buildEngagementLevel', $buildEngagementLevel);
715
716 // check for survey activity
717 $this->_isSurveyActivity = FALSE;
718
719 if ($this->_activityId && CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
720 CRM_Campaign_BAO_Campaign::accessCampaign()
721 ) {
722
723 $this->_isSurveyActivity = CRM_Campaign_BAO_Survey::isSurveyActivity($this->_activityId);
724 if ($this->_isSurveyActivity) {
725 $surveyId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
726 $this->_activityId,
727 'source_record_id'
728 );
729 $responseOptions = CRM_Campaign_BAO_Survey::getResponsesOptions($surveyId);
730 if ($responseOptions) {
731 $this->add('select', 'result', ts('Result'),
732 array('' => ts('- select -')) + array_combine($responseOptions, $responseOptions)
733 );
734 }
735 $surveyTitle = NULL;
736 if ($surveyId) {
737 $surveyTitle = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'title');
738 }
739 $this->assign('surveyTitle', $surveyTitle);
740 }
741 }
742 $this->assign('surveyActivity', $this->_isSurveyActivity);
743
744 // Add the "Activity Separation" field
745 $actionIsAdd = $this->_action != CRM_Core_Action::UPDATE;
746 $separationIsPossible = $this->supportsActivitySeparation;
747 if ($actionIsAdd && $separationIsPossible) {
748 $this->addRadio(
749 'separation',
750 ts('Activity Separation'),
751 array(
752 'separate' => ts('Create separate activities for each contact'),
753 'combined' => ts('Create one activity with all contacts together'),
754 )
755 );
756 }
757
758 $this->addRule('duration',
759 ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger'
760 );
761 $this->addDateTime('activity_date_time', ts('Date'), TRUE, array('formatType' => 'activityDateTime'));
762
763 // Add followup date.
764 $this->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
765
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();
769 }
770
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);
775
776 $tags = CRM_Core_BAO_Tag::getColorTags('civicrm_activity');
777
778 if (!empty($tags)) {
779 $this->add('select2', 'tag', ts('Tags'), $tags, FALSE, array('class' => 'huge', 'placeholder' => ts('- select -'), 'multiple' => TRUE));
780 }
781
782 // we need to hide activity tagset for special activities
783 $specialActivities = array('Open Case');
784
785 if (!in_array($this->_activityTypeName, $specialActivities)) {
786 // build tag widget
787 $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
788 CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', $this->_activityId);
789 }
790
791 // if we're viewing, we're assigning different buttons than for adding/editing
792 if ($this->_action & CRM_Core_Action::VIEW) {
793 if (isset($this->_groupTree)) {
794 CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $this->_groupTree, FALSE, NULL, NULL, NULL, $this->_activityId);
795 }
796 // form should be frozen for view mode
797 $this->freeze();
798
799 $buttons = array();
800 $buttons[] = array(
801 'type' => 'cancel',
802 'name' => ts('Done'),
803 );
804 $this->addButtons($buttons);
805 }
806 else {
807 $message = array(
808 '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.'),
809 '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.'),
810 );
811 $js = array('onclick' => "return activityStatus(" . json_encode($message) . ");");
812 $this->addButtons(array(
813 array(
814 'type' => 'upload',
815 'name' => ts('Save'),
816 'js' => $js,
817 'isDefault' => TRUE,
818 ),
819 array(
820 'type' => 'cancel',
821 'name' => ts('Cancel'),
822 ),
823 ));
824 }
825
826 if ($this->_activityTypeFile) {
827 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
828
829 $className::buildQuickForm($this);
830 $this->addFormRule(array($className, 'formRule'), $this);
831 }
832
833 $this->addFormRule(array('CRM_Activity_Form_Activity', 'formRule'), $this);
834
835 $doNotNotifyAssigneeFor = (array) Civi::settings()->get('do_not_notify_assignees_for');
836 if (($this->_activityTypeId && in_array($this->_activityTypeId, $doNotNotifyAssigneeFor)) || !Civi::settings()->get('activity_assignee_notification')) {
837 $this->assign('activityAssigneeNotification', FALSE);
838 }
839 else {
840 $this->assign('activityAssigneeNotification', TRUE);
841 }
842 $this->assign('doNotNotifyAssigneeFor', $doNotNotifyAssigneeFor);
843 }
844
845 /**
846 * Global form rule.
847 *
848 * @param array $fields
849 * The input form values.
850 * @param array $files
851 * The uploaded files if any.
852 * @param $self
853 *
854 * @return bool|array
855 * true if no errors, else array of errors
856 */
857 public static function formRule($fields, $files, $self) {
858 // skip form rule if deleting
859 if (CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Delete') {
860 return TRUE;
861 }
862 $errors = array();
863 if ((array_key_exists('activity_type_id', $fields) || !$self->_single) && empty($fields['activity_type_id'])) {
864 $errors['activity_type_id'] = ts('Activity Type is a required field');
865 }
866
867 if (CRM_Utils_Array::value('activity_type_id', $fields) == 3 &&
868 CRM_Utils_Array::value('status_id', $fields) == 1
869 ) {
870 $errors['status_id'] = ts('You cannot record scheduled email activity.');
871 }
872 elseif (CRM_Utils_Array::value('activity_type_id', $fields) == 4 &&
873 CRM_Utils_Array::value('status_id', $fields) == 1
874 ) {
875 $errors['status_id'] = ts('You cannot record scheduled SMS activity.');
876 }
877
878 if (!empty($fields['followup_activity_type_id']) && empty($fields['followup_date'])) {
879 $errors['followup_date_time'] = ts('Followup date is a required field.');
880 }
881 // Activity type is mandatory if subject or follow-up date is specified for an Follow-up activity, CRM-4515.
882 if ((!empty($fields['followup_activity_subject']) || !empty($fields['followup_date'])) && empty($fields['followup_activity_type_id'])) {
883 $errors['followup_activity_subject'] = ts('Follow-up Activity type is a required field.');
884 }
885
886 // Check that a value has been set for the "activity separation" field if needed
887 $separationIsPossible = $self->supportsActivitySeparation;
888 $actionIsAdd = $self->_action == CRM_Core_Action::ADD;
889 $hasMultipleTargetContacts = !empty($fields['target_contact_id']) && strpos($fields['target_contact_id'], ',') !== FALSE;
890 $separationFieldIsEmpty = empty($fields['separation']);
891 if ($separationIsPossible && $actionIsAdd && $hasMultipleTargetContacts && $separationFieldIsEmpty) {
892 $errors['separation'] = ts('Activity Separation is a required field.');
893 }
894
895 return $errors;
896 }
897
898 /**
899 * Process the form submission.
900 *
901 *
902 * @param array $params
903 * @return array|null
904 */
905 public function postProcess($params = NULL) {
906 if ($this->_action & CRM_Core_Action::DELETE) {
907 $deleteParams = array('id' => $this->_activityId);
908 $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($this->_activityId);
909 CRM_Activity_BAO_Activity::deleteActivity($deleteParams, $moveToTrash);
910
911 // delete tags for the entity
912 $tagParams = array(
913 'entity_table' => 'civicrm_activity',
914 'entity_id' => $this->_activityId,
915 );
916
917 CRM_Core_BAO_EntityTag::del($tagParams);
918
919 CRM_Core_Session::setStatus(ts("Selected Activity has been deleted successfully."), ts('Record Deleted'), 'success');
920 return NULL;
921 }
922
923 // store the submitted values in an array
924 if (!$params) {
925 $params = $this->controller->exportValues($this->_name);
926 }
927
928 // Set activity type id.
929 if (empty($params['activity_type_id'])) {
930 $params['activity_type_id'] = $this->_activityTypeId;
931 }
932
933 if (!empty($params['hidden_custom']) &&
934 !isset($params['custom'])
935 ) {
936 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
937 $this->_activityTypeId
938 );
939 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
940 CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
941 NULL, NULL, TRUE
942 )
943 );
944 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
945 $this->_activityId,
946 'Activity'
947 );
948 }
949
950 // store the date with proper format
951 $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
952
953 // format params as arrays
954 foreach (array('target', 'assignee', 'followup_assignee') as $name) {
955 if (!empty($params["{$name}_contact_id"])) {
956 $params["{$name}_contact_id"] = explode(',', $params["{$name}_contact_id"]);
957 }
958 else {
959 $params["{$name}_contact_id"] = array();
960 }
961 }
962
963 // get ids for associated contacts
964 if (!$params['source_contact_id']) {
965 $params['source_contact_id'] = $this->_currentUserId;
966 }
967
968 if (isset($this->_activityId)) {
969 $params['id'] = $this->_activityId;
970 }
971
972 // add attachments as needed
973 CRM_Core_BAO_File::formatAttachment($params,
974 $params,
975 'civicrm_activity',
976 $this->_activityId
977 );
978
979 $params['is_multi_activity'] = CRM_Utils_Array::value('separation', $params) == 'separate';
980
981 $activity = array();
982 if (!empty($params['is_multi_activity']) &&
983 !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])
984 ) {
985 $targetContacts = $params['target_contact_id'];
986 foreach ($targetContacts as $targetContactId) {
987 $params['target_contact_id'] = array($targetContactId);
988 // save activity
989 $activity[] = $this->processActivity($params);
990 }
991 }
992 else {
993 // save activity
994 $activity = $this->processActivity($params);
995 }
996
997 $activityIds = empty($this->_activityIds) ? array($this->_activityId) : $this->_activityIds;
998 foreach ($activityIds as $activityId) {
999 // set params for repeat configuration in create mode
1000 $params['entity_id'] = $activityId;
1001 $params['entity_table'] = 'civicrm_activity';
1002 if (!empty($params['entity_id']) && !empty($params['entity_table'])) {
1003 $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($params['entity_id'], $params['entity_table']);
1004 if ($checkParentExistsForThisId) {
1005 $params['parent_entity_id'] = $checkParentExistsForThisId;
1006 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $params['entity_table']);
1007 }
1008 else {
1009 $params['parent_entity_id'] = $params['entity_id'];
1010 $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($params['entity_id'], $params['entity_table']);
1011 }
1012 if (property_exists($scheduleReminderDetails, 'id')) {
1013 $params['schedule_reminder_id'] = $scheduleReminderDetails->id;
1014 }
1015 }
1016 $params['dateColumns'] = array('activity_date_time');
1017
1018 // Set default repetition start if it was not provided.
1019 if (empty($params['repetition_start_date'])) {
1020 $params['repetition_start_date'] = $params['activity_date_time'];
1021 }
1022
1023 // unset activity id
1024 unset($params['id']);
1025 $linkedEntities = array(
1026 array(
1027 'table' => 'civicrm_activity_contact',
1028 'findCriteria' => array(
1029 'activity_id' => $activityId,
1030 ),
1031 'linkedColumns' => array('activity_id'),
1032 'isRecurringEntityRecord' => FALSE,
1033 ),
1034 );
1035 CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_activity', $linkedEntities);
1036 }
1037
1038 return array('activity' => $activity);
1039 }
1040
1041 /**
1042 * Process activity creation.
1043 *
1044 * @param array $params
1045 * Associated array of submitted values.
1046 *
1047 * @return self|null|object
1048 */
1049 protected function processActivity(&$params) {
1050 $activityAssigned = array();
1051 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1052 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1053 // format assignee params
1054 if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
1055 //skip those assignee contacts which are already assigned
1056 //while sending a copy.CRM-4509.
1057 $activityAssigned = array_flip($params['assignee_contact_id']);
1058 if ($this->_activityId) {
1059 $assigneeContacts = CRM_Activity_BAO_ActivityContact::getNames($this->_activityId, $assigneeID);
1060 $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
1061 }
1062 }
1063
1064 // call begin post process. Idea is to let injecting file do
1065 // any processing before the activity is added/updated.
1066 $this->beginPostProcess($params);
1067
1068 $activity = CRM_Activity_BAO_Activity::create($params);
1069
1070 // add tags if exists
1071 $tagParams = array();
1072 if (!empty($params['tag'])) {
1073 if (!is_array($params['tag'])) {
1074 $params['tag'] = explode(',', $params['tag']);
1075 }
1076 foreach ($params['tag'] as $tag) {
1077 $tagParams[$tag] = 1;
1078 }
1079 }
1080
1081 // Save static tags.
1082 CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);
1083
1084 // Save free tags.
1085 if (isset($params['activity_taglist']) && !empty($params['activity_taglist'])) {
1086 CRM_Core_Form_Tag::postProcess($params['activity_taglist'], $activity->id, 'civicrm_activity', $this);
1087 }
1088
1089 // call end post process. Idea is to let injecting file do any
1090 // processing needed, after the activity has been added/updated.
1091 $this->endPostProcess($params, $activity);
1092
1093 // CRM-9590
1094 if (!empty($params['is_multi_activity'])) {
1095 $this->_activityIds[] = $activity->id;
1096 }
1097 else {
1098 $this->_activityId = $activity->id;
1099 }
1100
1101 // create follow up activity if needed
1102 $followupStatus = '';
1103 $followupActivity = NULL;
1104 if (!empty($params['followup_activity_type_id'])) {
1105 $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
1106 $followupStatus = ts('A followup activity has been scheduled.');
1107 }
1108
1109 // send copy to assignee contacts.CRM-4509
1110 $mailStatus = '';
1111
1112 if (Civi::settings()->get('activity_assignee_notification')
1113 && !in_array($activity->activity_type_id, Civi::settings()->get('do_not_notify_assignees_for'))) {
1114 $activityIDs = array($activity->id);
1115 if ($followupActivity) {
1116 $activityIDs = array_merge($activityIDs, array($followupActivity->id));
1117 }
1118 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityIDs, TRUE, FALSE);
1119
1120 if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
1121 $mailToContacts = array();
1122
1123 // Build an associative array with unique email addresses.
1124 foreach ($activityAssigned as $id => $dnc) {
1125 if (isset($id) && array_key_exists($id, $assigneeContacts)) {
1126 $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
1127 }
1128 }
1129
1130 $sent = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts);
1131 if ($sent) {
1132 $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
1133 }
1134 }
1135
1136 // Also send email to follow-up activity assignees if set
1137 if ($followupActivity) {
1138 $mailToFollowupContacts = array();
1139 foreach ($assigneeContacts as $values) {
1140 if ($values['activity_id'] == $followupActivity->id) {
1141 $mailToFollowupContacts[$values['email']] = $values;
1142 }
1143 }
1144
1145 $sentFollowup = CRM_Activity_BAO_Activity::sendToAssignee($followupActivity, $mailToFollowupContacts);
1146 if ($sentFollowup) {
1147 $mailStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
1148 }
1149 }
1150 }
1151
1152 // set status message
1153 $subject = '';
1154 if (!empty($params['subject'])) {
1155 $subject = "'" . $params['subject'] . "'";
1156 }
1157
1158 CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2 %3',
1159 array(
1160 1 => $subject,
1161 2 => $followupStatus,
1162 3 => $mailStatus,
1163 )
1164 ), ts('Saved'), 'success');
1165
1166 return $activity;
1167 }
1168
1169 /**
1170 * Shorthand for getting id by display name (makes code more readable)
1171 * @param $displayName
1172 * @return null|string
1173 */
1174 protected function _getIdByDisplayName($displayName) {
1175 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1176 $displayName,
1177 'id',
1178 'sort_name'
1179 );
1180 }
1181
1182 /**
1183 * Shorthand for getting display name by id (makes code more readable)
1184 * @param $id
1185 * @return null|string
1186 */
1187 protected function _getDisplayNameById($id) {
1188 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
1189 $id,
1190 'sort_name',
1191 'id'
1192 );
1193 }
1194
1195 /**
1196 * Let injecting activity type file do any processing.
1197 * needed, before the activity is added/updated
1198 *
1199 * @param array $params
1200 */
1201 public function beginPostProcess(&$params) {
1202 if ($this->_activityTypeFile) {
1203 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
1204 $className::beginPostProcess($this, $params);
1205 }
1206 }
1207
1208 /**
1209 * Let injecting activity type file do any processing
1210 * needed, after the activity has been added/updated
1211 *
1212 * @param array $params
1213 * @param $activity
1214 */
1215 public function endPostProcess(&$params, &$activity) {
1216 if ($this->_activityTypeFile) {
1217 $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
1218 $className::endPostProcess($this, $params, $activity);
1219 }
1220 }
1221
1222 }