Activity.php 40.2 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 Jalmi's avatar
Kurund Jalmi 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 26 27 28 29 30
 +--------------------------------------------------------------------+
 | 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        |
 +--------------------------------------------------------------------+
*/

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

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

  /**
210
   * Build the form object
totten's avatar
totten committed
211
   *
colemanw's avatar
colemanw committed
212
   * @return void
totten's avatar
totten committed
213
   */
214
  public function preProcess() {
totten's avatar
totten committed
215 216 217 218 219 220
    $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
221
    CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
totten's avatar
totten committed
222 223 224 225 226 227 228 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
    $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')) {
257
        CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
totten's avatar
totten committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
      }
    }

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

totten's avatar
totten committed
278 279 280
    //check for required permissions, CRM-6264
    if ($this->_activityId &&
      in_array($this->_action, array(
yashodha's avatar
yashodha committed
281 282 283
        CRM_Core_Action::UPDATE,
        CRM_Core_Action::VIEW
      )) &&
totten's avatar
totten committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
      !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]);
      }
    }

310
    // Set title
totten's avatar
totten committed
311
    if (isset($activityTName)) {
312
      $activityName = CRM_Utils_Array::value($this->_activityTypeId, $activityTName);
313
      $this->assign('pageTitle', ts('%1 Activity', array(1 => $activityName)));
314 315 316 317 318 319 320 321 322 323

      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 {
324
        CRM_Utils_System::setTitle(ts('%1 Activity', array(1 => $activityName)));
325
      }
totten's avatar
totten committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    }

    //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
341
      $searchPath = array_pop($urlArray);
totten's avatar
totten committed
342 343
      $searchType = 'basic';
      $this->_action = CRM_Core_Action::BASIC;
yashodha's avatar
yashodha committed
344
      switch ($searchPath) {
totten's avatar
totten committed
345
        case 'basic':
yashodha's avatar
yashodha committed
346
          $searchType = $searchPath;
totten's avatar
totten committed
347 348 349 350
          $this->_action = CRM_Core_Action::BASIC;
          break;

        case 'advanced':
yashodha's avatar
yashodha committed
351
          $searchType = $searchPath;
totten's avatar
totten committed
352 353 354 355
          $this->_action = CRM_Core_Action::ADVANCED;
          break;

        case 'builder':
yashodha's avatar
yashodha committed
356
          $searchType = $searchPath;
totten's avatar
totten committed
357 358 359 360 361
          $this->_action = CRM_Core_Action::PROFILE;
          break;

        case 'custom':
          $this->_action = CRM_Core_Action::COPY;
yashodha's avatar
yashodha committed
362
          $searchType = $searchPath;
totten's avatar
totten committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
          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
392 393 394 395
    $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
    if (!$qfKey) {
      $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
    }
totten's avatar
totten committed
396 397 398 399 400 401 402

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

    if ($this->_context == 'fulltext') {
yashodha's avatar
yashodha committed
403
      $keyName = '&qfKey';
totten's avatar
totten committed
404 405 406 407 408 409 410 411 412 413 414 415 416
      $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
417 418 419 420 421 422
      'standalone',
      'home',
      'dashlet',
      'dashletFullscreen'
    ))
    ) {
totten's avatar
totten committed
423 424 425 426 427 428 429 430
      $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
431
      $path = CRM_Utils_System::currentPath();
432
      if ($this->_compContext == 'advanced') {
totten's avatar
totten committed
433 434
        $urlString = 'civicrm/contact/search/advanced';
      }
435
      elseif ($path == 'civicrm/group/search'
totten's avatar
totten committed
436
    || $path == 'civicrm/contact/search'
437
        || $path == 'civicrm/contact/search/advanced'
438 439
        || $path == 'civicrm/contact/search/custom'
        || $path == 'civicrm/group/search') {
440 441
        $urlString = $path;
      }
totten's avatar
totten committed
442
      else {
443
        $urlString = 'civicrm/activity/search';
totten's avatar
totten committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
      }
      $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
462
    if (!empty($_POST['hidden_custom'])) {
totten's avatar
totten committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
      // 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
480
        CRM_Activity_BAO_Activity::getFileForActivityTypeId($this->_activityTypeId, $this->_crmDir)
totten's avatar
totten committed
481 482 483 484 485 486 487 488
    ) {
      $this->assign('activityTypeFile', $this->_activityTypeFile);
      $this->assign('crmDir', $this->_crmDir);
    }

    $this->setFields();

    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
489 490
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $className::preProcess($this);
totten's avatar
totten committed
491 492 493 494 495 496 497 498 499 500 501
    }

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

503
    if ($this->_action & CRM_Core_Action::UPDATE) {
504
      CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
505
    }
totten's avatar
totten committed
506
  }
unknown's avatar
unknown committed
507

totten's avatar
totten committed
508
  /**
509
   * Set default values for the form. For edit/view mode
totten's avatar
totten committed
510 511 512
   * the default values are retrieved from the database
   *
   *
colemanw's avatar
colemanw committed
513
   * @return void
totten's avatar
totten committed
514
   */
515
  public function setDefaultValues() {
totten's avatar
totten committed
516 517 518 519 520 521 522
    if ($this->_cdType) {
      return CRM_Custom_Form_CustomData::setDefaultValues($this);
    }

    $defaults = $this->_values;
    // if we're editing...
    if (isset($this->_activityId)) {
523
      if (empty($defaults['activity_date_time'])) {
totten's avatar
totten committed
524 525 526 527 528 529
        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
530
          ) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
531 532 533 534
        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
535 536 537 538 539 540 541 542 543 544 545
      }

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

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

totten's avatar
totten committed
550 551 552 553 554 555 556 557
      // 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;

558
      $defaults['source_contact_id'] = $this->_sourceContactId;
559
      $defaults['target_contact_id'] = $this->_targetContactId;
totten's avatar
totten committed
560 561 562 563 564 565 566 567 568

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

569 570 571 572
    if (!$this->_single && !empty($this->_contactIds)) {
      $defaults['target_contact_id'] = $this->_contactIds;
    }

573 574 575 576 577 578 579 580
    // 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
581 582 583 584 585
    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
586 587
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $defaults += $className::setDefaultValues($this);
totten's avatar
totten committed
588
    }
589
    if (empty($defaults['priority_id'])) {
590
      $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
totten's avatar
totten committed
591 592
      $defaults['priority_id'] = array_search('Normal', $priority);
    }
593
    if (empty($defaults['status_id'])) {
594 595
      $defaults['status_id'] = CRM_Core_OptionGroup::getDefaultValue('activity_status');
    }
totten's avatar
totten committed
596 597 598 599 600 601 602 603 604 605 606 607 608
    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
609 610 611 612 613 614 615 616 617 618 619
        array(
          'type' => 'next',
          'name' => $button,
          'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
          'isDefault' => TRUE
        ),
        array(
          'type' => 'cancel',
          'name' => ts('Cancel')
        )
      ));
totten's avatar
totten committed
620 621 622 623 624 625 626 627
      return;
    }

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

    //build other activity links
lobo's avatar
lobo committed
628
    CRM_Activity_Form_ActivityLinks::commonBuildQuickForm($this);
totten's avatar
totten committed
629 630 631 632

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

yashodha's avatar
yashodha committed
633
    $element = & $this->add('select', 'activity_type_id', ts('Activity Type'),
totten's avatar
totten committed
634 635
      $this->_fields['followup_activity_type_id']['attributes'],
      FALSE, array(
636 637
        'onchange' => "CRM.buildCustomData( 'Activity', this.value );",
        'class' => 'crm-select2',
totten's avatar
totten committed
638 639 640 641 642 643
      )
    );

    //freeze for update mode.
    if ($this->_action & CRM_Core_Action::UPDATE) {
      $element->freeze();
unknown's avatar
unknown committed
644 645 646 647
    }

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

    foreach ($this->_fields as $field => $values) {
652
      if (!empty($this->_fields[$field])) {
653 654
        $attribute = CRM_Utils_Array::value('attributes', $values);
        $required = !empty($values['required']);
totten's avatar
totten committed
655 656 657 658

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

    //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
680
      $this->addSelect('engagement_level', array('entity' => 'activity'));
totten's avatar
totten committed
681 682 683 684 685 686 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
      $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);

716
    // this option should be available only during add mode
717
    if ($this->_action != CRM_Core_Action::UPDATE) {
718
      $this->add('advcheckbox', 'is_multi_activity', ts('Create a separate activity for each contact.'));
719 720
    }

totten's avatar
totten committed
721 722 723 724 725 726
    $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
727
    $this->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
totten's avatar
totten committed
728

729 730
    // Only admins and case-workers can change the activity source
    if (!CRM_Core_Permission::check('administer CiviCRM') && $this->_context != 'caseActivity') {
731
      $this->getElement('source_contact_id')->freeze();
732
    }
totten's avatar
totten committed
733 734 735 736 737 738

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

739
    CRM_Core_BAO_Tag::getTags('civicrm_activity', $tags, NULL,
740
      '&nbsp;&nbsp;', TRUE);
totten's avatar
totten committed
741 742 743

    if (!empty($tags)) {
      $this->add('select', 'tag', ts('Tags'), $tags, FALSE,
744
        array('id' => 'tags', 'multiple' => 'multiple', 'class' => 'crm-select2 huge')
totten's avatar
totten committed
745 746 747 748 749 750 751 752 753
      );
    }

    // 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
754
      CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_activity', $this->_activityId);
totten's avatar
totten committed
755 756 757 758 759 760 761 762 763 764
    }

    // 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
765
      $buttons = array();
totten's avatar
totten committed
766 767 768 769 770 771 772
      $buttons[] = array(
        'type' => 'cancel',
        'name' => ts('Done')
      );
      $this->addButtons($buttons);
    }
    else {
yashodha's avatar
yashodha committed
773 774
      $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
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
        '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,
            'isDefault' => TRUE
          ),
          array(
            'type' => 'cancel',
            'name' => ts('Cancel')
          )
        )
      );
    }

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

lobo's avatar
lobo committed
796 797
      $className::buildQuickForm($this);
      $this->addFormRule(array($className, 'formRule'), $this);
totten's avatar
totten committed
798 799 800
    }

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

802
    if (CRM_Core_BAO_Setting::getItem(
yashodha's avatar
yashodha committed
803 804 805
      CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
      'activity_assignee_notification'
    )
806
    ) {
807 808 809 810
      $this->assign('activityAssigneeNotification', TRUE);
    }
    else {
      $this->assign('activityAssigneeNotification', FALSE);
811
    }
totten's avatar
totten committed
812 813 814
  }

  /**
colemanw's avatar
colemanw committed
815
   * Global form rule
totten's avatar
totten committed
816
   *
817 818 819 820
   * @param array $fields
   *   The input form values.
   * @param array $files
   *   The uploaded files if any.
Eileen McNaughton's avatar
Eileen McNaughton committed
821 822
   * @param $self
   *
totten's avatar
totten committed
823 824 825
   * @return true if no errors, else array of errors
   * @static
   */
826
  public static function formRule($fields, $files, $self) {
totten's avatar
totten committed
827 828 829 830 831 832 833 834 835 836
    // 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
837
    if (array_key_exists('activity_type_id', $fields) && empty($fields['activity_type_id'])) {
totten's avatar
totten committed
838 839 840 841 842 843 844 845 846 847 848 849 850 851
      $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.');
    }

852
    if (!empty($fields['followup_activity_type_id']) && empty($fields['followup_date'])) {
totten's avatar
totten committed
853 854 855
      $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
856
    if ((!empty($fields['followup_activity_subject']) || !empty($fields['followup_date'])) && empty($fields['followup_activity_type_id'])) {
totten's avatar
totten committed
857 858 859 860 861 862
      $errors['followup_activity_subject'] = ts('Follow-up Activity type is a required field.');
    }
    return $errors;
  }

  /**
863
   * Process the form submission
totten's avatar
totten committed
864 865
   *
   *
colemanw's avatar
colemanw committed
866 867
   * @param array $params
   * @return array|null
totten's avatar
totten committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
   */
  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',
        'entity_id' => $this->_activityId
      );

      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
893
    if (empty($params['activity_type_id'])) {
totten's avatar
totten committed
894 895 896
      $params['activity_type_id'] = $this->_activityTypeId;
    }

897
    if (!empty($params['hidden_custom']) &&
totten's avatar
totten committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
      !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']);

918 919 920 921 922 923 924 925
    // 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
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    }

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

944
    $activity = array();
945
    if (!empty($params['is_multi_activity']) &&
946 947 948
      !CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])
    ) {
      $targetContacts = $params['target_contact_id'];
yashodha's avatar
yashodha committed
949
      foreach ($targetContacts as $targetContactId) {
950 951 952 953 954 955 956 957 958 959
        $params['target_contact_id'] = array($targetContactId);
        // save activity
        $activity[] = $this->processActivity($params);
      }
    }
    else {
      // save activity
      $activity = $this->processActivity($params);
    }

unknown's avatar
unknown committed
960 961 962 963 964
    //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
965
      $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($params['entity_id'], $params['entity_table']);
unknown's avatar
unknown committed
966 967 968 969 970 971 972 973
      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']);
      }
974 975 976
      if (property_exists($scheduleReminderDetails, 'id')) {
        $params['schedule_reminder_id'] = $scheduleReminderDetails->id;
      }
unknown's avatar
unknown committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    }
    $params['dateColumns'] = array('activity_date_time');

    //Unset activity id
    unset($params['id']);
    $linkedEntities = array(
      array(
        'table'         => 'civicrm_activity_contact',
        'findCriteria'  => array(
          'activity_id' => $this->_activityId,
        ),
        'linkedColumns' => array('activity_id'),
        'isRecurringEntityRecord' => FALSE,
      )
    );
    CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_activity', $linkedEntities);

994 995 996 997 998 999
    return array('activity' => $activity);
  }

  /**
   * Process activity creation
   *
1000 1001
   * @param array $params
   *   Associated array of submitted values.
1002 1003
   *
   * @return $this|null|object
1004 1005
   */
  protected function processActivity(&$params) {
totten's avatar
totten committed
1006
    $activityAssigned = array();
1007
    $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
yashodha's avatar
yashodha committed
1008
    $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
totten's avatar
totten committed
1009 1010 1011 1012 1013 1014
    // 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
1015
        $assigneeContacts = CRM_Activity_BAO_ActivityContact::getNames($this->_activityId, $assigneeID);
totten's avatar
totten committed
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
        $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
1047
    if (!empty($params['is_multi_activity'])) {
1048 1049 1050 1051 1052
      $this->_activityIds[] = $activity->id;
    }
    else {
      $this->_activityId = $activity->id;
    }
totten's avatar
totten committed
1053 1054 1055

    // create follow up activity if needed
    $followupStatus = '';
1056
    $followupActivity = NULL;
1057
    if (!empty($params['followup_activity_type_id'])) {
1058
      $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
totten's avatar
totten committed
1059 1060 1061 1062 1063 1064
      $followupStatus = ts('A followup activity has been scheduled.');
    }

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

1065 1066 1067 1068 1069 1070 1071
    if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
        'activity_assignee_notification')) {
      $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
1072

1073 1074 1075 1076 1077 1078 1079 1080
      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
1081 1082
        }

1083 1084 1085 1086 1087 1088
        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
1089

1090 1091
          // 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
1092

1093
          $ics->cleanup();
totten's avatar
totten committed
1094

1095 1096 1097
          $mailStatus .= ts("A copy of the activity has also been sent to assignee contacts(s).");
        }
      }
1098

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
      // 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
1112

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

    // set status message
1123
    $subject = '';
1124
    if (!empty($params['subject'])) {
1125
      $subject = "'" . $params['subject'] . "'";
totten's avatar
totten committed
1126 1127
    }

1128
    CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2 %3',
1129
      array(
1130
        1 => $subject,
1131 1132 1133 1134
        2 => $followupStatus,
        3 => $mailStatus
      )
    ), ts('Saved'), 'success');
totten's avatar
totten committed
1135

1136
    return $activity;
totten's avatar
totten committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
  }

  /**
   * Shorthand for getting id by display name (makes code more readable)
   *
   */
  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)
   *
   */
  protected function _getDisplayNameById($id) {
    return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
      $id,
      'sort_name',
      'id'
    );
  }

  /**
colemanw's avatar
colemanw committed
1164
   * Let injecting activity type file do any processing
totten's avatar
totten committed
1165 1166
   * needed, before the activity is added/updated
   *
colemanw's avatar
colemanw committed
1167
   * @param array $params
totten's avatar
totten committed
1168
   */
1169
  public function beginPostProcess(&$params) {
totten's avatar
totten committed
1170
    if ($this->_activityTypeFile) {
lobo's avatar
lobo committed
1171 1172
      $className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
      $className::beginPostProcess($this, $params);
totten's avatar
totten committed
1173 1174 1175 1176
    }
  }

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