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