Activity.php 40.4 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
yashodha's avatar
yashodha committed
4
 | CiviCRM version 4.6                                                |
totten's avatar
totten committed
5
 +--------------------------------------------------------------------+
kurund's avatar
kurund committed
6
 | Copyright CiviCRM LLC (c) 2004-2014                                |
totten's avatar
totten committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
26
 */
totten's avatar
totten committed
27 28 29 30

/**
 *
 * @package CRM
kurund's avatar
kurund committed
31
 * @copyright CiviCRM LLC (c) 2004-2014
totten's avatar
totten committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
 * $Id$
 *
 */

/**
 * This class generates form components for Activity
 *
 */
class CRM_Activity_Form_Activity extends CRM_Contact_Form_Task {

  /**
   * The id of the object being edited / created
   *
   * @var int
   */
  public $_activityId;

49
  /**
colemanw's avatar
colemanw committed
50
   * Store activity ids when multiple activities are created
51 52 53 54 55
   *
   * @var int
   */
  public $_activityIds = array();

totten's avatar
totten committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  /**
   * The id of activity type
   *
   * @var int
   */
  public $_activityTypeId;

  /**
   * The name of activity type
   *
   * @var string
   */
  public $_activityTypeName;

  /**
   * The id of currently viewed contact
   *
   * @var int
   */
  public $_currentlyViewedContactId;

  /**
   * The id of source contact and target contact
   *
   * @var int
   */
  protected $_sourceContactId;
  protected $_targetContactId;
  protected $_asigneeContactId;

  protected $_single;

  public $_context;
  public $_compContext;
  public $_action;
  public $_activityTypeFile;

  /**
   * The id of the logged in user, used when add / edit
   *
   * @var int
   */
  public $_currentUserId;

  /**
   * The array of form field attributes
   *
   * @var array
   */
  public $_fields;

  /**
   * The the directory inside CRM, to include activity type file from
   *
   * @var string
   */
  protected $_crmDir = 'Activity';

114 115 116 117 118
  /**
   * Survey activity
   *
   * @var boolean
   */
totten's avatar
totten committed
119 120 121 122
  protected $_isSurveyActivity;

  protected $_values = array();

colemanw's avatar
colemanw committed
123
  protected $unsavedWarn = TRUE;
unknown's avatar
unknown committed
124

totten's avatar
totten committed
125 126 127 128
  /**
   * The _fields var can be used by sub class to set/unset/edit the
   * form fields based on their requirement
   */
129
  public function setFields() {
totten's avatar
totten committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    $this->_fields = array(
      'subject' => array(
        'type' => 'text',
        'label' => ts('Subject'),
        'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
          'subject'
        ),
      ),
      'duration' => array(
        'type' => 'text',
        'label' => ts('Duration'),
        'attributes' => array('size' => 4, 'maxlength' => 8),
        'required' => FALSE,
      ),
      'location' => array(
        'type' => 'text',
        'label' => ts('Location'),
147
        'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity', 'location'),
148
        'required' => FALSE,
totten's avatar
totten committed
149 150 151 152 153 154
      ),
      'details' => array(
        'type' => 'wysiwyg',
        'label' => ts('Details'),
        // forces a smaller edit window
        'attributes' => array('rows' => 4, 'cols' => 60),
155
        'required' => FALSE,
totten's avatar
totten committed
156 157 158
      ),
      'status_id' => array(
        'type' => 'select',
159
        'required' => TRUE,
totten's avatar
totten committed
160 161 162
      ),
      'priority_id' => array(
        'type' => 'select',
163
        'required' => TRUE,
totten's avatar
totten committed
164 165
      ),
      'source_contact_id' => array(
166
        'type' => 'entityRef',
totten's avatar
totten committed
167
        'label' => ts('Added By'),
168
        'required' => FALSE,
totten's avatar
totten committed
169
      ),
170 171 172
      'target_contact_id' => array(
        'type' => 'entityRef',
        'label' => ts('With Contact'),
173
        'attributes' => array('multiple' => TRUE, 'create' => TRUE),
174 175 176
      ),
      'assignee_contact_id' => array(
        'type' => 'entityRef',
177
        'label' => ts('Assigned to'),
totten's avatar
totten committed
178 179 180 181 182
        'attributes' => array(
          'multiple' => TRUE,
          'create' => TRUE,
          'api' => array('params' => array('is_deceased' => 0))
        ),
183 184 185
      ),
      'followup_assignee_contact_id' => array(
        'type' => 'entityRef',
186
        'label' => ts('Assigned to'),
totten's avatar
totten committed
187 188 189 190 191
        'attributes' => array(
          'multiple' => TRUE,
          'create' => TRUE,
          'api' => array('params' => array('is_deceased' => 0))
        ),
192
      ),
totten's avatar
totten committed
193 194 195
      'followup_activity_type_id' => array(
        'type' => 'select',
        'label' => ts('Followup Activity'),
colemanw's avatar
colemanw committed
196 197
        'attributes' => array('' => '- ' . ts('select activity') . ' -') + CRM_Core_PseudoConstant::ActivityType(FALSE),
        'extra' => array('class' => 'crm-select2'),
totten's avatar
totten committed
198 199 200 201 202 203 204
      ),
      // Add optional 'Subject' field for the Follow-up Activiity, CRM-4491
      'followup_activity_subject' => array(
        'type' => 'text',
        'label' => ts('Subject'),
        'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
          'subject'
205 206
        ),
      ),
totten's avatar
totten committed
207 208 209 210 211 212 213 214 215 216
    );

    if (($this->_context == 'standalone') &&
      ($printPDF = CRM_Utils_Array::key('Print PDF Letter', $this->_fields['followup_activity_type_id']['attributes']))
    ) {
      unset($this->_fields['followup_activity_type_id']['attributes'][$printPDF]);
    }
  }

  /**
217
   * Build the form object
totten's avatar
totten committed
218
   *
colemanw's avatar
colemanw committed
219
   * @return void
totten's avatar
totten committed
220
   */
221
  public function preProcess() {
totten's avatar
totten committed
222 223 224 225 226 227
    $this->_cdType = CRM_Utils_Array::value('type', $_GET);
    $this->assign('cdType', FALSE);
    if ($this->_cdType) {
      $this->assign('cdType', TRUE);
      return CRM_Custom_Form_CustomData::preProcess($this);
    }
unknown's avatar
unknown committed
228
    CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
totten's avatar
totten committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    $this->_atypefile = CRM_Utils_Array::value('atypefile', $_GET);
    $this->assign('atypefile', FALSE);
    if ($this->_atypefile) {
      $this->assign('atypefile', TRUE);
    }

    $session = CRM_Core_Session::singleton();
    $this->_currentUserId = $session->get('userID');

    $this->_currentlyViewedContactId = $this->get('contactId');
    if (!$this->_currentlyViewedContactId) {
      $this->_currentlyViewedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
    }
    $this->assign('contactId', $this->_currentlyViewedContactId);

    //give the context.
    if (!isset($this->_context)) {
      $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
      if (CRM_Contact_Form_Search::isSearchContext($this->_context)) {
        $this->_context = 'search';
      }
      elseif (!in_array($this->_context, array('dashlet', 'dashletFullscreen'))
        && $this->_currentlyViewedContactId
      ) {
        $this->_context = 'activity';
      }
      $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
    }

    $this->assign('context', $this->_context);

    $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this);

    if ($this->_action & CRM_Core_Action::DELETE) {
      if (!CRM_Core_Permission::check('delete activities')) {
264
        CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
totten's avatar
totten committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
      }
    }

    //CRM-6957
    //when we come from contact search, activity id never comes.
    //so don't try to get from object, it might gives you wrong one.

    // if we're not adding new one, there must be an id to
    // an activity we're trying to work on.
    if ($this->_action != CRM_Core_Action::ADD &&
      get_class($this->controller) != 'CRM_Contact_Controller_Search'
    ) {
      $this->_activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this);
    }

    $this->_activityTypeId = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
    $this->assign('atype', $this->_activityTypeId);

colemanw's avatar
colemanw committed
283 284
    $this->assign('activityId', $this->_activityId);

totten's avatar
totten committed
285 286 287
    //check for required permissions, CRM-6264
    if ($this->_activityId &&
      in_array($this->_action, array(
yashodha's avatar
yashodha committed
288
        CRM_Core_Action::UPDATE,
289
        CRM_Core_Action::VIEW,
yashodha's avatar
yashodha committed
290
      )) &&
totten's avatar
totten committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
      !CRM_Activity_BAO_Activity::checkPermission($this->_activityId, $this->_action)
    ) {
      CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
    }
    if (($this->_action & CRM_Core_Action::VIEW) &&
      CRM_Activity_BAO_Activity::checkPermission($this->_activityId, CRM_Core_Action::UPDATE)
    ) {
      $this->assign('permission', 'edit');
    }

    if (!$this->_activityTypeId && $this->_activityId) {
      $this->_activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
        $this->_activityId,
        'activity_type_id'
      );
    }

    //Assigning Activity type name
    if ($this->_activityTypeId) {
      $activityTName = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, 'AND v.value = ' . $this->_activityTypeId, 'name');
      if ($activityTName[$this->_activityTypeId]) {
        $this->_activityTypeName = $activityTName[$this->_activityTypeId];
        $this->assign('activityTName', $activityTName[$this->_activityTypeId]);
      }
    }

317
    // Set title
totten's avatar
totten committed
318
    if (isset($activityTName)) {
319
      $activityName = CRM_Utils_Array::value($this->_activityTypeId, $activityTName);
320
      $this->assign('pageTitle', ts('%1 Activity', array(1 => $activityName)));
321 322 323 324 325 326 327 328 329 330

      if ($this->_currentlyViewedContactId) {
        $displayName = CRM_Contact_BAO_Contact::displayName($this->_currentlyViewedContactId);
        // Check if this is default domain contact CRM-10482
        if (CRM_Contact_BAO_Contact::checkDomainContact($this->_currentlyViewedContactId)) {
          $displayName .= ' (' . ts('default organization') . ')';
        }
        CRM_Utils_System::setTitle($displayName . ' - ' . $activityName);
      }
      else {
331
        CRM_Utils_System::setTitle(ts('%1 Activity', array(1 => $activityName)));
332
      }
totten's avatar
totten committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    }

    //check the mode when this form is called either single or as
    //search task action
    if ($this->_activityTypeId ||
      $this->_context == 'standalone' ||
      $this->_currentlyViewedContactId
    ) {
      $this->_single = TRUE;
      $this->assign('urlPath', 'civicrm/activity');
    }
    else {
      //set the appropriate action
      $url = CRM_Utils_System::currentPath();
      $urlArray = explode('/', $url);
yashodha's avatar
yashodha committed
348
      $searchPath = array_pop($urlArray);
totten's avatar
totten committed
349 350
      $searchType = 'basic';
      $this->_action = CRM_Core_Action::BASIC;
yashodha's avatar
yashodha committed
351
      switch ($searchPath) {
totten's avatar
totten committed
352
        case 'basic':
yashodha's avatar
yashodha committed
353
          $searchType = $searchPath;
totten's avatar
totten committed
354 355 356 357
          $this->_action = CRM_Core_Action::BASIC;
          break;

        case 'advanced':
yashodha's avatar
yashodha committed
358
          $searchType = $searchPath;
totten's avatar
totten committed
359 360 361 362
          $this->_action = CRM_Core_Action::ADVANCED;
          break;

        case 'builder':
yashodha's avatar
yashodha committed
363
          $searchType = $searchPath;
totten's avatar
totten committed
364 365 366 367 368
          $this->_action = CRM_Core_Action::PROFILE;
          break;

        case 'custom':
          $this->_action = CRM_Core_Action::COPY;
yashodha's avatar
yashodha committed
369
          $searchType = $searchPath;
totten's avatar
totten committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
          break;
      }

      parent::preProcess();
      $this->_single = FALSE;

      $this->assign('urlPath', "civicrm/contact/search/$searchType");
      $this->assign('urlPathVar', "_qf_Activity_display=true&qfKey={$this->controller->_key}");
    }

    $this->assign('single', $this->_single);
    $this->assign('action', $this->_action);

    if ($this->_action & CRM_Core_Action::VIEW) {
      // get the tree of custom fields
      $this->_groupTree = &CRM_Core_BAO_CustomGroup::getTree('Activity', $this,
        $this->_activityId, 0, $this->_activityTypeId
      );
    }

    if ($this->_activityTypeId) {
      //set activity type name and description to template
      list($this->_activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($this->_activityTypeId);
      $this->assign('activityTypeName', $this->_activityTypeName);
      $this->assign('activityTypeDescription', $activityTypeDescription);
    }

    // set user context
    $urlParams = $urlString = NULL;
Deepak Srivastava's avatar
Deepak Srivastava committed
399 400 401 402
    $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
    if (!$qfKey) {
      $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
    }
totten's avatar
totten committed
403 404 405 406 407 408 409

    //validate the qfKey
    if (!CRM_Utils_Rule::qfKey($qfKey)) {
      $qfKey = NULL;
    }

    if ($this->_context == 'fulltext') {
yashodha's avatar
yashodha committed
410
      $keyName = '&qfKey';
totten's avatar
totten committed
411 412 413 414 415 416 417 418 419 420 421 422 423
      $urlParams = 'force=1';
      $urlString = 'civicrm/contact/search/custom';
      if ($this->_action == CRM_Core_Action::UPDATE) {
        $keyName = '&key';
        $urlParams .= '&context=fulltext&action=view';
        $urlString = 'civicrm/contact/view/activity';
      }
      if ($qfKey) {
        $urlParams .= "$keyName=$qfKey";
      }
      $this->assign('searchKey', $qfKey);
    }
    elseif (in_array($this->_context, array(
yashodha's avatar
yashodha committed
424 425 426
      'standalone',
      'home',
      'dashlet',
427
      'dashletFullscreen',
yashodha's avatar
yashodha committed
428 429
    ))
    ) {
totten's avatar
totten committed
430 431 432 433 434 435 436 437
      $urlParams = 'reset=1';
      $urlString = 'civicrm/dashboard';
    }
    elseif ($this->_context == 'search') {
      $urlParams = 'force=1';
      if ($qfKey) {
        $urlParams .= "&qfKey=$qfKey";
      }
Deepak Srivastava's avatar
Deepak Srivastava committed
438
      $path = CRM_Utils_System::currentPath();
439
      if ($this->_compContext == 'advanced') {
totten's avatar
totten committed
440 441
        $urlString = 'civicrm/contact/search/advanced';
      }
442
      elseif ($path == 'civicrm/group/search'
totten's avatar
totten committed
443
        || $path == 'civicrm/contact/search'
444
        || $path == 'civicrm/contact/search/advanced'
445
        || $path == 'civicrm/contact/search/custom'
totten's avatar
totten committed
446 447
        || $path == 'civicrm/group/search'
      ) {
448 449
        $urlString = $path;
      }
totten's avatar
totten committed
450
      else {
451
        $urlString = 'civicrm/activity/search';
totten's avatar
totten committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
      }
      $this->assign('searchKey', $qfKey);
    }
    elseif ($this->_context != 'caseActivity') {
      $urlParams = "action=browse&reset=1&cid={$this->_currentlyViewedContactId}&selectedChild=activity";
      $urlString = 'civicrm/contact/view';
    }

    if ($urlString) {
      $session->pushUserContext(CRM_Utils_System::url($urlString, $urlParams));
    }

    // hack to retrieve activity type id from post variables
    if (!$this->_activityTypeId) {
      $this->_activityTypeId = CRM_Utils_Array::value('activity_type_id', $_POST);
    }

    // when custom data is included in this page
470
    if (!empty($_POST['hidden_custom'])) {
totten's avatar
totten committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
      // we need to set it in the session for the below code to work
      // CRM-3014
      //need to assign custom data subtype to the template
      $this->set('type', 'Activity');
      $this->set('subType', $this->_activityTypeId);
      $this->set('entityId', $this->_activityId);
      CRM_Custom_Form_CustomData::preProcess($this);
      CRM_Custom_Form_CustomData::buildQuickForm($this);
      CRM_Custom_Form_CustomData::setDefaultValues($this);
    }

    // add attachments part
    CRM_Core_BAO_File::buildAttachment($this, 'civicrm_activity', $this->_activityId, NULL, TRUE);

    // figure out the file name for activity type, if any
    if ($this->_activityTypeId &&
      $this->_activityTypeFile =
yashodha's avatar
yashodha committed
488
        CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, $this->_crmDir)
totten's avatar
totten committed
489 490 491 492 493 494 495 496
    ) {
      $this->assign('activityTypeFile', $this->_activityTypeFile);
      $this->assign('crmDir', $this->_crmDir);
    }

    $this->setFields();

    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
497 498
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $className::preProcess($this);
totten's avatar
totten committed
499 500 501 502 503 504 505 506 507 508 509
    }

    $this->_values = $this->get('values');
    if (!is_array($this->_values)) {
      $this->_values = array();
      if (isset($this->_activityId) && $this->_activityId) {
        $params = array('id' => $this->_activityId);
        CRM_Activity_BAO_Activity::retrieve($params, $this->_values);
      }
      $this->set('values', $this->_values);
    }
unknown's avatar
unknown committed
510

511
    if ($this->_action & CRM_Core_Action::UPDATE) {
512
      CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
513
    }
totten's avatar
totten committed
514
  }
unknown's avatar
unknown committed
515

totten's avatar
totten committed
516
  /**
517
   * Set default values for the form. For edit/view mode
totten's avatar
totten committed
518 519 520
   * the default values are retrieved from the database
   *
   *
colemanw's avatar
colemanw committed
521
   * @return void
totten's avatar
totten committed
522
   */
523
  public function setDefaultValues() {
totten's avatar
totten committed
524 525 526 527 528 529 530
    if ($this->_cdType) {
      return CRM_Custom_Form_CustomData::setDefaultValues($this);
    }

    $defaults = $this->_values;
    // if we're editing...
    if (isset($this->_activityId)) {
531
      if (empty($defaults['activity_date_time'])) {
totten's avatar
totten committed
532 533 534 535 536 537
        list($defaults['activity_date_time'], $defaults['activity_date_time_time']) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
      }
      elseif ($this->_action & CRM_Core_Action::UPDATE) {
        $this->assign('current_activity_date_time', $defaults['activity_date_time']);
        list($defaults['activity_date_time'],
          $defaults['activity_date_time_time']
yashodha's avatar
yashodha committed
538
          ) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
539 540 541 542
        list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
        $recurringEntityDefaults = array();
        $recurringEntityDefaults = CRM_Core_Form_RecurringEntity::setDefaultValues();
        $defaults = array_merge($defaults, $recurringEntityDefaults);
totten's avatar
totten committed
543 544 545 546 547 548 549 550 551 552 553
      }

      if ($this->_context != 'standalone') {
        $this->assign('target_contact_value',
          CRM_Utils_Array::value('target_contact_value', $defaults)
        );
        $this->assign('assignee_contact_value',
          CRM_Utils_Array::value('assignee_contact_value', $defaults)
        );
      }

554
      // Fixme: why are we getting the wrong keys from upstream?
Jitendra Purohit's avatar
Jitendra Purohit committed
555 556
      $defaults['target_contact_id'] = CRM_Utils_Array::value('target_contact', $defaults);
      $defaults['assignee_contact_id'] = CRM_Utils_Array::value('assignee_contact', $defaults);
557

totten's avatar
totten committed
558 559 560 561 562 563 564 565
      // set default tags if exists
      $defaults['tag'] = CRM_Core_BAO_EntityTag::getTag($this->_activityId, 'civicrm_activity');
    }
    else {
      // if it's a new activity, we need to set default values for associated contact fields
      $this->_sourceContactId = $this->_currentUserId;
      $this->_targetContactId = $this->_currentlyViewedContactId;

566
      $defaults['source_contact_id'] = $this->_sourceContactId;
567
      $defaults['target_contact_id'] = $this->_targetContactId;
totten's avatar
totten committed
568 569 570 571 572 573 574 575 576

      list($defaults['activity_date_time'], $defaults['activity_date_time_time']) =
        CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
    }

    if ($this->_activityTypeId) {
      $defaults['activity_type_id'] = $this->_activityTypeId;
    }

577 578 579 580
    if (!$this->_single && !empty($this->_contactIds)) {
      $defaults['target_contact_id'] = $this->_contactIds;
    }

581 582 583 584 585 586 587 588
    // CRM-15472 - 50 is around the practial limit of how many items a select2 entityRef can handle
    if (!empty($defaults['target_contact_id'])) {
      $count = count(is_array($defaults['target_contact_id']) ? $defaults['target_contact_id'] : explode(',', $defaults['target_contact_id']));
      if ($count > 50) {
        $this->freeze(array('target_contact_id'));
      }
    }

totten's avatar
totten committed
589 590 591 592 593
    if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) {
      $this->assign('delName', CRM_Utils_Array::value('subject', $defaults));
    }

    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
594 595
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $defaults += $className::setDefaultValues($this);
totten's avatar
totten committed
596
    }
597
    if (empty($defaults['priority_id'])) {
598
      $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
totten's avatar
totten committed
599 600
      $defaults['priority_id'] = array_search('Normal', $priority);
    }
601
    if (empty($defaults['status_id'])) {
602 603
      $defaults['status_id'] = CRM_Core_OptionGroup::getDefaultValue('activity_status');
    }
totten's avatar
totten committed
604 605 606 607 608 609 610 611 612 613 614 615 616
    return $defaults;
  }

  public function buildQuickForm() {
    if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::RENEW)) {
      //enable form element (ActivityLinks sets this true)
      $this->assign('suppressForm', FALSE);

      $button = ts('Delete');
      if ($this->_action & CRM_Core_Action::RENEW) {
        $button = ts('Restore');
      }
      $this->addButtons(array(
yashodha's avatar
yashodha committed
617 618 619 620
        array(
          'type' => 'next',
          'name' => $button,
          'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
621
          'isDefault' => TRUE,
yashodha's avatar
yashodha committed
622 623 624
        ),
        array(
          'type' => 'cancel',
625 626
          'name' => ts('Cancel'),
        ),
yashodha's avatar
yashodha committed
627
      ));
totten's avatar
totten committed
628 629 630 631 632 633 634 635
      return;
    }

    if ($this->_cdType) {
      return CRM_Custom_Form_CustomData::buildQuickForm($this);
    }

    //build other activity links
lobo's avatar
lobo committed
636
    CRM_Activity_Form_ActivityLinks::commonBuildQuickForm($this);
totten's avatar
totten committed
637 638 639 640

    //enable form element (ActivityLinks sets this true)
    $this->assign('suppressForm', FALSE);

totten's avatar
totten committed
641
    $element = &$this->add('select', 'activity_type_id', ts('Activity Type'),
totten's avatar
totten committed
642 643
      $this->_fields['followup_activity_type_id']['attributes'],
      FALSE, array(
644 645
        'onchange' => "CRM.buildCustomData( 'Activity', this.value );",
        'class' => 'crm-select2',
totten's avatar
totten committed
646 647 648 649 650 651
      )
    );

    //freeze for update mode.
    if ($this->_action & CRM_Core_Action::UPDATE) {
      $element->freeze();
unknown's avatar
unknown committed
652 653 654 655
    }

    //Call to RecurringEntity buildQuickForm for add/update mode
    if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
656
      CRM_Core_Form_RecurringEntity::buildQuickForm($this);
totten's avatar
totten committed
657 658 659
    }

    foreach ($this->_fields as $field => $values) {
660
      if (!empty($this->_fields[$field])) {
661 662
        $attribute = CRM_Utils_Array::value('attributes', $values);
        $required = !empty($values['required']);
totten's avatar
totten committed
663 664 665 666

        if ($values['type'] == 'wysiwyg') {
          $this->addWysiwyg($field, $values['label'], $attribute, $required);
        }
667
        elseif ($values['type'] == 'select' && empty($attribute)) {
668 669 670 671
          $this->addSelect($field, array('entity' => 'activity'), $required);
        }
        elseif ($values['type'] == 'entityRef') {
          $this->addEntityRef($field, $values['label'], $attribute, $required);
672
        }
673
        else {
colemanw's avatar
colemanw committed
674
          $this->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array::value('extra', $values));
totten's avatar
totten committed
675 676 677 678 679 680 681 682 683 684 685 686 687
        }
      }
    }

    //CRM-7362 --add campaigns.
    CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));

    //add engagement level CRM-7775
    $buildEngagementLevel = FALSE;
    if (CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
      CRM_Campaign_BAO_Campaign::accessCampaign()
    ) {
      $buildEngagementLevel = TRUE;
totten's avatar
totten committed
688
      $this->addSelect('engagement_level', array('entity' => 'activity'));
totten's avatar
totten committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
      $this->addRule('engagement_level',
        ts('Please enter the engagement index as a number (integers only).'),
        'positiveInteger'
      );
    }
    $this->assign('buildEngagementLevel', $buildEngagementLevel);

    // check for survey activity
    $this->_isSurveyActivity = FALSE;

    if ($this->_activityId && CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
      CRM_Campaign_BAO_Campaign::accessCampaign()
    ) {

      $this->_isSurveyActivity = CRM_Campaign_BAO_Survey::isSurveyActivity($this->_activityId);
      if ($this->_isSurveyActivity) {
        $surveyId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
          $this->_activityId,
          'source_record_id'
        );
        $responseOptions = CRM_Campaign_BAO_Survey::getResponsesOptions($surveyId);
        if ($responseOptions) {
          $this->add('select', 'result', ts('Result'),
            array('' => ts('- select -')) + array_combine($responseOptions, $responseOptions)
          );
        }
        $surveyTitle = NULL;
        if ($surveyId) {
          $surveyTitle = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'title');
        }
        $this->assign('surveyTitle', $surveyTitle);
      }
    }
    $this->assign('surveyActivity', $this->_isSurveyActivity);

724
    // this option should be available only during add mode
725
    if ($this->_action != CRM_Core_Action::UPDATE) {
726
      $this->add('advcheckbox', 'is_multi_activity', ts('Create a separate activity for each contact.'));
727 728
    }

totten's avatar
totten committed
729 730 731 732 733 734
    $this->addRule('duration',
      ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger'
    );
    $this->addDateTime('activity_date_time', ts('Date'), TRUE, array('formatType' => 'activityDateTime'));

    //add followup date
735
    $this->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
totten's avatar
totten committed
736

737 738
    // Only admins and case-workers can change the activity source
    if (!CRM_Core_Permission::check('administer CiviCRM') && $this->_context != 'caseActivity') {
739
      $this->getElement('source_contact_id')->freeze();
740
    }
totten's avatar
totten committed
741 742 743 744 745 746

    //need to assign custom data type and subtype to the template
    $this->assign('customDataType', 'Activity');
    $this->assign('customDataSubType', $this->_activityTypeId);
    $this->assign('entityID', $this->_activityId);

747
    CRM_Core_BAO_Tag::getTags('civicrm_activity', $tags, NULL,
748
      '&nbsp;&nbsp;', TRUE);
totten's avatar
totten committed
749 750 751

    if (!empty($tags)) {
      $this->add('select', 'tag', ts('Tags'), $tags, FALSE,
752
        array('id' => 'tags', 'multiple' => 'multiple', 'class' => 'crm-select2 huge')
totten's avatar
totten committed
753 754 755 756 757 758 759 760 761
      );
    }

    // we need to hide activity tagset for special activities
    $specialActivities = array('Open Case');

    if (!in_array($this->_activityTypeName, $specialActivities)) {
      // build tag widget
      $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_activity');
colemanw's avatar
colemanw committed
762
      CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', $this->_activityId);
totten's avatar
totten committed
763 764 765 766 767 768 769 770 771 772
    }

    // if we're viewing, we're assigning different buttons than for adding/editing
    if ($this->_action & CRM_Core_Action::VIEW) {
      if (isset($this->_groupTree)) {
        CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $this->_groupTree);
      }
      // form should be frozen for view mode
      $this->freeze();

colemanw's avatar
colemanw committed
773
      $buttons = array();
totten's avatar
totten committed
774 775
      $buttons[] = array(
        'type' => 'cancel',
776
        'name' => ts('Done'),
totten's avatar
totten committed
777 778 779 780
      );
      $this->addButtons($buttons);
    }
    else {
yashodha's avatar
yashodha committed
781 782
      $message = array(
        '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.'),
totten's avatar
totten committed
783 784 785 786 787 788 789 790
        '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.'),
      );
      $js = array('onclick' => "return activityStatus(" . json_encode($message) . ");");
      $this->addButtons(array(
          array(
            'type' => 'upload',
            'name' => ts('Save'),
            'js' => $js,
791
            'isDefault' => TRUE,
totten's avatar
totten committed
792 793 794
          ),
          array(
            'type' => 'cancel',
795 796
            'name' => ts('Cancel'),
          ),
totten's avatar
totten committed
797 798 799 800 801
        )
      );
    }

    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
802
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
totten's avatar
totten committed
803

lobo's avatar
lobo committed
804 805
      $className::buildQuickForm($this);
      $this->addFormRule(array($className, 'formRule'), $this);
totten's avatar
totten committed
806 807 808
    }

    $this->addFormRule(array('CRM_Activity_Form_Activity', 'formRule'), $this);
809

810
    if (CRM_Core_BAO_Setting::getItem(
yashodha's avatar
yashodha committed
811 812 813
      CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
      'activity_assignee_notification'
    )
814
    ) {
815 816 817 818
      $this->assign('activityAssigneeNotification', TRUE);
    }
    else {
      $this->assign('activityAssigneeNotification', FALSE);
819
    }
totten's avatar
totten committed
820 821 822
  }

  /**
colemanw's avatar
colemanw committed
823
   * Global form rule
totten's avatar
totten committed
824
   *
825 826 827 828
   * @param array $fields
   *   The input form values.
   * @param array $files
   *   The uploaded files if any.
Eileen McNaughton's avatar
Eileen McNaughton committed
829 830
   * @param $self
   *
831 832
   * @return bool|array
   *   true if no errors, else array of errors
totten's avatar
totten committed
833
   */
834
  public static function formRule($fields, $files, $self) {
totten's avatar
totten committed
835 836 837 838 839 840 841 842 843 844
    // skip form rule if deleting
    if (CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Delete') {
      return TRUE;
    }
    $errors = array();
    if (!$self->_single && !$fields['activity_type_id']) {
      $errors['activity_type_id'] = ts('Activity Type is a required field');
    }

    //Activity type is mandatory if creating new activity, CRM-4515
845
    if (array_key_exists('activity_type_id', $fields) && empty($fields['activity_type_id'])) {
totten's avatar
totten committed
846 847 848 849 850 851 852 853 854 855 856 857 858 859
      $errors['activity_type_id'] = ts('Activity Type is required field.');
    }

    if (CRM_Utils_Array::value('activity_type_id', $fields) == 3 &&
      CRM_Utils_Array::value('status_id', $fields) == 1
    ) {
      $errors['status_id'] = ts('You cannot record scheduled email activity.');
    }
    elseif (CRM_Utils_Array::value('activity_type_id', $fields) == 4 &&
      CRM_Utils_Array::value('status_id', $fields) == 1
    ) {
      $errors['status_id'] = ts('You cannot record scheduled SMS activity.');
    }

860
    if (!empty($fields['followup_activity_type_id']) && empty($fields['followup_date'])) {
totten's avatar
totten committed
861 862 863
      $errors['followup_date_time'] = ts('Followup date is a required field.');
    }
    //Activity type is mandatory if subject or follow-up date is specified for an Follow-up activity, CRM-4515
864
    if ((!empty($fields['followup_activity_subject']) || !empty($fields['followup_date'])) && empty($fields['followup_activity_type_id'])) {
totten's avatar
totten committed
865 866 867 868 869 870
      $errors['followup_activity_subject'] = ts('Follow-up Activity type is a required field.');
    }
    return $errors;
  }

  /**
871
   * Process the form submission
totten's avatar
totten committed
872 873
   *
   *
colemanw's avatar
colemanw committed
874 875
   * @param array $params
   * @return array|null
totten's avatar
totten committed
876 877 878 879 880 881 882 883 884 885
   */
  public function postProcess($params = NULL) {
    if ($this->_action & CRM_Core_Action::DELETE) {
      $deleteParams = array('id' => $this->_activityId);
      $moveToTrash = CRM_Case_BAO_Case::isCaseActivity($this->_activityId);
      CRM_Activity_BAO_Activity::deleteActivity($deleteParams, $moveToTrash);

      // delete tags for the entity
      $tagParams = array(
        'entity_table' => 'civicrm_activity',
886
        'entity_id' => $this->_activityId,
totten's avatar
totten committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900
      );

      CRM_Core_BAO_EntityTag::del($tagParams);

      CRM_Core_Session::setStatus(ts("Selected Activity has been deleted successfully."), ts('Record Deleted'), 'success');
      return;
    }

    // store the submitted values in an array
    if (!$params) {
      $params = $this->controller->exportValues($this->_name);
    }

    //set activity type id
901
    if (empty($params['activity_type_id'])) {
totten's avatar
totten committed
902 903 904
      $params['activity_type_id'] = $this->_activityTypeId;
    }

905
    if (!empty($params['hidden_custom']) &&
totten's avatar
totten committed
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
      !isset($params['custom'])
    ) {
      $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
        $this->_activityTypeId
      );
      $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
        CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
          NULL, NULL, TRUE
        )
      );
      $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
        $customFields,
        $this->_activityId,
        'Activity'
      );
    }

    // store the date with proper format
    $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);

926 927 928 929 930 931 932 933
    // format params as arrays
    foreach (array('target', 'assignee', 'followup_assignee') as $name) {
      if (!empty($params["{$name}_contact_id"])) {
        $params["{$name}_contact_id"] = explode(',', $params["{$name}_contact_id"]);
      }
      else {
        $params["{$name}_contact_id"] = array();
      }
totten's avatar
totten committed
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    }

    // get ids for associated contacts
    if (!$params['source_contact_id']) {
      $params['source_contact_id'] = $this->_currentUserId;
    }

    if (isset($this->_activityId)) {
      $params['id'] = $this->_activityId;
    }

    // add attachments as needed
    CRM_Core_BAO_File::formatAttachment($params,
      $params,
      'civicrm_activity',
      $this->_activityId
    );

952
    $activity = array();
953
    if (!empty($params['is_multi_activity']) &&
954 955 956
      !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])
    ) {
      $targetContacts = $params['target_contact_id'];
yashodha's avatar
yashodha committed
957
      foreach ($targetContacts as $targetContactId) {
958 959 960 961 962 963 964 965 966 967
        $params['target_contact_id'] = array($targetContactId);
        // save activity
        $activity[] = $this->processActivity($params);
      }
    }
    else {
      // save activity
      $activity = $this->processActivity($params);
    }

unknown's avatar
unknown committed
968 969 970 971 972
    //Set for repeat configuration in create mode
    $params['entity_id'] = $this->_activityId;
    $params['entity_table'] = 'civicrm_activity';
    $scheduleReminderDetails = array();
    if (!empty($params['entity_id']) && !empty($params['entity_table'])) {
unknown's avatar
unknown committed
973
      $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($params['entity_id'], $params['entity_table']);
unknown's avatar
unknown committed
974 975 976 977 978 979 980 981
      if ($checkParentExistsForThisId) {
        $params['parent_entity_id'] = $checkParentExistsForThisId;
        $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $params['entity_table']);
      }
      else {
        $params['parent_entity_id'] = $params['entity_id'];
        $scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($params['entity_id'], $params['entity_table']);
      }
982 983 984
      if (property_exists($scheduleReminderDetails, 'id')) {
        $params['schedule_reminder_id'] = $scheduleReminderDetails->id;
      }
unknown's avatar
unknown committed
985 986 987 988 989 990 991
    }
    $params['dateColumns'] = array('activity_date_time');

    //Unset activity id
    unset($params['id']);
    $linkedEntities = array(
      array(
totten's avatar
totten committed
992 993
        'table' => 'civicrm_activity_contact',
        'findCriteria' => array(
unknown's avatar
unknown committed
994 995 996 997
          'activity_id' => $this->_activityId,
        ),
        'linkedColumns' => array('activity_id'),
        'isRecurringEntityRecord' => FALSE,
998
      ),
unknown's avatar
unknown committed
999 1000 1001
    );
    CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_activity', $linkedEntities);

1002 1003 1004 1005 1006 1007
    return array('activity' => $activity);
  }

  /**
   * Process activity creation
   *
1008 1009
   * @param array $params
   *   Associated array of submitted values.
1010 1011
   *
   * @return $this|null|object
1012 1013
   */
  protected function processActivity(&$params) {
totten's avatar
totten committed
1014
    $activityAssigned = array();
1015
    $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
yashodha's avatar
yashodha committed
1016
    $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
totten's avatar
totten committed
1017 1018 1019 1020 1021 1022
    // format assignee params
    if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
      //skip those assignee contacts which are already assigned
      //while sending a copy.CRM-4509.
      $activityAssigned = array_flip($params['assignee_contact_id']);
      if ($this->_activityId) {
yashodha's avatar
yashodha committed
1023
        $assigneeContacts = CRM_Activity_BAO_ActivityContact::getNames($this->_activityId, $assigneeID);
totten's avatar
totten committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
        $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
      }
    }

    // call begin post process. Idea is to let injecting file do
    // any processing before the activity is added/updated.
    $this->beginPostProcess($params);

    $activity = CRM_Activity_BAO_Activity::create($params);

    // add tags if exists
    $tagParams = array();
    if (!empty($params['tag'])) {
      foreach ($params['tag'] as $tag) {
        $tagParams[$tag] = 1;
      }
    }

    //save static tags
    CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);

    //save free tags
    if (isset($params['activity_taglist']) && !empty($params['activity_taglist'])) {
      CRM_Core_Form_Tag::postProcess($params['activity_taglist'], $activity->id, 'civicrm_activity', $this);
    }

    // call end post process. Idea is to let injecting file do any
    // processing needed, after the activity has been added/updated.
    $this->endPostProcess($params, $activity);

    // CRM-9590
1055
    if (!empty($params['is_multi_activity'])) {
1056 1057 1058 1059 1060
      $this->_activityIds[] = $activity->id;
    }
    else {
      $this->_activityId = $activity->id;
    }
totten's avatar
totten committed
1061 1062 1063

    // create follow up activity if needed
    $followupStatus = '';
1064
    $followupActivity = NULL;
1065
    if (!empty($params['followup_activity_type_id'])) {
1066
      $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
totten's avatar
totten committed
1067 1068 1069 1070 1071 1072
      $followupStatus = ts('A followup activity has been scheduled.');
    }

    // send copy to assignee contacts.CRM-4509
    $mailStatus = '';

1073
    if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
totten's avatar
totten committed
1074 1075
      'activity_assignee_notification')
    ) {
1076 1077 1078 1079 1080
      $activityIDs = array($activity->id);
      if ($followupActivity) {
        $activityIDs = array_merge($activityIDs, array($followupActivity->id));
      }
      $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityIDs, TRUE, FALSE);
totten's avatar
totten committed
1081

1082 1083 1084 1085 1086 1087 1088 1089
      if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
        $mailToContacts = array();

        //build an associative array with unique email addresses.
        foreach ($activityAssigned as $id => $dnc) {
          if (isset($id) && array_key_exists($id, $assigneeContacts)) {
            $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
          }
totten's avatar
totten committed
1090 1091
        }

1092 1093 1094 1095 1096 1097
        if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
          //include attachments while sending a copy of activity.
          $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);

          $ics = new CRM_Activity_BAO_ICalendar($activity);
          $ics->addAttachment($attachments, $mailToContacts);
totten's avatar
totten committed
1098

1099 1100
          // CRM-8400 add param with _currentlyViewedContactId for URL link in mail
          CRM_Case_BAO_Case::sendActivityCopy(NULL, $activity->id, $mailToContacts, $attachments, NULL);
totten's avatar
totten committed
1101

1102
          $ics->cleanup();
totten's avatar
totten committed
1103

1104 1105 1106
          $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
        }
      }
1107

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
      // Also send email to follow-up activity assignees if set
      if ($followupActivity) {
        $mailToFollowupContacts = array();
        foreach ($assigneeContacts as $values) {
          if ($values['activity_id'] == $followupActivity->id) {
            $mailToFollowupContacts[$values['email']] = $values;
          }
        }

        if (!CRM_Utils_array::crmIsEmptyArray($mailToFollowupContacts)) {
          $ics = new CRM_Activity_BAO_ICalendar($followupActivity);
          $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $followupActivity->id);
          $ics->addAttachment($attachments, $mailToFollowupContacts);
totten's avatar
totten committed
1121

1122 1123 1124 1125 1126 1127
          CRM_Case_BAO_Case::sendActivityCopy(NULL, $followupActivity->id, $mailToFollowupContacts, $attachments, NULL);

          $ics->cleanup();

          $mailStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
        }
totten's avatar
totten committed
1128 1129 1130 1131
      }
    }

    // set status message
1132
    $subject = '';
1133
    if (!empty($params['subject'])) {
1134
      $subject = "'" . $params['subject'] . "'";
totten's avatar
totten committed
1135 1136
    }

1137
    CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2 %3',
1138
      array(
1139
        1 => $subject,
1140
        2 => $followupStatus,
1141
        3 => $mailStatus,
1142 1143
      )
    ), ts('Saved'), 'success');
totten's avatar
totten committed
1144

1145
    return $activity;
totten's avatar
totten committed
1146 1147 1148 1149
  }

  /**
   * Shorthand for getting id by display name (makes code more readable)
Eileen McNaughton's avatar
Eileen McNaughton committed
1150 1151
   * @param $displayName
   * @return null|string
totten's avatar
totten committed
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
   */
  protected function _getIdByDisplayName($displayName) {
    return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
      $displayName,
      'id',
      'sort_name'
    );
  }

  /**
   * Shorthand for getting display name by id (makes code more readable)
Eileen McNaughton's avatar
Eileen McNaughton committed
1163 1164
   * @param $id
   * @return null|string
totten's avatar
totten committed
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
   */
  protected function _getDisplayNameById($id) {
    return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
      $id,
      'sort_name',
      'id'
    );
  }

  /**
colemanw's avatar
colemanw committed
1175
   * Let injecting activity type file do any processing
totten's avatar
totten committed
1176 1177
   * needed, before the activity is added/updated
   *
colemanw's avatar
colemanw committed
1178
   * @param array $params
totten's avatar
totten committed
1179
   */
1180
  public function beginPostProcess(&$params) {
totten's avatar
totten committed
1181
    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
1182 1183
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $className::beginPostProcess($this, $params);
totten's avatar
totten committed
1184 1185 1186 1187
    }
  }

  /**
colemanw's avatar
colemanw committed
1188
   * Let injecting activity type file do any processing
totten's avatar
totten committed
1189 1190
   * needed, after the activity has been added/updated
   *
colemanw's avatar
colemanw committed
1191 1192
   * @param array $params
   * @param $activity
totten's avatar
totten committed
1193
   */
1194
  public function endPostProcess(&$params, &$activity) {
totten's avatar
totten committed
1195
    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
1196
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
colemanw's avatar
colemanw committed
1197
      $className::endPostProcess($this, $params, $activity);
totten's avatar
totten committed
1198 1199
    }
  }
1200

totten's avatar
totten committed
1201
}