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