Activity.php 41.1 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
Kurund Jalmi's avatar
Kurund Jalmi committed
4
 | CiviCRM version 4.7                                                |
totten's avatar
totten committed
5
 +--------------------------------------------------------------------+
yashodha's avatar
yashodha committed
6
 | Copyright CiviCRM LLC (c) 2004-2018                                |
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
yashodha's avatar
yashodha committed
31
 * @copyright CiviCRM LLC (c) 2004-2018
totten's avatar
totten committed
32 33 34
 */

/**
eileenmcnaugton's avatar
eileenmcnaugton committed
35
 * This class generates form components for Activity.
totten's avatar
totten committed
36 37 38 39 40 41 42 43 44 45
 */
class CRM_Activity_Form_Activity extends CRM_Contact_Form_Task {

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

46
  /**
47
   * Store activity ids when multiple activities are created.
48 49 50 51 52
   *
   * @var int
   */
  public $_activityIds = array();

totten's avatar
totten committed
53
  /**
54
   * The id of activity type.
totten's avatar
totten committed
55 56 57 58 59 60
   *
   * @var int
   */
  public $_activityTypeId;

  /**
61
   * The name of activity type.
totten's avatar
totten committed
62 63 64 65 66 67
   *
   * @var string
   */
  public $_activityTypeName;

  /**
68
   * The id of currently viewed contact.
totten's avatar
totten committed
69 70 71 72 73 74
   *
   * @var int
   */
  public $_currentlyViewedContactId;

  /**
75
   * The id of source contact and target contact.
totten's avatar
totten committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
   *
   * @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;

  /**
98
   * The array of form field attributes.
totten's avatar
totten committed
99 100 101 102 103 104 105 106 107 108 109 110
   *
   * @var array
   */
  public $_fields;

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

111
  /**
112
   * Survey activity.
113 114 115
   *
   * @var boolean
   */
totten's avatar
totten committed
116 117 118 119
  protected $_isSurveyActivity;

  protected $_values = array();

colemanw's avatar
colemanw committed
120
  protected $unsavedWarn = TRUE;
Tim Mallezie's avatar
Tim Mallezie committed
121

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
  /*
   * Is it possible to create separate activities with this form?
   *
   * When TRUE, the form will ask whether the user wants to create separate
   * activities (if the user has specified multiple contacts in the "with"
   * field).
   *
   * When FALSE, the form will create one activity with all contacts together
   * and won't ask the user anything.
   *
   * Note: This is a class property so that child classes can turn off this
   * behavior (e.g. in CRM_Case_Form_Activity)
   *
   * @var boolean
   */
  protected $supportsActivitySeparation = TRUE;

Tim Mallezie's avatar
Tim Mallezie committed
139
  /**
Tim Mallezie's avatar
Tim Mallezie committed
140
   * Explicitly declare the entity api name.
141 142
   *
   * @return string
Tim Mallezie's avatar
Tim Mallezie committed
143 144 145 146
   */
  public function getDefaultEntity() {
    return 'Activity';
  }
unknown's avatar
unknown committed
147

totten's avatar
totten committed
148 149 150 151
  /**
   * The _fields var can be used by sub class to set/unset/edit the
   * form fields based on their requirement
   */
152
  public function setFields() {
153 154 155 156
    // Remove print document activity type
    $unwanted = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, "AND v.name = 'Print PDF Letter'");
    $activityTypes = array_diff_key(CRM_Core_PseudoConstant::ActivityType(FALSE), $unwanted);

totten's avatar
totten committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    $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'),
174
        'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity', 'location'),
175
        'required' => FALSE,
totten's avatar
totten committed
176 177 178 179
      ),
      'details' => array(
        'type' => 'wysiwyg',
        'label' => ts('Details'),
colemanw's avatar
colemanw committed
180
        'attributes' => array('class' => 'huge'),
181
        'required' => FALSE,
totten's avatar
totten committed
182 183 184
      ),
      'status_id' => array(
        'type' => 'select',
185
        'required' => TRUE,
totten's avatar
totten committed
186 187 188
      ),
      'priority_id' => array(
        'type' => 'select',
189
        'required' => TRUE,
totten's avatar
totten committed
190 191
      ),
      'source_contact_id' => array(
192
        'type' => 'entityRef',
totten's avatar
totten committed
193
        'label' => ts('Added By'),
194
        'required' => FALSE,
totten's avatar
totten committed
195
      ),
196 197 198
      'target_contact_id' => array(
        'type' => 'entityRef',
        'label' => ts('With Contact'),
199
        'attributes' => array('multiple' => TRUE, 'create' => TRUE),
200 201 202
      ),
      'assignee_contact_id' => array(
        'type' => 'entityRef',
203
        'label' => ts('Assigned to'),
totten's avatar
totten committed
204 205 206
        'attributes' => array(
          'multiple' => TRUE,
          'create' => TRUE,
207
          'api' => array('params' => array('is_deceased' => 0)),
totten's avatar
totten committed
208
        ),
209 210 211
      ),
      'followup_assignee_contact_id' => array(
        'type' => 'entityRef',
212
        'label' => ts('Assigned to'),
totten's avatar
totten committed
213 214 215
        'attributes' => array(
          'multiple' => TRUE,
          'create' => TRUE,
216
          'api' => array('params' => array('is_deceased' => 0)),
totten's avatar
totten committed
217
        ),
218
      ),
totten's avatar
totten committed
219 220 221
      'followup_activity_type_id' => array(
        'type' => 'select',
        'label' => ts('Followup Activity'),
222
        'attributes' => array('' => '- ' . ts('select activity') . ' -') + $activityTypes,
colemanw's avatar
colemanw committed
223
        'extra' => array('class' => 'crm-select2'),
totten's avatar
totten committed
224 225 226 227 228 229 230
      ),
      // 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'
231 232
        ),
      ),
totten's avatar
totten committed
233 234 235 236
    );
  }

  /**
237
   * Build the form object.
totten's avatar
totten committed
238
   */
239
  public function preProcess() {
unknown's avatar
unknown committed
240
    CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
totten's avatar
totten committed
241 242 243 244 245 246 247
    $this->_atypefile = CRM_Utils_Array::value('atypefile', $_GET);
    $this->assign('atypefile', FALSE);
    if ($this->_atypefile) {
      $this->assign('atypefile', TRUE);
    }

    $session = CRM_Core_Session::singleton();
248
    $this->_currentUserId = CRM_Core_Session::getLoggedInContactID();
totten's avatar
totten committed
249 250 251 252 253 254 255

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

256
    // Give the context.
totten's avatar
totten committed
257 258 259 260 261
    if (!isset($this->_context)) {
      $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
      if (CRM_Contact_Form_Search::isSearchContext($this->_context)) {
        $this->_context = 'search';
      }
262
      elseif (!in_array($this->_context, array('dashlet', 'case', 'dashletFullscreen'))
totten's avatar
totten committed
263 264 265 266 267 268 269 270 271 272 273 274 275
        && $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')) {
276
        CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
totten's avatar
totten committed
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.
totten's avatar
totten committed
283 284 285 286 287 288 289 290 291 292 293 294

    // 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
295 296
    $this->assign('activityId', $this->_activityId);

297
    // Check for required permissions, CRM-6264.
totten's avatar
totten committed
298 299
    if ($this->_activityId &&
      in_array($this->_action, array(
yashodha's avatar
yashodha committed
300
        CRM_Core_Action::UPDATE,
301
        CRM_Core_Action::VIEW,
yashodha's avatar
yashodha committed
302
      )) &&
totten's avatar
totten committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
      !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'
      );
    }

320
    // Assigning Activity type name.
totten's avatar
totten committed
321
    if ($this->_activityTypeId) {
322
      $activityTName = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, 'AND v.value = ' . $this->_activityTypeId, 'label');
totten's avatar
totten committed
323 324 325 326 327 328
      if ($activityTName[$this->_activityTypeId]) {
        $this->_activityTypeName = $activityTName[$this->_activityTypeId];
        $this->assign('activityTName', $activityTName[$this->_activityTypeId]);
      }
    }

329
    // Set title.
totten's avatar
totten committed
330
    if (isset($activityTName)) {
331
      $activityName = CRM_Utils_Array::value($this->_activityTypeId, $activityTName);
332
      $this->assign('pageTitle', ts('%1 Activity', array(1 => $activityName)));
333 334 335

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

347 348
    // Check the mode when this form is called either single or as
    // search task action.
totten's avatar
totten committed
349 350 351 352 353 354 355 356
    if ($this->_activityTypeId ||
      $this->_context == 'standalone' ||
      $this->_currentlyViewedContactId
    ) {
      $this->_single = TRUE;
      $this->assign('urlPath', 'civicrm/activity');
    }
    else {
357
      // Set the appropriate action.
totten's avatar
totten committed
358 359
      $url = CRM_Utils_System::currentPath();
      $urlArray = explode('/', $url);
yashodha's avatar
yashodha committed
360
      $searchPath = array_pop($urlArray);
totten's avatar
totten committed
361 362
      $searchType = 'basic';
      $this->_action = CRM_Core_Action::BASIC;
yashodha's avatar
yashodha committed
363
      switch ($searchPath) {
totten's avatar
totten committed
364
        case 'basic':
yashodha's avatar
yashodha committed
365
          $searchType = $searchPath;
totten's avatar
totten committed
366 367 368 369
          $this->_action = CRM_Core_Action::BASIC;
          break;

        case 'advanced':
yashodha's avatar
yashodha committed
370
          $searchType = $searchPath;
totten's avatar
totten committed
371 372 373 374
          $this->_action = CRM_Core_Action::ADVANCED;
          break;

        case 'builder':
yashodha's avatar
yashodha committed
375
          $searchType = $searchPath;
totten's avatar
totten committed
376 377 378 379 380
          $this->_action = CRM_Core_Action::PROFILE;
          break;

        case 'custom':
          $this->_action = CRM_Core_Action::COPY;
yashodha's avatar
yashodha committed
381
          $searchType = $searchPath;
totten's avatar
totten committed
382 383 384 385 386 387 388 389 390 391 392 393 394 395
          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) {
396
      // Get the tree of custom fields.
397
      $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Activity', NULL,
totten's avatar
totten committed
398 399 400 401 402
        $this->_activityId, 0, $this->_activityTypeId
      );
    }

    if ($this->_activityTypeId) {
403
      // Set activity type name and description to template.
totten's avatar
totten committed
404 405 406 407 408 409 410
      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
411 412 413 414
    $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
    if (!$qfKey) {
      $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
    }
totten's avatar
totten committed
415

416
    // Validate the qfKey.
totten's avatar
totten committed
417 418 419 420 421
    if (!CRM_Utils_Rule::qfKey($qfKey)) {
      $qfKey = NULL;
    }

    if ($this->_context == 'fulltext') {
yashodha's avatar
yashodha committed
422
      $keyName = '&qfKey';
totten's avatar
totten committed
423 424 425 426 427 428 429 430 431 432 433 434 435
      $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
436 437 438
      'standalone',
      'home',
      'dashlet',
439
      'dashletFullscreen',
yashodha's avatar
yashodha committed
440 441
    ))
    ) {
totten's avatar
totten committed
442 443 444 445 446 447 448 449
      $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
450
      $path = CRM_Utils_System::currentPath();
451
      if ($this->_compContext == 'advanced') {
totten's avatar
totten committed
452 453
        $urlString = 'civicrm/contact/search/advanced';
      }
454
      elseif ($path == 'civicrm/group/search'
totten's avatar
totten committed
455
        || $path == 'civicrm/contact/search'
456
        || $path == 'civicrm/contact/search/advanced'
457
        || $path == 'civicrm/contact/search/custom'
totten's avatar
totten committed
458 459
        || $path == 'civicrm/group/search'
      ) {
460 461
        $urlString = $path;
      }
totten's avatar
totten committed
462
      else {
463
        $urlString = 'civicrm/activity/search';
totten's avatar
totten committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
      }
      $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
482
    if (!empty($_POST['hidden_custom'])) {
483
      // We need to set it in the session for the code below to work.
totten's avatar
totten committed
484
      // CRM-3014
485
      // Need to assign custom data subtype to the template.
totten's avatar
totten committed
486 487 488
      $this->set('type', 'Activity');
      $this->set('subType', $this->_activityTypeId);
      $this->set('entityId', $this->_activityId);
489
      CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_activityTypeId, 1, 'Activity', $this->_activityId);
totten's avatar
totten committed
490 491 492 493 494 495 496 497 498
      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 &&
totten's avatar
totten committed
499
      $this->_activityTypeFile = CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, $this->_crmDir)
totten's avatar
totten committed
500 501 502 503 504 505 506 507
    ) {
      $this->assign('activityTypeFile', $this->_activityTypeFile);
      $this->assign('crmDir', $this->_crmDir);
    }

    $this->setFields();

    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
508 509
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $className::preProcess($this);
totten's avatar
totten committed
510 511 512 513 514 515 516 517 518 519 520
    }

    $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
521

522
    if ($this->_action & CRM_Core_Action::UPDATE) {
523
      CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
524
    }
totten's avatar
totten committed
525
  }
unknown's avatar
unknown committed
526

totten's avatar
totten committed
527
  /**
eileenmcnaugton's avatar
eileenmcnaugton committed
528
   * Set default values for the form.
totten's avatar
totten committed
529
   *
eileenmcnaugton's avatar
eileenmcnaugton committed
530
   * For edit/view mode the default values are retrieved from the database.
531 532
   *
   * @return array
totten's avatar
totten committed
533
   */
534
  public function setDefaultValues() {
totten's avatar
totten committed
535

536
    $defaults = $this->_values + CRM_Core_Form_RecurringEntity::setDefaultValues();
totten's avatar
totten committed
537 538
    // if we're editing...
    if (isset($this->_activityId)) {
539
      if (empty($defaults['activity_date_time'])) {
totten's avatar
totten committed
540 541 542 543 544 545
        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
546
          ) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
547
        list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
totten's avatar
totten committed
548 549 550 551 552 553 554 555 556 557 558
      }

      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)
        );
      }

559
      // Fixme: why are we getting the wrong keys from upstream?
jitendra's avatar
jitendra committed
560 561
      $defaults['target_contact_id'] = CRM_Utils_Array::value('target_contact', $defaults);
      $defaults['assignee_contact_id'] = CRM_Utils_Array::value('assignee_contact', $defaults);
562

totten's avatar
totten committed
563
      // set default tags if exists
564
      $defaults['tag'] = implode(',', CRM_Core_BAO_EntityTag::getTag($this->_activityId, 'civicrm_activity'));
totten's avatar
totten committed
565 566 567 568 569 570
    }
    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;

571
      $defaults['source_contact_id'] = $this->_sourceContactId;
572
      $defaults['target_contact_id'] = $this->_targetContactId;
totten's avatar
totten committed
573

totten's avatar
totten committed
574 575
      list($defaults['activity_date_time'], $defaults['activity_date_time_time'])
        = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
totten's avatar
totten committed
576 577 578 579 580 581
    }

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

582 583 584 585
    if (!$this->_single && !empty($this->_contactIds)) {
      $defaults['target_contact_id'] = $this->_contactIds;
    }

Dmitry Smirnov's avatar
Dmitry Smirnov committed
586
    // CRM-15472 - 50 is around the practical limit of how many items a select2 entityRef can handle
587
    if ($this->_action == 2 && !empty($defaults['target_contact_id'])) {
588 589 590 591 592 593
      $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
594 595 596 597 598
    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
599 600
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $defaults += $className::setDefaultValues($this);
totten's avatar
totten committed
601
    }
602
    if (empty($defaults['priority_id'])) {
603
      $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
totten's avatar
totten committed
604 605
      $defaults['priority_id'] = array_search('Normal', $priority);
    }
606
    if (empty($defaults['status_id'])) {
607 608
      $defaults['status_id'] = CRM_Core_OptionGroup::getDefaultValue('activity_status');
    }
totten's avatar
totten committed
609 610 611 612 613 614 615 616 617 618 619 620 621
    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
622 623 624 625
        array(
          'type' => 'next',
          'name' => $button,
          'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
626
          'isDefault' => TRUE,
yashodha's avatar
yashodha committed
627 628 629
        ),
        array(
          'type' => 'cancel',
630 631
          'name' => ts('Cancel'),
        ),
yashodha's avatar
yashodha committed
632
      ));
totten's avatar
totten committed
633 634 635
      return;
    }

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

639
    // Enable form element (ActivityLinks sets this true).
totten's avatar
totten committed
640 641
    $this->assign('suppressForm', FALSE);

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

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

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

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

colemanw's avatar
colemanw committed
665
        if ($values['type'] == 'select' && empty($attribute)) {
666 667 668 669
          $this->addSelect($field, array('entity' => 'activity'), $required);
        }
        elseif ($values['type'] == 'entityRef') {
          $this->addEntityRef($field, $values['label'], $attribute, $required);
670
        }
671
        else {
colemanw's avatar
colemanw committed
672
          $this->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array::value('extra', $values));
totten's avatar
totten committed
673 674 675 676
        }
      }
    }

677
    // CRM-7362 --add campaigns.
totten's avatar
totten committed
678 679
    CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));

680
    // Add engagement level CRM-7775
totten's avatar
totten committed
681 682 683 684 685
    $buildEngagementLevel = FALSE;
    if (CRM_Campaign_BAO_Campaign::isCampaignEnable() &&
      CRM_Campaign_BAO_Campaign::accessCampaign()
    ) {
      $buildEngagementLevel = TRUE;
totten's avatar
totten committed
686
      $this->addSelect('engagement_level', array('entity' => 'activity'));
totten's avatar
totten committed
687 688 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
      $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);

722 723 724 725
    // Add the "Activity Separation" field
    $actionIsAdd = $this->_action != CRM_Core_Action::UPDATE;
    $separationIsPossible = $this->supportsActivitySeparation;
    if ($actionIsAdd && $separationIsPossible) {
726 727 728 729 730 731 732 733
      $this->addRadio(
        'separation',
        ts('Activity Separation'),
        array(
          'separate' => ts('Create separate activities for each contact'),
          'combined' => ts('Create one activity with all contacts together'),
        )
      );
734 735
    }

totten's avatar
totten committed
736 737 738 739 740
    $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'));

741
    // Add followup date.
742
    $this->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
totten's avatar
totten committed
743

744 745
    // Only admins and case-workers can change the activity source
    if (!CRM_Core_Permission::check('administer CiviCRM') && $this->_context != 'caseActivity') {
746
      $this->getElement('source_contact_id')->freeze();
747
    }
totten's avatar
totten committed
748 749 750 751 752 753

    //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);

754
    $tags = CRM_Core_BAO_Tag::getColorTags('civicrm_activity');
totten's avatar
totten committed
755 756

    if (!empty($tags)) {
757
      $this->add('select2', 'tag', ts('Tags'), $tags, FALSE, array('class' => 'huge', 'placeholder' => ts('- select -'), 'multiple' => TRUE));
totten's avatar
totten committed
758 759 760 761 762 763 764 765
    }

    // 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
766
      CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', $this->_activityId);
totten's avatar
totten committed
767 768 769 770 771
    }

    // if we're viewing, we're assigning different buttons than for adding/editing
    if ($this->_action & CRM_Core_Action::VIEW) {
      if (isset($this->_groupTree)) {
monishdeb's avatar
monishdeb committed
772
        CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $this->_groupTree, FALSE, NULL, NULL, NULL, $this->_activityId);
totten's avatar
totten committed
773 774 775 776
      }
      // form should be frozen for view mode
      $this->freeze();

colemanw's avatar
colemanw committed
777
      $buttons = array();
totten's avatar
totten committed
778 779
      $buttons[] = array(
        'type' => 'cancel',
780
        'name' => ts('Done'),
totten's avatar
totten committed
781 782 783 784
      );
      $this->addButtons($buttons);
    }
    else {
yashodha's avatar
yashodha committed
785 786
      $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
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(
791 792 793 794 795 796 797 798 799 800 801
        array(
          'type' => 'upload',
          'name' => ts('Save'),
          'js' => $js,
          'isDefault' => TRUE,
        ),
        array(
          'type' => 'cancel',
          'name' => ts('Cancel'),
        ),
      ));
totten's avatar
totten committed
802 803 804
    }

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

lobo's avatar
lobo committed
807 808
      $className::buildQuickForm($this);
      $this->addFormRule(array($className, 'formRule'), $this);
totten's avatar
totten committed
809 810 811
    }

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

eileen's avatar
eileen committed
813
    $doNotNotifyAssigneeFor = (array) Civi::settings()->get('do_not_notify_assignees_for');
814 815
    if (($this->_activityTypeId && in_array($this->_activityTypeId, $doNotNotifyAssigneeFor)) || !Civi::settings()->get('activity_assignee_notification')) {
      $this->assign('activityAssigneeNotification', FALSE);
816 817
    }
    else {
818
      $this->assign('activityAssigneeNotification', TRUE);
819
    }
820
    $this->assign('doNotNotifyAssigneeFor', $doNotNotifyAssigneeFor);
totten's avatar
totten committed
821 822 823
  }

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

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

    // Check that a value has been set for the "activity separation" field if needed
    $separationIsPossible = $self->supportsActivitySeparation;
866 867 868
    $actionIsAdd = $self->_action == CRM_Core_Action::ADD;
    $hasMultipleTargetContacts = !empty($fields['target_contact_id']) && strpos($fields['target_contact_id'], ',') !== FALSE;
    $separationFieldIsEmpty = empty($fields['separation']);
869
    if ($separationIsPossible && $actionIsAdd && $hasMultipleTargetContacts && $separationFieldIsEmpty) {
870 871
      $errors['separation'] = ts('Activity Separation is a required field.');
    }
872

totten's avatar
totten committed
873 874 875 876
    return $errors;
  }

  /**
877
   * Process the form submission.
totten's avatar
totten committed
878 879
   *
   *
colemanw's avatar
colemanw committed
880 881
   * @param array $params
   * @return array|null
totten's avatar
totten committed
882 883 884 885 886 887 888 889 890 891
   */
  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',
892
        'entity_id' => $this->_activityId,
totten's avatar
totten committed
893 894 895 896 897
      );

      CRM_Core_BAO_EntityTag::del($tagParams);

      CRM_Core_Session::setStatus(ts("Selected Activity has been deleted successfully."), ts('Record Deleted'), 'success');
totten's avatar
totten committed
898
      return NULL;
totten's avatar
totten committed
899 900 901 902 903 904 905
    }

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

906
    // Set activity type id.
907
    if (empty($params['activity_type_id'])) {
totten's avatar
totten committed
908 909 910
      $params['activity_type_id'] = $this->_activityTypeId;
    }

911
    if (!empty($params['hidden_custom']) &&
totten's avatar
totten committed
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
      !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,
        $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']);

931 932 933 934 935 936 937 938
    // 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
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    }

    // 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
    );

957 958
    $params['is_multi_activity'] = CRM_Utils_Array::value('separation', $params) == 'separate';

959
    $activity = array();
960
    if (!empty($params['is_multi_activity']) &&
961 962 963
      !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])
    ) {
      $targetContacts = $params['target_contact_id'];
yashodha's avatar
yashodha committed
964
      foreach ($targetContacts as $targetContactId) {
965 966 967 968 969 970 971 972 973 974
        $params['target_contact_id'] = array($targetContactId);
        // save activity
        $activity[] = $this->processActivity($params);
      }
    }
    else {
      // save activity
      $activity = $this->processActivity($params);
    }

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
    $activityIds = empty($this->_activityIds) ? array($this->_activityId) : $this->_activityIds;
    foreach ($activityIds as $activityId) {
      // set params for repeat configuration in create mode
      $params['entity_id'] = $activityId;
      $params['entity_table'] = 'civicrm_activity';
      if (!empty($params['entity_id']) && !empty($params['entity_table'])) {
        $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($params['entity_id'], $params['entity_table']);
        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']);
        }
        if (property_exists($scheduleReminderDetails, 'id')) {
          $params['schedule_reminder_id'] = $scheduleReminderDetails->id;
        }
993
      }
994
      $params['dateColumns'] = array('activity_date_time');
unknown's avatar
unknown committed
995

colemanw's avatar
colemanw committed
996 997 998 999 1000
      // Set default repetition start if it was not provided.
      if (empty($params['repetition_start_date'])) {
        $params['repetition_start_date'] = $params['activity_date_time'];
      }

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
      // unset activity id
      unset($params['id']);
      $linkedEntities = array(
        array(
          'table' => 'civicrm_activity_contact',
          'findCriteria' => array(
            'activity_id' => $activityId,
          ),
          'linkedColumns' => array('activity_id'),
          'isRecurringEntityRecord' => FALSE,
unknown's avatar
unknown committed
1011
        ),
1012 1013 1014
      );
      CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_activity', $linkedEntities);
    }
unknown's avatar
unknown committed
1015

1016 1017 1018 1019
    return array('activity' => $activity);
  }

  /**
1020
   * Process activity creation.
1021
   *
1022 1023
   * @param array $params
   *   Associated array of submitted values.
1024
   *
totten's avatar
totten committed
1025
   * @return self|null|object
1026 1027
   */
  protected function processActivity(&$params) {
totten's avatar
totten committed
1028
    $activityAssigned = array();
1029
    $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
yashodha's avatar
yashodha committed
1030
    $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
totten's avatar
totten committed
1031 1032 1033 1034 1035 1036
    // 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
1037
        $assigneeContacts = CRM_Activity_BAO_ActivityContact::getNames($this->_activityId, $assigneeID);
totten's avatar
totten committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        $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'])) {
1051 1052 1053
      if (!is_array($params['tag'])) {
        $params['tag'] = explode(',', $params['tag']);
      }
totten's avatar
totten committed
1054 1055 1056 1057 1058
      foreach ($params['tag'] as $tag) {
        $tagParams[$tag] = 1;
      }
    }

1059
    // Save static tags.
totten's avatar
totten committed
1060 1061
    CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);

1062
    // Save free tags.
totten's avatar
totten committed
1063 1064 1065 1066 1067 1068 1069 1070 1071
    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
1072
    if (!empty($params['is_multi_activity'])) {
1073 1074 1075 1076 1077
      $this->_activityIds[] = $activity->id;
    }
    else {
      $this->_activityId = $activity->id;
    }
totten's avatar
totten committed
1078 1079 1080

    // create follow up activity if needed
    $followupStatus = '';
1081
    $followupActivity = NULL;
1082
    if (!empty($params['followup_activity_type_id'])) {
1083
      $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
totten's avatar
totten committed
1084 1085 1086 1087 1088 1089
      $followupStatus = ts('A followup activity has been scheduled.');
    }

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

1090
    if (Civi::settings()->get('activity_assignee_notification')
jitendra's avatar
jitendra committed
1091
      && !in_array($activity->activity_type_id, Civi::settings()->get('do_not_notify_assignees_for'))) {
1092 1093 1094 1095 1096
      $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
1097

1098 1099 1100
      if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
        $mailToContacts = array();

1101
        // Build an associative array with unique email addresses.
1102 1103 1104 1105
        foreach ($activityAssigned as $id => $dnc) {
          if (isset($id) && array_key_exists($id, $assigneeContacts)) {
            $mailToContacts[$assigneeContacts[$id]['email']] = $assigneeContacts[$id];
          }
totten's avatar
totten committed
1106 1107
        }

yashodha's avatar
cleanup  
yashodha committed
1108 1109 1110 1111 1112
        $sent = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts);
        if ($sent) {
          $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
        }
      }
1113

1114 1115 1116 1117 1118 1119 1120 1121 1122
      // 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;
          }
        }

yashodha's avatar
cleanup  
yashodha committed
1123
        $sentFollowup = CRM_Activity_BAO_Activity::sendToAssignee($followupActivity, $mailToFollowupContacts);
yashodha's avatar
cleanup  
yashodha committed
1124
        if ($sentFollowup) {
yashodha's avatar
cleanup  
yashodha committed
1125
          $mailStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
yashodha's avatar
cleanup  
yashodha committed
1126
        }
totten's avatar
totten committed
1127 1128 1129 1130
      }
    }

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

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

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

  /**
   * Shorthand for getting id by display name (makes code more readable)
Eileen McNaughton's avatar
Eileen McNaughton committed
1149 1150
   * @param $displayName
   * @return null|string
totten's avatar
totten committed
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
   */
  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
1162 1163
   * @param $id
   * @return null|string
totten's avatar
totten committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
   */
  protected function _getDisplayNameById($id) {
    return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
      $id,
      'sort_name',
      'id'
    );
  }

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

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

totten's avatar
totten committed
1200
}