Esempio n. 1
0
 public function onChange(CRM_HRCaseUtils_Analyzer $analyzer, $objectRef)
 {
     if (isset($objectRef->activity_type_id)) {
         // Get activity type name & status of the activity being completed
         $activityTypeGroup = civicrm_api3('option_group', 'get', array('name' => 'activity_type'));
         $activityType = array('value' => $objectRef->activity_type_id, 'option_group_id' => $activityTypeGroup['id']);
         $activityTypeID = civicrm_api3('option_value', 'get', $activityType);
         $activityTypeID = $activityTypeID['values'][$activityTypeID['id']]['name'];
         $activityStatusGroup = civicrm_api3('option_group', 'get', array('name' => 'activity_status'));
         $activityStatus = array('value' => $objectRef->status_id, 'option_group_id' => $activityStatusGroup['id']);
         $activityStatusID = civicrm_api3('option_value', 'get', $activityStatus);
         $activityStatusID = $activityStatusID['values'][$activityStatusID['id']]['name'];
         // Schedule Interview Prospect activity
         if ($activityTypeID == 'Open Case' && $activityStatusID == 'Completed') {
             if ($analyzer->hasActivity($activityTypeID, $activityStatusID)) {
                 $nextActivity = 'Interview Prospect';
                 // Get the activity ID for Interview Prospect
                 $activityID = array('name' => $nextActivity, 'option_group_id' => $activityTypeGroup['id']);
                 $activityTypeID = civicrm_api3('option_value', 'get', $activityID);
                 $activityTypeID = $activityTypeID['values'][$activityTypeID['id']]['value'];
                 $params = self::buildParams($activityTypeID, $nextActivity, $objectRef);
             }
         } elseif ($activityTypeID == 'Interview Prospect' && $activityStatusID == 'Completed') {
             if ($analyzer->hasActivity($activityTypeID, $activityStatusID)) {
                 $nextActivity = 'Background Check';
                 // Get the activity ID for Background Check
                 $activityID = array('name' => $nextActivity, 'option_group_id' => $activityTypeGroup['id']);
                 $activityTypeID = civicrm_api3('option_value', 'get', $activityID);
                 $activityTypeID = $activityTypeID['values'][$activityTypeID['id']]['value'];
                 $params = self::buildParams($activityTypeID, $nextActivity, $objectRef);
             }
         } elseif ($activityTypeID == 'Background Check' && $activityStatusID == 'Completed') {
             return;
         }
         if (isset($params)) {
             $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($objectRef->original_id, $params);
             if ($followupActivity) {
                 $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $objectRef->case_id);
                 CRM_Case_BAO_Case::processCaseActivity($caseParams);
                 $analyzer->flush();
             }
         }
     }
 }
Esempio n. 2
0
 /**
  * Process the user submitted custom data values.
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $transaction = new CRM_Core_Transaction();
     CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_case', $this->_entityID, 'Case');
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/view/case', "reset=1&id={$this->_entityID}&cid={$this->_contactID}&action=view"));
     $session = CRM_Core_Session::singleton();
     $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Change Custom Data', 'name');
     $activityParams = array('activity_type_id' => $activityTypeID, 'source_contact_id' => $session->get('userID'), 'is_auto' => TRUE, 'subject' => $this->_customTitle . " : change data", 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'target_contact_id' => $this->_contactID, 'details' => json_encode($this->_defaults), 'activity_date_time' => date('YmdHis'));
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $this->_entityID);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     $transaction->commit();
 }
Esempio n. 3
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 static function postProcess(&$form)
 {
     if (count($form->_contactIds) > self::MAX_EMAILS_KILL_SWITCH) {
         CRM_Core_Error::fatal(ts('Please do not use this task to send a lot of emails (greater than %1). We recommend using CiviMail instead.', array(1 => self::MAX_EMAILS_KILL_SWITCH)));
     }
     // check and ensure that
     $formValues = $form->controller->exportValues($form->getName());
     $fromEmail = $formValues['fromEmailAddress'];
     $from = CRM_Utils_Array::value($fromEmail, $form->_fromEmails);
     $cc = CRM_Utils_Array::value('cc_id', $formValues);
     $bcc = CRM_Utils_Array::value('bcc_id', $formValues);
     $subject = $formValues['subject'];
     // process message template
     require_once 'CRM/Core/BAO/MessageTemplates.php';
     if (CRM_Utils_Array::value('saveTemplate', $formValues) || CRM_Utils_Array::value('updateTemplate', $formValues)) {
         $messageTemplate = array('msg_text' => $formValues['text_message'], 'msg_html' => $formValues['html_message'], 'msg_subject' => $formValues['subject'], 'is_active' => true);
         if ($formValues['saveTemplate']) {
             $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
             CRM_Core_BAO_MessageTemplates::add($messageTemplate);
         }
         if ($formValues['template'] && $formValues['updateTemplate']) {
             $messageTemplate['id'] = $formValues['template'];
             unset($messageTemplate['msg_title']);
             CRM_Core_BAO_MessageTemplates::add($messageTemplate);
         }
     }
     $attachments = array();
     CRM_Core_BAO_File::formatAttachment($formValues, $attachments, null, null);
     // format contact details array to handle multiple emails from same contact
     $formattedContactDetails = array();
     $tempEmails = array();
     foreach ($form->_contactIds as $key => $contactId) {
         $email = $form->_toContactEmails[$key];
         // prevent duplicate emails if same email address is selected CRM-4067
         // we should allow same emails for different contacts
         $emailKey = "{$contactId}::{$email}";
         if (!in_array($emailKey, $tempEmails)) {
             $tempEmails[] = $emailKey;
             $details = $form->_contactDetails[$contactId];
             $details['email'] = $email;
             unset($details['email_id']);
             $formattedContactDetails[] = $details;
         }
     }
     // send the mail
     require_once 'CRM/Activity/BAO/Activity.php';
     list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail($formattedContactDetails, $subject, $formValues['text_message'], $formValues['html_message'], null, null, $from, $attachments, $cc, $bcc, array_keys($form->_contactDetails));
     if ($sent) {
         $status = array('', ts('Your message has been sent.'));
     }
     //Display the name and number of contacts for those email is not sent.
     $emailsNotSent = array_diff_assoc($form->_allContactDetails, $form->_contactDetails);
     if (!empty($emailsNotSent)) {
         $statusOnHold = '';
         $statusDisplay = ts('Email not sent to contact(s) (no email address on file or communication preferences specify DO NOT EMAIL or Contact is deceased or Primary email address is On Hold): %1', array(1 => count($emailsNotSent))) . '<br />' . ts('Details') . ': ';
         foreach ($emailsNotSent as $contactId => $values) {
             $displayName = $values['display_name'];
             $email = $values['email'];
             $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contactId}");
             $statusDisplay .= "<a href='{$contactViewUrl}'>{$displayName}</a>, ";
             // build separate status for on hold messages
             if ($values['on_hold']) {
                 $statusOnHold .= ts('Email was not sent to %1 because primary email address (%2) is On Hold.', array(1 => "<a href='{$contactViewUrl}'>{$displayName}</a>", 2 => "<strong>{$email}</strong>")) . '<br />';
             }
         }
         $status[] = $statusDisplay;
     }
     if ($form->_caseId) {
         // if case-id is found in the url, create case activity record
         $caseParams = array('activity_id' => $activityId, 'case_id' => $form->_caseId);
         require_once 'CRM/Case/BAO/Case.php';
         CRM_Case_BAO_Case::processCaseActivity($caseParams);
     }
     if (strlen($statusOnHold)) {
         $status[] = $statusOnHold;
     }
     CRM_Core_Session::setStatus($status);
 }
Esempio n. 4
0
 /**
  * @param $activityTypeXML
  * @param array $params
  *
  * @return bool
  * @throws CRM_Core_Exception
  * @throws Exception
  */
 public function createActivity($activityTypeXML, &$params)
 {
     $activityTypeName = (string) $activityTypeXML->name;
     $activityTypes =& $this->allActivityTypes(TRUE, TRUE);
     $activityTypeInfo = CRM_Utils_Array::value($activityTypeName, $activityTypes);
     if (!$activityTypeInfo) {
         $docLink = CRM_Utils_System::docURL2("user/case-management/setup");
         CRM_Core_Error::fatal(ts('Activity type %1, found in case configuration file, is not present in the database %2', array(1 => $activityTypeName, 2 => $docLink)));
         return FALSE;
     }
     $activityTypeID = $activityTypeInfo['id'];
     if (isset($activityTypeXML->status)) {
         $statusName = (string) $activityTypeXML->status;
     } else {
         $statusName = 'Scheduled';
     }
     if ($this->_isMultiClient) {
         $client = $params['clientID'];
     } else {
         $client = array(1 => $params['clientID']);
     }
     //set order
     $orderVal = '';
     if (isset($activityTypeXML->order)) {
         $orderVal = (string) $activityTypeXML->order;
     }
     if ($activityTypeName == 'Open Case') {
         $activityParams = array('activity_type_id' => $activityTypeID, 'source_contact_id' => $params['creatorID'], 'is_auto' => FALSE, 'is_current_revision' => 1, 'subject' => CRM_Utils_Array::value('subject', $params) ? $params['subject'] : $activityTypeName, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', $statusName, 'name'), 'target_contact_id' => $client, 'medium_id' => CRM_Utils_Array::value('medium_id', $params), 'location' => CRM_Utils_Array::value('location', $params), 'details' => CRM_Utils_Array::value('details', $params), 'duration' => CRM_Utils_Array::value('duration', $params), 'weight' => $orderVal);
     } else {
         $activityParams = array('activity_type_id' => $activityTypeID, 'source_contact_id' => $params['creatorID'], 'is_auto' => TRUE, 'is_current_revision' => 1, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', $statusName, 'name'), 'target_contact_id' => $client, 'weight' => $orderVal);
     }
     //parsing date to default preference format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time']);
     if ($activityTypeName == 'Open Case') {
         // we don't set activity_date_time for auto generated
         // activities, but we want it to be set for open case.
         $activityParams['activity_date_time'] = $params['activity_date_time'];
         if (array_key_exists('custom', $params) && is_array($params['custom'])) {
             $activityParams['custom'] = $params['custom'];
         }
         // Add parameters for attachments
         $numAttachments = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'max_attachments');
         for ($i = 1; $i <= $numAttachments; $i++) {
             $attachName = "attachFile_{$i}";
             if (isset($params[$attachName]) && !empty($params[$attachName])) {
                 $activityParams[$attachName] = $params[$attachName];
             }
         }
     } else {
         $activityDate = NULL;
         //get date of reference activity if set.
         if ($referenceActivityName = (string) $activityTypeXML->reference_activity) {
             //we skip open case as reference activity.CRM-4374.
             if (!empty($params['resetTimeline']) && $referenceActivityName == 'Open Case') {
                 $activityDate = $params['activity_date_time'];
             } else {
                 $referenceActivityInfo = CRM_Utils_Array::value($referenceActivityName, $activityTypes);
                 if ($referenceActivityInfo['id']) {
                     $caseActivityParams = array('activity_type_id' => $referenceActivityInfo['id']);
                     //if reference_select is set take according activity.
                     if ($referenceSelect = (string) $activityTypeXML->reference_select) {
                         $caseActivityParams[$referenceSelect] = 1;
                     }
                     $referenceActivity = CRM_Case_BAO_Case::getCaseActivityDates($params['caseID'], $caseActivityParams, TRUE);
                     if (is_array($referenceActivity)) {
                         foreach ($referenceActivity as $aId => $details) {
                             $activityDate = CRM_Utils_Array::value('activity_date', $details);
                             break;
                         }
                     }
                 }
             }
         }
         if (!$activityDate) {
             $activityDate = $params['activity_date_time'];
         }
         list($activity_date, $activity_time) = CRM_Utils_Date::setDateDefaults($activityDate);
         $activityDateTime = CRM_Utils_Date::processDate($activity_date, $activity_time);
         //add reference offset to date.
         if ((int) $activityTypeXML->reference_offset) {
             $activityDateTime = CRM_Utils_Date::intervalAdd('day', (int) $activityTypeXML->reference_offset, $activityDateTime);
         }
         $activityParams['activity_date_time'] = CRM_Utils_Date::format($activityDateTime);
     }
     // if same activity is already there, skip and dont touch
     $params['activityTypeID'] = $activityTypeID;
     $params['activityTypeName'] = $activityTypeName;
     if ($this->isActivityPresent($params)) {
         return TRUE;
     }
     $activityParams['case_id'] = $params['caseID'];
     if (!empty($activityParams['is_auto'])) {
         $activityParams['skipRecentView'] = TRUE;
     }
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     if (!$activity) {
         CRM_Core_Error::fatal();
         return FALSE;
     }
     // create case activity record
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $params['caseID']);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     return TRUE;
 }
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function endPostProcess(&$form, &$params, $activity)
 {
     if (CRM_Utils_Array::value('start_date', $params)) {
         $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
     }
     $caseType = $form->_caseType;
     if (!$caseType && $form->_caseId) {
         $query = "\nSELECT  cov_type.label as case_type FROM civicrm_case \nLEFT JOIN  civicrm_option_group cog_type ON cog_type.name = 'case_type'\nLEFT JOIN civicrm_option_value cov_type ON \n( civicrm_case.case_type_id = cov_type.value AND cog_type.id = cov_type.option_group_id ) \nWHERE civicrm_case.id=  %1";
         $queryParams = array(1 => array($form->_caseId, 'Integer'));
         $caseType = CRM_Core_DAO::singleValueQuery($query, $queryParams);
     }
     if (!$form->_currentlyViewedContactId || !$form->_currentUserId || !$form->_caseId || !$caseType) {
         CRM_Core_Error::fatal('Required parameter missing for ChangeCaseType - end post processing');
     }
     $config =& CRM_Core_Config::singleton();
     // 1. save activity subject with new start date
     $currentStartDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $form->_caseId, 'start_date'), $config->dateformatFull);
     $newStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Date::mysqlToIso($params['start_date']), $config->dateformatFull);
     $subject = 'Change Case Start Date from ' . $currentStartDate . ' to ' . $newStartDate;
     $activity->subject = $subject;
     $activity->save();
     // 2. initiate xml processor
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $xmlProcessorParams = array('clientID' => $form->_currentlyViewedContactId, 'creatorID' => $form->_currentUserId, 'standardTimeline' => 0, 'activity_date_time' => $params['start_date'], 'caseID' => $form->_caseId, 'caseType' => $caseType, 'activityTypeName' => 'Change Case Start Date', 'activitySetName' => 'standard_timeline', 'resetTimeline' => 1);
     $xmlProcessor->run($caseType, $xmlProcessorParams);
     // 2.5 Update open case activity date
     // Multiple steps since revisioned
     if ($form->openCaseActivityId) {
         require_once 'CRM/Activity/BAO/Activity.php';
         $abao = new CRM_Activity_BAO_Activity();
         $oldParams = array('id' => $form->openCaseActivityId);
         $oldActivityDefaults = array();
         $oldActivity = $abao->retrieve($oldParams, $oldActivityDefaults);
         // save the old values
         require_once 'api/v2/utils.php';
         $openCaseParams = array();
         _civicrm_object_to_array($oldActivity, $openCaseParams);
         // update existing revision
         $oldParams = array('id' => $form->openCaseActivityId, 'is_current_revision' => 0);
         require_once 'CRM/Activity/DAO/Activity.php';
         $oldActivity = new CRM_Activity_DAO_Activity();
         $oldActivity->copyValues($oldParams);
         $oldActivity->save();
         // change some params for the new one
         unset($openCaseParams['id']);
         $openCaseParams['activity_date_time'] = $params['start_date'];
         $openCaseParams['target_contact_id'] = $oldActivityDefaults['target_contact'];
         $openCaseParams['assignee_contact_id'] = $oldActivityDefaults['assignee_contact'];
         $session =& CRM_Core_Session::singleton();
         $openCaseParams['source_contact_id'] = $session->get('userID');
         // original_id always refers to the first activity, so only update if null (i.e. this is the second revision)
         $openCaseParams['original_id'] = $openCaseParams['original_id'] ? $openCaseParams['original_id'] : $form->openCaseActivityId;
         $newActivity = CRM_Activity_BAO_Activity::create($openCaseParams);
         if (is_a($newActivity, 'CRM_Core_Error')) {
             CRM_Core_Error::fatal('Unable to update Open Case activity');
         } else {
             // Create linkage to case
             $caseActivityParams = array('activity_id' => $newActivity->id, 'case_id' => $form->_caseId);
             require_once "CRM/Case/BAO/Case.php";
             CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
         }
     }
     // 3.status msg
     $params['statusMsg'] = ts('Case Start Date changed successfully.');
 }
Esempio n. 6
0
 /**
  * Function to create activities when Case or Other roles assigned/modified/deleted.
  *
  * @param $caseId
  * @param int $relationshipId relationship id
  * @param int $relContactId case role assignee contactId.
  *
  * @param null $contactId
  *
  * @internal param int $caseID case id
  * @return void on success creates activity and case activity
  *
  * @static
  */
 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL)
 {
     if (!$caseId || !$relationshipId || empty($relationshipId)) {
         return;
     }
     $queryParam = array();
     if (is_array($relationshipId)) {
         $relationshipId = implode(',', $relationshipId);
         $relationshipClause = " civicrm_relationship.id IN ({$relationshipId})";
     } else {
         $relationshipClause = " civicrm_relationship.id = %1";
         $queryParam[1] = array($relationshipId, 'Positive');
     }
     $query = "\n   SELECT  cc.display_name as clientName,\n           cca.display_name as  assigneeContactName,\n           civicrm_relationship.case_id as caseId,\n           civicrm_relationship_type.label_a_b as relation_a_b,\n           civicrm_relationship_type.label_b_a as relation_b_a,\n           civicrm_relationship.contact_id_b as rel_contact_id,\n           civicrm_relationship.contact_id_a as assign_contact_id\n     FROM  civicrm_relationship_type,  civicrm_relationship\n LEFT JOIN  civicrm_contact cc  ON cc.id  = civicrm_relationship.contact_id_b\n LEFT JOIN  civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a\n    WHERE  civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
     $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
     while ($dao->fetch()) {
         //to get valid assignee contact(s).
         if (isset($dao->caseId) || $dao->rel_contact_id != $contactId) {
             $caseRelationship = $dao->relation_a_b;
             $assigneContactName = $dao->clientName;
             $assigneContactIds[$dao->rel_contact_id] = $dao->rel_contact_id;
         } else {
             $caseRelationship = $dao->relation_b_a;
             $assigneContactName = $dao->assigneeContactName;
             $assigneContactIds[$dao->assign_contact_id] = $dao->assign_contact_id;
         }
     }
     $session = CRM_Core_Session::singleton();
     $activityParams = array('source_contact_id' => $session->get('userID'), 'subject' => $caseRelationship . ' : ' . $assigneContactName, 'activity_date_time' => date('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'));
     //if $relContactId is passed, role is added or modified.
     if (!empty($relContactId)) {
         $activityParams['assignee_contact_id'] = $assigneContactIds;
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Assign Case Role', 'name');
     } else {
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Remove Case Role', 'name');
     }
     $activityParams['activity_type_id'] = $activityTypeID;
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     //create case_activity record.
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $caseId);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
 }
Esempio n. 7
0
 /**
  * Process the activities.
  *
  * @param array $params
  *   Associated array of the submitted values.
  *
  * @throws CRM_Core_Exception
  *
  * @return CRM_Activity_BAO_Activity|null|object
  */
 public static function create(&$params)
 {
     // check required params
     if (!self::dataExists($params)) {
         throw new CRM_Core_Exception('Not enough data to create activity object');
     }
     $activity = new CRM_Activity_DAO_Activity();
     if (isset($params['id']) && empty($params['id'])) {
         unset($params['id']);
     }
     if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
         if (isset($params['activity_date_time']) && strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)) {
             $params['status_id'] = 2;
         } else {
             $params['status_id'] = 1;
         }
     }
     // Set priority to Normal for Auto-populated activities (for Cases)
     if (CRM_Utils_Array::value('priority_id', $params) === NULL && !CRM_Utils_Array::value('id', $params)) {
         $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
         $params['priority_id'] = array_search('Normal', $priority);
     }
     if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
         $params['target_contact_id'] = array_unique($params['target_contact_id']);
     }
     if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
     }
     // CRM-9137
     if (!empty($params['id'])) {
         CRM_Utils_Hook::pre('edit', 'Activity', $activity->id, $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Activity', NULL, $params);
     }
     $activity->copyValues($params);
     if (isset($params['case_id'])) {
         // CRM-8708, preserve case ID even though it's not part of the SQL model
         $activity->case_id = $params['case_id'];
     } elseif (is_numeric($activity->id)) {
         // CRM-8708, preserve case ID even though it's not part of the SQL model
         $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
     }
     // start transaction
     $transaction = new CRM_Core_Transaction();
     $result = $activity->save();
     if (is_a($result, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $result;
     }
     $activityId = $activity->id;
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
     if (isset($params['source_contact_id'])) {
         $acParams = array('activity_id' => $activityId, 'contact_id' => $params['source_contact_id'], 'record_type_id' => $sourceID);
         self::deleteActivityContact($activityId, $sourceID);
         CRM_Activity_BAO_ActivityContact::create($acParams);
     }
     // check and attach and files as needed
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
     // attempt to save activity assignment
     $resultAssignment = NULL;
     if (!empty($params['assignee_contact_id'])) {
         $assignmentParams = array('activity_id' => $activityId);
         if (is_array($params['assignee_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
                 // first delete existing assignments if any
                 self::deleteActivityContact($activityId, $assigneeID);
             }
             $values = array();
             foreach ($params['assignee_contact_id'] as $acID) {
                 if ($acID) {
                     $values[] = "( {$activityId}, {$acID}, {$assigneeID} )";
                 }
             }
             while (!empty($values)) {
                 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
                 $str = implode(',', $input);
                 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};";
                 CRM_Core_DAO::executeQuery($sql);
             }
         } else {
             $assignmentParams['contact_id'] = $params['assignee_contact_id'];
             $assignmentParams['record_type_id'] = $assigneeID;
             if (!empty($params['id'])) {
                 $assignment = new CRM_Activity_BAO_ActivityContact();
                 $assignment->activity_id = $activityId;
                 $assignment->record_type_id = $assigneeID;
                 $assignment->find(TRUE);
                 if ($assignment->contact_id != $params['assignee_contact_id']) {
                     $assignmentParams['id'] = $assignment->id;
                     $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
                 }
             } else {
                 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
             self::deleteActivityContact($activityId, $assigneeID);
         }
     }
     if (is_a($resultAssignment, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $resultAssignment;
     }
     // attempt to save activity targets
     $resultTarget = NULL;
     if (!empty($params['target_contact_id'])) {
         $targetParams = array('activity_id' => $activityId);
         $resultTarget = array();
         if (is_array($params['target_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
                 // first delete existing targets if any
                 self::deleteActivityContact($activityId, $targetID);
             }
             $values = array();
             foreach ($params['target_contact_id'] as $tid) {
                 if ($tid) {
                     $values[] = "( {$activityId}, {$tid},  {$targetID} )";
                 }
             }
             while (!empty($values)) {
                 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
                 $str = implode(',', $input);
                 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};";
                 CRM_Core_DAO::executeQuery($sql);
             }
         } else {
             $targetParams['contact_id'] = $params['target_contact_id'];
             $targetParams['record_type_id'] = $targetID;
             if (!empty($params['id'])) {
                 $target = new CRM_Activity_BAO_ActivityContact();
                 $target->activity_id = $activityId;
                 $target->record_type_id = $targetID;
                 $target->find(TRUE);
                 if ($target->contact_id != $params['target_contact_id']) {
                     $targetParams['id'] = $target->id;
                     $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
                 }
             } else {
                 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
             self::deleteActivityContact($activityId, $targetID);
         }
     }
     // write to changelog before transaction is committed/rolled
     // back (and prepare status to display)
     if (!empty($params['id'])) {
         $logMsg = "Activity (id: {$result->id} ) updated with ";
     } else {
         $logMsg = "Activity created for ";
     }
     $msgs = array();
     if (isset($params['source_contact_id'])) {
         $msgs[] = "source={$params['source_contact_id']}";
     }
     if (!empty($params['target_contact_id'])) {
         if (is_array($params['target_contact_id']) && !CRM_Utils_array::crmIsEmptyArray($params['target_contact_id'])) {
             $msgs[] = "target=" . implode(',', $params['target_contact_id']);
             // take only first target
             // will be used for recently viewed display
             $t = array_slice($params['target_contact_id'], 0, 1);
             $recentContactId = $t[0];
         } elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
             $msgs[] = "target={$params['target_contact_id']}";
             // will be used for recently viewed display
             $recentContactId = $params['target_contact_id'];
         }
     } else {
         // at worst, take source for recently viewed display
         $recentContactId = CRM_Utils_Array::value('source_contact_id', $params);
     }
     if (isset($params['assignee_contact_id'])) {
         if (is_array($params['assignee_contact_id'])) {
             $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
         } else {
             $msgs[] = "assignee={$params['assignee_contact_id']}";
         }
     }
     $logMsg .= implode(', ', $msgs);
     self::logActivityAction($result, $logMsg);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
     }
     $transaction->commit();
     if (empty($params['skipRecentView'])) {
         $recentOther = array();
         if (!empty($params['case_id'])) {
             $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
             $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home");
         } else {
             $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home";
             if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
                 $url = CRM_Utils_System::url('civicrm/activity', $q);
                 if ($activity->activity_type_id == CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name')) {
                     $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/pdf/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home");
                 } else {
                     $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
                 if (CRM_Core_Permission::check("delete activities")) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/activity/view', $q);
                 if (CRM_Core_Permission::check('delete activities')) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
             }
         }
         if (!isset($activity->parent_id)) {
             $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
             // add the recently created Activity
             $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
             $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
             $title = "";
             if (isset($activitySubject)) {
                 $title = $activitySubject . ' - ';
             }
             $title = $title . $recentContactDisplay;
             if (!empty($activityTypes[$activity->activity_type_id])) {
                 $title .= ' (' . $activityTypes[$activity->activity_type_id] . ')';
             }
             CRM_Utils_Recent::add($title, $url, $activity->id, 'Activity', $recentContactId, $recentContactDisplay, $recentOther);
         }
     }
     // reset the group contact cache since smart groups might be affected due to this
     CRM_Contact_BAO_GroupContactCache::remove();
     if (!empty($params['id'])) {
         CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
     } else {
         CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
     }
     // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
     $matches = array();
     if (preg_match('/\\[case #([0-9a-h]{7})\\]/', CRM_Utils_Array::value('subject', $params), $matches)) {
         $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
         $hash = $matches[1];
         $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('{$key}', id)), 1, 7) = '{$hash}'";
         $caseParams = array('activity_id' => $activity->id, 'case_id' => CRM_Core_DAO::singleValueQuery($query));
         if ($caseParams['case_id']) {
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
         } else {
             self::logActivityAction($activity, "unknown case hash encountered: {$hash}");
         }
     }
     return $result;
 }
Esempio n. 8
0
 /**
  * Process the form submission.
  *
  *
  * @param array $params
  *
  * @return void
  */
 public function postProcess($params = NULL)
 {
     $transaction = new CRM_Core_Transaction();
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = NULL;
         //block deleting activities which affects
         //case attributes.CRM-4543
         $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
         $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
         if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
             $params = array('id' => $this->_activityId);
             $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, TRUE);
             if ($activityDelete) {
                 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
             }
         } else {
             $statusMsg = ts("Selected Activity cannot be deleted.");
         }
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = NULL;
         $params = array('id' => $this->_activityId);
         $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
         if ($activityRestore) {
             $statusMsg = ts('The selected activity has been restored.<br />');
         }
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     //set parent id if its edit mode
     if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
         $params['parent_id'] = $parentId;
     }
     // store the dates with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     $params['activity_type_id'] = $this->_activityTypeId;
     // format with contact (target contact) values
     if (isset($params['target_contact_id'])) {
         $params['target_contact_id'] = explode(',', $params['target_contact_id']);
     } else {
         $params['target_contact_id'] = array();
     }
     // format activity custom data
     if (!empty($params['hidden_custom'])) {
         if ($this->_activityId) {
             // unset custom fields-id from params since we want custom
             // fields to be saved for new activity.
             foreach ($params as $key => $value) {
                 $match = array();
                 if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) {
                     $params[$match[1] . '-1'] = $params[$key];
                     // for autocomplete transfer hidden value instead of label
                     if ($params[$key] && isset($params[$key . '_id'])) {
                         $params[$match[1] . '-1_id'] = $params[$key . '_id'];
                         unset($params[$key . '_id']);
                     }
                     unset($params[$key]);
                 }
             }
         }
         // build custom data getFields array
         $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');
     }
     // assigning formatted value
     if (!empty($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = array();
     }
     if (isset($this->_activityId)) {
         // activity which hasn't been modified by a user yet
         if ($this->_defaults['is_auto'] == 1) {
             $params['is_auto'] = 0;
         }
         // always create a revision of an case activity. CRM-4533
         $newActParams = $params;
         // add target contact values in update mode
         if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
             $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
         }
     }
     if (!isset($newActParams)) {
         // add more attachments if needed for old activity
         CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($params);
         foreach ($this->_caseId as $key => $val) {
             $params['case_id'] = $val;
             // activity create/update
             $activity = CRM_Activity_BAO_Activity::create($params);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($params, $activity);
         }
     } else {
         // since the params we need to set are very few, and we don't want rest of the
         // work done by bao create method , lets use dao object to make the changes
         $params = array('id' => $this->_activityId);
         $params['is_current_revision'] = 0;
         $activity = new CRM_Activity_DAO_Activity();
         $activity->copyValues($params);
         $activity->save();
     }
     // create a new version of activity if activity was found to
     // have been modified/created by user
     if (isset($newActParams)) {
         // set proper original_id
         if (!empty($this->_defaults['original_id'])) {
             $newActParams['original_id'] = $this->_defaults['original_id'];
         } else {
             $newActParams['original_id'] = $activity->id;
         }
         //is_current_revision will be set to 1 by default.
         // add attachments if any
         CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($newActParams);
         foreach ($this->_caseId as $key => $val) {
             $newActParams['case_id'] = $val;
             $activity = CRM_Activity_BAO_Activity::create($newActParams);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($newActParams, $activity);
         }
         // copy files attached to old activity if any, to new one,
         // as long as users have not selected the 'delete attachment' option.
         if (empty($newActParams['is_delete_attachment'])) {
             CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id);
         }
         // copy back params to original var
         $params = $newActParams;
     }
     foreach ($vvalue as $vkey => $vval) {
         if ($vval['actId']) {
             // 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', $vval['actId']);
             //save free tags
             if (isset($params['taglist']) && !empty($params['taglist'])) {
                 CRM_Core_Form_Tag::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
             }
         }
         // update existing case record if needed
         $caseParams = $params;
         $caseParams['id'] = $vval['case_id'];
         if (!empty($caseParams['case_status_id'])) {
             $caseParams['status_id'] = $caseParams['case_status_id'];
         }
         // unset params intended for activities only
         unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']);
         $case = CRM_Case_BAO_Case::create($caseParams);
         // create case activity record
         $caseParams = array('activity_id' => $vval['actId'], 'case_id' => $vval['case_id']);
         CRM_Case_BAO_Case::processCaseActivity($caseParams);
     }
     // Insert civicrm_log record for the activity (e.g. store the
     // created / edited by contact id and date for the activity)
     // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
     // send copy to selected contacts.
     $mailStatus = '';
     $mailToContacts = array();
     //CRM-5695
     //check for notification settings for assignee contacts
     $selectedContacts = array('contact_check');
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
         $selectedContacts[] = 'assignee_contact_id';
     }
     foreach ($vvalue as $vkey => $vval) {
         foreach ($selectedContacts as $dnt => $val) {
             if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) {
                 if ($val == 'contact_check') {
                     $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
                 } else {
                     $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
                     $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
                 }
                 //build an associative array with unique email addresses.
                 foreach ($params[$val] as $key => $value) {
                     if ($val == 'contact_check') {
                         $id = $key;
                     } else {
                         $id = $value;
                     }
                     if (isset($id) && array_key_exists($id, $this->_relatedContacts) && isset($this->_relatedContacts[$id]['email'])) {
                         //if email already exists in array then append with ', ' another role only otherwise add it to array.
                         if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
                             $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
                             $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
                         } else {
                             $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
                         }
                     }
                 }
             }
         }
         $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId);
         $result = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts, $extraParams);
         if (empty($result)) {
             $mailStatus = '';
         }
         // create follow up activity if needed
         $followupStatus = '';
         if (!empty($params['followup_activity_type_id'])) {
             $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($vval['actId'], $params);
             if ($followupActivity) {
                 $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $vval['case_id']);
                 CRM_Case_BAO_Case::processCaseActivity($caseParams);
                 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
             }
         }
         $title = ts("%1 Saved", array(1 => $this->_activityTypeName));
         CRM_Core_Session::setStatus($followupStatus . $mailStatus, $title, 'success');
     }
 }
/**
 * Creates or updates an Activity. See the example for usage
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs for the activity.
 * {@getfields activity_create}
 *
 * @return array Array containing 'is_error' to denote success or failure and details of the created activity
 *
 * @example ActivityCreate.php Standard create example
 * @example Activity/ContactRefCustomField.php Create example including setting a contact reference custom field
 * {@example ActivityCreate.php 0}
 *
 */
function civicrm_api3_activity_create($params)
{
    if (!CRM_Utils_Array::value('id', $params)) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('activity_name', 'activity_type_id', 'activity_label'));
    }
    $errors = array();
    // check for various error and required conditions
    $errors = _civicrm_api3_activity_check_params($params);
    if (!empty($errors)) {
        return $errors;
    }
    // processing for custom data
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Activity');
    if (!empty($values['custom'])) {
        $params['custom'] = $values['custom'];
    }
    $params['skipRecentView'] = TRUE;
    // If this is a case activity, see if there is an existing activity
    // and set it as an old revision. Also retrieve details we'll need.
    $case_id = '';
    $createRevision = FALSE;
    $oldActivityValues = array();
    if (CRM_Utils_Array::value('case_id', $params)) {
        $case_id = $params['case_id'];
        if (CRM_Utils_Array::value('id', $params)) {
            $oldActivityParams = array('id' => $params['id']);
            if (!$oldActivityValues) {
                CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
            }
            if (empty($oldActivityValues)) {
                return civicrm_api3_create_error(ts("Unable to locate existing activity."), NULL, CRM_Core_DAO::$_nullObject);
            } else {
                require_once 'CRM/Activity/DAO/Activity.php';
                $activityDAO = new CRM_Activity_DAO_Activity();
                $activityDAO->id = $params['id'];
                $activityDAO->is_current_revision = 0;
                if (!$activityDAO->save()) {
                    return civicrm_api3_create_error(ts("Unable to revision existing case activity."), NULL, $activityDAO);
                }
                $createRevision = TRUE;
            }
        }
    }
    $deleteActivityAssignment = FALSE;
    if (isset($params['assignee_contact_id'])) {
        $deleteActivityAssignment = TRUE;
    }
    $deleteActivityTarget = FALSE;
    if (isset($params['target_contact_id'])) {
        $deleteActivityTarget = TRUE;
    }
    $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
    $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
    if ($case_id && $createRevision) {
        // This is very similar to the copy-to-case action.
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
            $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
        }
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
            $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
        }
        $oldActivityValues['mode'] = 'copy';
        $oldActivityValues['caseID'] = $case_id;
        $oldActivityValues['activityID'] = $oldActivityValues['id'];
        $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
        require_once 'CRM/Activity/Page/AJAX.php';
        $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
        if (empty($copyToCase['error_msg'])) {
            // now fix some things that are different from copy-to-case
            // then fall through to the create below to update with the passed in params
            $params['id'] = $copyToCase['newId'];
            $params['is_auto'] = 0;
            $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
        } else {
            return civicrm_api3_create_error(ts("Unable to create new revision of case activity."), NULL, CRM_Core_DAO::$_nullObject);
        }
    }
    // create activity
    $activityBAO = CRM_Activity_BAO_Activity::create($params);
    if (isset($activityBAO->id)) {
        if ($case_id && !$createRevision) {
            // If this is a brand new case activity we need to add this
            $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
            require_once 'CRM/Case/BAO/Case.php';
            CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
        }
        _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
        return civicrm_api3_create_success($activityArray, $params, 'activity', 'get', $activityBAO);
    }
}
Esempio n. 10
0
 function processCaseTags()
 {
     require_once 'CRM/Core/BAO/EntityTag.php';
     $caseId = CRM_Utils_Type::escape($_POST['case_id'], 'Integer');
     $tags = CRM_Utils_Type::escape($_POST['tag'], 'String');
     if (empty($caseId)) {
         echo 'false';
         CRM_Utils_System::civiExit();
     }
     $tagIds = array();
     if ($tags) {
         $tagIds = explode(',', $tags);
     }
     $params = array('entity_id' => $caseId, 'entity_table' => 'civicrm_case');
     CRM_Core_BAO_EntityTag::del($params);
     foreach ($tagIds as $tagid) {
         $params['tag_id'] = $tagid;
         CRM_Core_BAO_EntityTag::add($params);
     }
     $session =& CRM_Core_Session::singleton();
     require_once "CRM/Activity/BAO/Activity.php";
     require_once "CRM/Core/OptionGroup.php";
     $activityParams = array();
     $activityParams['source_contact_id'] = $session->get('userID');
     $activityParams['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Change Case Tags', 'name');
     $activityParams['activity_date_time'] = date('YmdHis');
     $activityParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activityParams['case_id'] = $caseId;
     $activityParams['is_auto'] = 0;
     $activityParams['subject'] = 'Change Case Tags';
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     require_once "CRM/Case/BAO/Case.php";
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $caseId);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     echo 'true';
     CRM_Utils_System::civiExit();
 }
Esempio n. 11
0
 function addClient()
 {
     $caseId = CRM_Utils_Type::escape($_POST['caseID'], 'Integer');
     $contactId = CRM_Utils_Type::escape($_POST['contactID'], 'Integer');
     $params = array('case_id' => $caseId, 'contact_id' => $contactId);
     $result = CRM_Case_BAO_Case::addCaseToContact($params);
     $session = CRM_Core_Session::singleton();
     $activityParams = array();
     $activityParams['source_contact_id'] = $session->get('userID');
     $activityParams['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Add Client To Case', 'name');
     $activityParams['activity_date_time'] = date('YmdHis');
     $activityParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activityParams['case_id'] = $caseId;
     $activityParams['is_auto'] = 0;
     $activityParams['subject'] = 'Client Added To Case';
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $caseId);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     echo json_encode(TRUE);
     CRM_Utils_System::civiExit();
 }
Esempio n. 12
0
/**
* Create new activity for a case
*
* @param array( //REQUIRED:
*                         'case_id'                     => int
*                         'activity_type_id'            => int
*                         'source_contact_id'           => int
*                         'status_id'                   => int
*                         'medium_id'                   => int // see civicrm option values for possibilities
*
*               //OPTIONAL
*                         'subject'                     => str
*                         'activity_date_time'          => date string // defaults to: date('YmdHis')
*                         'details                      => str
*
* @return activity id
*
* NOTE: For other case activity functions (update, delete, etc) use the Activity API
*
*/
function civicrm_case_activity_create(&$params)
{
    _civicrm_initialize();
    //check parameters
    $errors = _civicrm_case_check_params($params, 'activity');
    _civicrm_case_format_params($params, 'activity');
    if ($errors) {
        return $errors;
    }
    require_once 'CRM/Activity/BAO/Activity.php';
    $activity = CRM_Activity_BAO_Activity::create($params);
    $caseParams = array('activity_id' => $activity->id, 'case_id' => $params['case_id']);
    CRM_Case_BAO_Case::processCaseActivity($caseParams);
    return civicrm_create_success($activity->id);
}
Esempio n. 13
0
 function createActivity($activityTypeXML, &$params)
 {
     $activityTypeName = (string) $activityTypeXML->name;
     $activityTypes =& $this->allActivityTypes();
     $activityTypeInfo = CRM_Utils_Array::value($activityTypeName, $activityTypes);
     if (!$activityTypeInfo) {
         require_once 'CRM/Utils/System.php';
         $docLink = CRM_Utils_System::docURL2("CiviCase Configuration");
         CRM_Core_Error::fatal(ts('Activity type %1, found in case configuration file, is not present in the database %2', array(1 => $activityTypeName, 2 => $docLink)));
         return false;
     }
     $activityTypeID = $activityTypeInfo['id'];
     if (isset($activityTypeXML->status)) {
         $statusName = (string) $activityTypeXML->status;
     } else {
         $statusName = 'Scheduled';
     }
     require_once 'CRM/Core/OptionGroup.php';
     if ($activityTypeName == 'Open Case') {
         $activityParams = array('activity_type_id' => $activityTypeID, 'source_contact_id' => $params['creatorID'], 'is_auto' => false, 'is_current_revision' => 1, 'subject' => CRM_Utils_Array::value('subject', $params) ? $params['subject'] : $activityTypeName, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', $statusName, 'name'), 'target_contact_id' => $params['clientID'], 'medium_id' => CRM_Utils_Array::value('medium_id', $params), 'location' => CRM_Utils_Array::value('location', $params), 'details' => CRM_Utils_Array::value('details', $params), 'duration' => CRM_Utils_Array::value('duration', $params));
     } else {
         $activityParams = array('activity_type_id' => $activityTypeID, 'source_contact_id' => $params['creatorID'], 'is_auto' => true, 'is_current_revision' => 1, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', $statusName, 'name'), 'target_contact_id' => $params['clientID']);
     }
     if ($activityTypeName == 'Open Case') {
         // we don't set activity_date_time for auto generated
         // activities, but we want it to be set for open case.
         $activityParams['activity_date_time'] = $params['activity_date_time'];
         if (array_key_exists('custom', $params) && is_array($params['custom'])) {
             $activityParams['custom'] = $params['custom'];
         }
     } else {
         $activityDate = null;
         //get date of reference activity if set.
         if ($referenceActivityName = (string) $activityTypeXML->reference_activity) {
             //we skip open case as reference activity.CRM-4374.
             if (CRM_Utils_Array::value('resetTimeline', $params) && $referenceActivityName == 'Open Case') {
                 $activityDate = $params['activity_date_time'];
             } else {
                 $referenceActivityInfo = CRM_Utils_Array::value($referenceActivityName, $activityTypes);
                 if ($referenceActivityInfo['id']) {
                     $caseActivityParams = array('activity_type_id' => $referenceActivityInfo['id']);
                     //if reference_select is set take according activity.
                     if ($referenceSelect = (string) $activityTypeXML->reference_select) {
                         $caseActivityParams[$referenceSelect] = 1;
                     }
                     require_once 'CRM/Case/BAO/Case.php';
                     $referenceActivity = CRM_Case_BAO_Case::getCaseActivityDates($params['caseID'], $caseActivityParams, true);
                     if (is_array($referenceActivity)) {
                         foreach ($referenceActivity as $aId => $details) {
                             $activityDate = CRM_Utils_Array::value('activity_date', $details);
                             break;
                         }
                     }
                 }
             }
         }
         if (!$activityDate) {
             $activityDate = $params['activity_date_time'];
         }
         $datetime = new DateTime($activityDate);
         $activityDateTime = CRM_Utils_Date::unformat($datetime->format('Y:m:d:H:i:s'), ':');
         //add reference offset to date.
         if ((int) $activityTypeXML->reference_offset) {
             $activityDateTime = CRM_Utils_Date::intervalAdd('day', (int) $activityTypeXML->reference_offset, $activityDateTime);
         }
         $activityParams['activity_date_time'] = CRM_Utils_Date::format($activityDateTime);
     }
     // if same activity is already there, skip and dont touch
     $params['activityTypeID'] = $activityTypeID;
     $params['activityTypeName'] = $activityTypeName;
     if ($this->isActivityPresent($params)) {
         return true;
     }
     $activityParams['case_id'] = $params['caseID'];
     if (CRM_Utils_Array::value('is_auto', $activityParams)) {
         $activityParams['skipRecentView'] = true;
     }
     require_once 'CRM/Activity/BAO/Activity.php';
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     if (!$activity) {
         CRM_Core_Error::fatal();
         return false;
     }
     // create case activity record
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $params['caseID']);
     require_once 'CRM/Case/BAO/Case.php';
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     return true;
 }
Esempio n. 14
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = null;
         //block deleting activities which affects
         //case attributes.CRM-4543
         $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
         $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', false, false, false, $activityCondition);
         if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
             $params = array('id' => $this->_activityId);
             $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, true);
             if ($activityDelete) {
                 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
             }
         } else {
             $statusMsg = ts("Selected Activity cannot be deleted.");
         }
         require_once 'CRM/Core/BAO/EntityTag.php';
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = null;
         $params = array('id' => $this->_activityId);
         $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
         if ($activityRestore) {
             $statusMsg = ts('The selected activity has been restored.<br />');
         }
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     if ($params['source_contact_id']) {
         $params['source_contact_id'] = $params['source_contact_qid'];
     }
     //set parent id if its edit mode
     if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
         $params['parent_id'] = $parentId;
     }
     // required for status msg
     $recordStatus = 'created';
     // store the dates with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     $params['activity_type_id'] = $this->_activityTypeId;
     require_once 'CRM/Case/XMLProcessor/Process.php';
     $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
     $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
     $this->assign('multiClient', $isMultiClient);
     $targetContacts = array($this->_currentlyViewedContactId);
     if (CRM_Utils_Array::value('hidden_target_contact', $params) && CRM_Utils_Array::value('target_contact_id', $params)) {
         $targetContacts = array_unique(explode(',', $params['target_contact_id']));
     }
     $params['target_contact_id'] = $targetContacts;
     // format activity custom data
     if (CRM_Utils_Array::value('hidden_custom', $params)) {
         if ($this->_activityId) {
             // unset custom fields-id from params since we want custom
             // fields to be saved for new activity.
             foreach ($params as $key => $value) {
                 $match = array();
                 if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) {
                     $params[$match[1] . '-1'] = $params[$key];
                     // for autocomplete transfer hidden value instead of label
                     if ($params[$key] && isset($params[$key . '_id'])) {
                         $params[$match[1] . '-1_id'] = $params[$key . '_id'];
                         unset($params[$key . '_id']);
                     }
                     unset($params[$key]);
                 }
             }
         }
         // build custom data getFields array
         $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');
     }
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         $assineeContacts = explode(',', $params['assignee_contact_id']);
         $assineeContacts = array_unique($assineeContacts);
         unset($params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = $assineeContacts = array();
     }
     if (isset($this->_activityId)) {
         // activity which hasn't been modified by a user yet
         if ($this->_defaults['is_auto'] == 1) {
             $params['is_auto'] = 0;
         }
         // always create a revision of an case activity. CRM-4533
         $newActParams = $params;
         // add target contact values in update mode
         if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
             $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
         }
         // record status for status msg
         $recordStatus = 'updated';
     }
     if (!isset($newActParams)) {
         // add more attachments if needed for old activity
         CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($params);
         $params['case_id'] = $this->_caseId;
         // activity create/update
         $activity = CRM_Activity_BAO_Activity::create($params);
         // call end post process, after the activity has been created/updated.
         $this->endPostProcess($params, $activity);
     } else {
         // since the params we need to set are very few, and we don't want rest of the
         // work done by bao create method , lets use dao object to make the changes
         $params = array('id' => $this->_activityId);
         $params['is_current_revision'] = 0;
         $activity = new CRM_Activity_DAO_Activity();
         $activity->copyValues($params);
         $activity->save();
     }
     // create a new version of activity if activity was found to
     // have been modified/created by user
     if (isset($newActParams)) {
         // set proper original_id
         if (CRM_Utils_Array::value('original_id', $this->_defaults)) {
             $newActParams['original_id'] = $this->_defaults['original_id'];
         } else {
             $newActParams['original_id'] = $activity->id;
         }
         //is_current_revision will be set to 1 by default.
         // add attachments if any
         CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($newActParams);
         $newActParams['case_id'] = $this->_caseId;
         $activity = CRM_Activity_BAO_Activity::create($newActParams);
         // call end post process, after the activity has been created/updated.
         $this->endPostProcess($newActParams, $activity);
         // copy files attached to old activity if any, to new one,
         // as long as users have not selected the 'delete attachment' option.
         if (!CRM_Utils_Array::value('is_delete_attachment', $newActParams)) {
             CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id);
         }
         // copy back params to original var
         $params = $newActParams;
     }
     if ($activity->id) {
         // add tags if exists
         $tagParams = array();
         if (!empty($params['tag'])) {
             foreach ($params['tag'] as $tag) {
                 $tagParams[$tag] = 1;
             }
         }
         //save static tags
         require_once 'CRM/Core/BAO/EntityTag.php';
         CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);
         //save free tags
         if (isset($params['taglist']) && !empty($params['taglist'])) {
             require_once 'CRM/Core/Form/Tag.php';
             CRM_Core_Form_Tag::postProcess($params['taglist'], $activity->id, 'civicrm_activity', $this);
         }
     }
     $params['assignee_contact_id'] = $assineeContacts;
     // update existing case record if needed
     $caseParams = $params;
     $caseParams['id'] = $this->_caseId;
     if (CRM_Utils_Array::value('case_type_id', $caseParams)) {
         $caseParams['case_type_id'] = CRM_Case_BAO_Case::VALUE_SEPERATOR . $caseParams['case_type_id'] . CRM_Case_BAO_Case::VALUE_SEPERATOR;
     }
     if (CRM_Utils_Array::value('case_status_id', $caseParams)) {
         $caseParams['status_id'] = $caseParams['case_status_id'];
     }
     // unset params intended for activities only
     unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']);
     $case = CRM_Case_BAO_Case::create($caseParams);
     // create case activity record
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $this->_caseId);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     // create activity assignee records
     $assigneeParams = array('activity_id' => $activity->id);
     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']);
         $activityId = isset($this->_activityId) ? $this->_activityId : $activity->id;
         $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityId);
         $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
         foreach ($params['assignee_contact_id'] as $key => $id) {
             $assigneeParams['assignee_contact_id'] = $id;
             CRM_Activity_BAO_Activity::createActivityAssignment($assigneeParams);
         }
         //modify assigne_contact as per newly assigned contact before sending copy. CRM-4509.
         $params['assignee_contact_id'] = $activityAssigned;
     }
     // Insert civicrm_log record for the activity (e.g. store the
     // created / edited by contact id and date for the activity)
     // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
     // send copy to selected contacts.
     $mailStatus = '';
     $mailToContacts = array();
     //CRM-5695
     //check for notification settings for assignee contacts
     $selectedContacts = array('contact_check');
     $config =& CRM_Core_Config::singleton();
     if ($config->activityAssigneeNotification) {
         $selectedContacts[] = 'assignee_contact_id';
     }
     foreach ($selectedContacts as $dnt => $val) {
         if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) {
             if ($val == 'contact_check') {
                 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
             } else {
                 $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activity->id, true, false);
                 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
             }
             //build an associative array with unique email addresses.
             foreach ($params[$val] as $id => $dnc) {
                 if (isset($id) && array_key_exists($id, $this->_relatedContacts)) {
                     //if email already exists in array then append with ', ' another role only otherwise add it to array.
                     if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
                         $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
                         $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
                     } else {
                         $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
                     }
                 }
             }
         }
     }
     if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
         //include attachments while sendig a copy of activity.
         $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
         $result = CRM_Case_BAO_Case::sendActivityCopy($this->_currentlyViewedContactId, $activity->id, $mailToContacts, $attachments, $this->_caseId);
         if (empty($result)) {
             $mailStatus = '';
         }
     } else {
         $mailStatus = '';
     }
     // create follow up activity if needed
     $followupStatus = '';
     if (CRM_Utils_Array::value('followup_activity_type_id', $params)) {
         $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
         if ($followupActivity) {
             $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $this->_caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
             $followupStatus = ts("A followup activity has been scheduled.");
         }
     }
     CRM_Core_Session::setStatus(ts("'%1' activity has been %2. %3 %4", array(1 => $this->_activityTypeName, 2 => $recordStatus, 3 => $followupStatus, 4 => $mailStatus)));
 }
Esempio n. 15
0
 /**
  * Process the form after the input has been submitted and validated.
  *
  * @param CRM_Core_Form $form
  */
 public static function postProcess(&$form)
 {
     if (count($form->_contactIds) > self::MAX_EMAILS_KILL_SWITCH) {
         CRM_Core_Error::fatal(ts('Please do not use this task to send a lot of emails (greater than %1). We recommend using CiviMail instead.', array(1 => self::MAX_EMAILS_KILL_SWITCH)));
     }
     // check and ensure that
     $formValues = $form->controller->exportValues($form->getName());
     $fromEmail = $formValues['fromEmailAddress'];
     $from = CRM_Utils_Array::value($fromEmail, $form->_emails);
     $subject = $formValues['subject'];
     // CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields
     $elements = array('cc_id', 'bcc_id');
     $additionalDetails = NULL;
     $ccValues = $bccValues = array();
     foreach ($elements as $element) {
         if (!empty($formValues[$element])) {
             $allEmails = explode(',', $formValues[$element]);
             foreach ($allEmails as $value) {
                 list($contactId, $email) = explode('::', $value);
                 $contactURL = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$contactId}", TRUE);
                 switch ($element) {
                     case 'cc_id':
                         $ccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
                         $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
                         break;
                     case 'bcc_id':
                         $bccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
                         $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
                         break;
                 }
             }
         }
     }
     $cc = $bcc = '';
     if (!empty($ccValues)) {
         $cc = implode(',', $ccValues['email']);
         $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']);
     }
     if (!empty($bccValues)) {
         $bcc = implode(',', $bccValues['email']);
         $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']);
     }
     // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
     if (isset($form->_caseId) && is_numeric($form->_caseId)) {
         $hash = substr(sha1(CIVICRM_SITE_KEY . $form->_caseId), 0, 7);
         $subject = "[case #{$hash}] {$subject}";
     }
     // process message template
     if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
         $messageTemplate = array('msg_text' => $formValues['text_message'], 'msg_html' => $formValues['html_message'], 'msg_subject' => $formValues['subject'], 'is_active' => TRUE);
         if (!empty($formValues['saveTemplate'])) {
             $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
             CRM_Core_BAO_MessageTemplate::add($messageTemplate);
         }
         if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) {
             $messageTemplate['id'] = $formValues['template'];
             unset($messageTemplate['msg_title']);
             CRM_Core_BAO_MessageTemplate::add($messageTemplate);
         }
     }
     $attachments = array();
     CRM_Core_BAO_File::formatAttachment($formValues, $attachments, NULL, NULL);
     // format contact details array to handle multiple emails from same contact
     $formattedContactDetails = array();
     $tempEmails = array();
     foreach ($form->_contactIds as $key => $contactId) {
         // if we dont have details on this contactID, we should ignore
         // potentially this is due to the contact not wanting to receive email
         if (!isset($form->_contactDetails[$contactId])) {
             continue;
         }
         $email = $form->_toContactEmails[$key];
         // prevent duplicate emails if same email address is selected CRM-4067
         // we should allow same emails for different contacts
         $emailKey = "{$contactId}::{$email}";
         if (!in_array($emailKey, $tempEmails)) {
             $tempEmails[] = $emailKey;
             $details = $form->_contactDetails[$contactId];
             $details['email'] = $email;
             unset($details['email_id']);
             $formattedContactDetails[] = $details;
         }
     }
     // send the mail
     list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail($formattedContactDetails, $subject, $formValues['text_message'], $formValues['html_message'], NULL, NULL, $from, $attachments, $cc, $bcc, array_keys($form->_toContactDetails), $additionalDetails);
     $followupStatus = '';
     if ($sent) {
         $followupActivity = NULL;
         if (!empty($formValues['followup_activity_type_id'])) {
             $params['followup_activity_type_id'] = $formValues['followup_activity_type_id'];
             $params['followup_activity_subject'] = $formValues['followup_activity_subject'];
             $params['followup_date'] = $formValues['followup_date'];
             $params['followup_date_time'] = $formValues['followup_date_time'];
             $params['target_contact_id'] = $form->_contactIds;
             $params['followup_assignee_contact_id'] = explode(',', $formValues['followup_assignee_contact_id']);
             $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activityId, $params);
             $followupStatus = ts('A followup activity has been scheduled.');
             if (Civi::settings()->get('activity_assignee_notification')) {
                 if ($followupActivity) {
                     $mailToFollowupContacts = array();
                     $assignee = array($followupActivity->id);
                     $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($assignee, TRUE, FALSE);
                     foreach ($assigneeContacts as $values) {
                         $mailToFollowupContacts[$values['email']] = $values;
                     }
                     $sentFollowup = CRM_Activity_BAO_Activity::sendToAssignee($followupActivity, $mailToFollowupContacts);
                     if ($sentFollowup) {
                         $followupStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
                     }
                 }
             }
         }
         $count_success = count($form->_toContactDetails);
         CRM_Core_Session::setStatus(ts('One message was sent successfully. ', array('plural' => '%count messages were sent successfully. ', 'count' => $count_success)) . $followupStatus, ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $count_success)), 'success');
     }
     // Display the name and number of contacts for those email is not sent.
     // php 5.4 throws out a notice since the values of these below arrays are arrays.
     // the behavior is not documented in the php manual, but it does the right thing
     // suppressing the notices to get things in good shape going forward
     $emailsNotSent = @array_diff_assoc($form->_allContactDetails, $form->_contactDetails);
     if ($emailsNotSent) {
         $not_sent = array();
         foreach ($emailsNotSent as $contactId => $values) {
             $displayName = $values['display_name'];
             $email = $values['email'];
             $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contactId}");
             $not_sent[] = "<a href='{$contactViewUrl}' title='{$email}'>{$displayName}</a>" . ($values['on_hold'] ? '(' . ts('on hold') . ')' : '');
         }
         $status = '(' . ts('because no email address on file or communication preferences specify DO NOT EMAIL or Contact is deceased or Primary email address is On Hold') . ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>';
         CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($emailsNotSent), 'plural' => '%count Messages Not Sent')), 'info');
     }
     if (isset($form->_caseId)) {
         // if case-id is found in the url, create case activity record
         $cases = explode(',', $form->_caseId);
         foreach ($cases as $key => $val) {
             if (is_numeric($val)) {
                 $caseParams = array('activity_id' => $activityId, 'case_id' => $val);
                 CRM_Case_BAO_Case::processCaseActivity($caseParams);
             }
         }
     }
 }
Esempio n. 16
0
/**
 * Creates or updates an Activity.
 *
 * @param array $params
 *   Array per getfields documentation.
 *
 * @throws API_Exception
 * @return array
 *   API result array
 */
function civicrm_api3_activity_create($params)
{
    if (empty($params['id'])) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('activity_name', 'activity_type_id', 'activity_label'));
    }
    // check for various error and required conditions
    // note that almost all the processing in there should be managed by the wrapper layer
    // & should be removed - needs testing
    $errors = _civicrm_api3_activity_check_params($params);
    // this should not be required as should throw exception rather than return errors -
    //needs testing
    if (!empty($errors)) {
        return $errors;
    }
    // processing for custom data
    $values = $activityArray = array();
    _civicrm_api3_custom_format_params($params, $values, 'Activity');
    if (!empty($values['custom'])) {
        $params['custom'] = $values['custom'];
    }
    // this should be set as a default rather than hard coded
    // needs testing
    $params['skipRecentView'] = TRUE;
    // If this is a case activity, see if there is an existing activity
    // and set it as an old revision. Also retrieve details we'll need.
    // this handling should all be moved to the BAO layer
    $case_id = '';
    $createRevision = FALSE;
    $oldActivityValues = array();
    // Lookup case id if not supplied
    if (!isset($params['case_id']) && !empty($params['id'])) {
        $params['case_id'] = CRM_Core_DAO::singleValueQuery("SELECT case_id FROM civicrm_case_activity WHERE activity_id = " . (int) $params['id']);
    }
    if (!empty($params['case_id'])) {
        $case_id = $params['case_id'];
        if (!empty($params['id'])) {
            $oldActivityParams = array('id' => $params['id']);
            if (!$oldActivityValues) {
                CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
            }
            if (empty($oldActivityValues)) {
                throw new API_Exception(ts("Unable to locate existing activity."));
            } else {
                $activityDAO = new CRM_Activity_DAO_Activity();
                $activityDAO->id = $params['id'];
                $activityDAO->is_current_revision = 0;
                if (!$activityDAO->save()) {
                    if (is_object($activityDAO)) {
                        $activityDAO->free();
                    }
                    throw new API_Exception(ts("Unable to revision existing case activity."));
                }
                $createRevision = TRUE;
            }
        }
    }
    $deleteActivityAssignment = FALSE;
    if (isset($params['assignee_contact_id'])) {
        $deleteActivityAssignment = TRUE;
    }
    $deleteActivityTarget = FALSE;
    if (isset($params['target_contact_id'])) {
        $deleteActivityTarget = TRUE;
    }
    // this should all be handled at the BAO layer
    $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
    $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
    if ($case_id && $createRevision) {
        // This is very similar to the copy-to-case action.
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
            $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
        }
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
            $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
        }
        $oldActivityValues['mode'] = 'copy';
        $oldActivityValues['caseID'] = $case_id;
        $oldActivityValues['activityID'] = $oldActivityValues['id'];
        $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
        $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
        if (empty($copyToCase['error_msg'])) {
            // now fix some things that are different from copy-to-case
            // then fall through to the create below to update with the passed in params
            $params['id'] = $copyToCase['newId'];
            $params['is_auto'] = 0;
            $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
        } else {
            throw new API_Exception(ts("Unable to create new revision of case activity."));
        }
    }
    // create activity
    $activityBAO = CRM_Activity_BAO_Activity::create($params);
    if (isset($activityBAO->id)) {
        if ($case_id && !$createRevision) {
            // If this is a brand new case activity we need to add this
            $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
            CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
        }
        _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
        return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
    }
}
 /**
  * Process the form submission.
  *
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param $activity
  */
 public static function endPostProcess(&$form, &$params, $activity)
 {
     if (!empty($params['start_date'])) {
         $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
     }
     $caseType = CRM_Utils_Array::first($form->_caseType);
     $caseId = CRM_Utils_Array::first($form->_caseId);
     if (!$caseType && $caseId) {
         $caseType = CRM_Case_BAO_Case::getCaseType($caseId, 'title');
     }
     if (!$form->_currentlyViewedContactId || !$form->_currentUserId || !$caseId || !$caseType) {
         CRM_Core_Error::fatal('Required parameter missing for ChangeCaseType - end post processing');
     }
     $config = CRM_Core_Config::singleton();
     $params['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activity->status_id = $params['status_id'];
     $params['priority_id'] = CRM_Core_OptionGroup::getValue('priority', 'Normal', 'name');
     $activity->priority_id = $params['priority_id'];
     // 1. save activity subject with new start date
     $currentStartDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseId, 'start_date'), $config->dateformatFull);
     $newStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Date::mysqlToIso($params['start_date']), $config->dateformatFull);
     $subject = 'Change Case Start Date from ' . $currentStartDate . ' to ' . $newStartDate;
     $activity->subject = $subject;
     $activity->save();
     // 2. initiate xml processor
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $xmlProcessorParams = array('clientID' => $form->_currentlyViewedContactId, 'creatorID' => $form->_currentUserId, 'standardTimeline' => 0, 'activity_date_time' => $params['start_date'], 'caseID' => $caseId, 'caseType' => $caseType, 'activityTypeName' => 'Change Case Start Date', 'activitySetName' => 'standard_timeline', 'resetTimeline' => 1);
     $xmlProcessor->run($caseType, $xmlProcessorParams);
     // 2.5 Update open case activity date
     // Multiple steps since revisioned
     if ($form->openCaseActivityId) {
         $abao = new CRM_Activity_BAO_Activity();
         $oldParams = array('id' => $form->openCaseActivityId);
         $oldActivityDefaults = array();
         $oldActivity = $abao->retrieve($oldParams, $oldActivityDefaults);
         // save the old values
         require_once 'api/v3/utils.php';
         $openCaseParams = array();
         //@todo calling api functions directly is not supported
         _civicrm_api3_object_to_array($oldActivity, $openCaseParams);
         // update existing revision
         $oldParams = array('id' => $form->openCaseActivityId, 'is_current_revision' => 0);
         $oldActivity = new CRM_Activity_DAO_Activity();
         $oldActivity->copyValues($oldParams);
         $oldActivity->save();
         // change some params for the new one
         unset($openCaseParams['id']);
         $openCaseParams['activity_date_time'] = $params['start_date'];
         $openCaseParams['target_contact_id'] = $oldActivityDefaults['target_contact'];
         $openCaseParams['assignee_contact_id'] = $oldActivityDefaults['assignee_contact'];
         $session = CRM_Core_Session::singleton();
         $openCaseParams['source_contact_id'] = $session->get('userID');
         // original_id always refers to the first activity, so only update if null (i.e. this is the second revision)
         $openCaseParams['original_id'] = $openCaseParams['original_id'] ? $openCaseParams['original_id'] : $form->openCaseActivityId;
         $newActivity = CRM_Activity_BAO_Activity::create($openCaseParams);
         if (is_a($newActivity, 'CRM_Core_Error')) {
             CRM_Core_Error::fatal('Unable to update Open Case activity');
         } else {
             // Create linkage to case
             $caseActivityParams = array('activity_id' => $newActivity->id, 'case_id' => $caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
             $caseActivityParams = array('activityID' => $form->openCaseActivityId, 'mainActivityId' => $newActivity->id);
             CRM_Activity_BAO_Activity::copyExtendedActivityData($caseActivityParams);
         }
     }
     // 3.status msg
     $params['statusMsg'] = ts('Case Start Date changed successfully.');
 }
    /**
     * @param int $mappingID
     * @param $now
     *
     * @throws CRM_Core_Exception
     */
    public static function sendMailings($mappingID, $now)
    {
        $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
        $fromEmailAddress = "{$domainValues['0']} <{$domainValues['1']}>";
        $mapping = new CRM_Core_DAO_ActionMapping();
        $mapping->id = $mappingID;
        $mapping->find(TRUE);
        $actionSchedule = new CRM_Core_DAO_ActionSchedule();
        $actionSchedule->mapping_id = $mappingID;
        $actionSchedule->is_active = 1;
        $actionSchedule->find(FALSE);
        $tokenFields = array();
        $session = CRM_Core_Session::singleton();
        while ($actionSchedule->fetch()) {
            $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
            if ($actionSchedule->from_email) {
                $fromEmailAddress = "{$actionSchedule->from_name} <{$actionSchedule->from_email}>";
            }
            $activityTypeID = FALSE;
            $activityStatusID = FALSE;
            if ($actionSchedule->record_activity) {
                if ($mapping->entity == 'civicrm_membership') {
                    $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
                } else {
                    $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
                }
                $activityStatusID = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
            }
            if ($mapping->entity == 'civicrm_activity') {
                $compInfo = CRM_Core_Component::getEnabledComponents();
                $tokenEntity = 'activity';
                $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
                $extraSelect = ', ov.label as activity_type, e.id as activity_id';
                $extraJoin = "\nINNER JOIN civicrm_option_group og ON og.name = 'activity_type'\nINNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
                $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = "\nLEFT JOIN civicrm_option_group og ON og.name = 'activity_type'\nLEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
                }
                //join for caseId
                // if CiviCase component is enabled
                if (array_key_exists('CiviCase', $compInfo)) {
                    $extraSelect .= ", civicrm_case_activity.case_id as case_id";
                    $extraJoin .= "\n            LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
                }
            }
            if ($mapping->entity == 'civicrm_participant') {
                $tokenEntity = 'event';
                $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone', 'balance');
                $extraSelect = ', ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone ';
                $extraJoin = "\nINNER JOIN civicrm_event ev ON e.event_id = ev.id\nINNER JOIN civicrm_option_group og ON og.name = 'event_type'\nINNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT  JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT  JOIN civicrm_address address ON address.id = lb.address_id\nLEFT  JOIN civicrm_email email ON email.id = lb.email_id\nLEFT  JOIN civicrm_phone phone ON phone.id = lb.phone_id\n";
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = "\nLEFT JOIN civicrm_event ev ON e.event_id = ev.id\nLEFT JOIN civicrm_option_group og ON og.name = 'event_type'\nLEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT JOIN civicrm_address address ON address.id = lb.address_id\nLEFT JOIN civicrm_email email ON email.id = lb.email_id\nLEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id\n";
                }
            }
            if ($mapping->entity == 'civicrm_membership') {
                $tokenEntity = 'membership';
                $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
                $extraSelect = ', mt.minimum_fee as fee, e.id as id , e.join_date, e.start_date, e.end_date, ms.name as status, mt.name as type';
                $extraJoin = '
 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = '
 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
                }
            }
            if ($mapping->entity == 'civicrm_contact') {
                $tokenEntity = 'contact';
                //TODO: get full list somewhere!
                $tokenFields = array('birth_date', 'last_name');
                //TODO: is there anything to add here?
            }
            $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
            if ($actionSchedule->limit_to == 0) {
                $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
                $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
            }
            $entityJoinClause .= $extraOn;
            $query = "\nSELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}\nFROM  civicrm_action_log reminder\n{$entityJoinClause}\n{$extraJoin}\nWHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL\n{$extraWhere}";
            $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
            while ($dao->fetch()) {
                $entityTokenParams = array();
                foreach ($tokenFields as $field) {
                    if ($field == 'location') {
                        $loc = array();
                        $stateProvince = CRM_Core_PseudoConstant::stateProvince();
                        $loc['street_address'] = $dao->street_address;
                        $loc['city'] = $dao->city;
                        $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince);
                        $loc['postal_code'] = $dao->postal_code;
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
                    } elseif ($field == 'info_url') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                    } elseif ($field == 'registration_url') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                    } elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->{$field});
                    } elseif ($field == 'balance') {
                        if ($dao->entityTable == 'civicrm_contact') {
                            $balancePay = 'N/A';
                        } elseif (!empty($dao->entityID)) {
                            $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event');
                            $balancePay = CRM_Utils_Array::value('balance', $info);
                            $balancePay = CRM_Utils_Money::format($balancePay);
                        }
                        $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
                    } elseif ($field == 'fee_amount') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money::format($dao->{$field});
                    } else {
                        $entityTokenParams["{$tokenEntity}." . $field] = $dao->{$field};
                    }
                }
                $isError = 0;
                $errorMsg = $toEmail = $toPhoneNumber = '';
                if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
                    $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
                    $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters);
                    //to get primary mobile ph,if not get a first mobile phONE
                    if (!empty($toPhoneNumbers)) {
                        $toPhoneNumberDetails = reset($toPhoneNumbers);
                        $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
                        //contact allows to send sms
                        $toDoNotSms = 0;
                    }
                }
                if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
                    $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID);
                }
                if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) {
                    $to['email'] = $toEmail;
                    $to['phone'] = $toPhoneNumber;
                    $result = CRM_Core_BAO_ActionSchedule::sendReminder($dao->contactID, $to, $actionSchedule->id, $fromEmailAddress, $entityTokenParams);
                    if (!$result || is_a($result, 'PEAR_Error')) {
                        // we could not send an email, for now we ignore, CRM-3406
                        $isError = 1;
                    }
                } else {
                    $isError = 1;
                    $errorMsg = "Couldn\\'t find recipient\\'s email address.";
                }
                // update action log record
                $logParams = array('id' => $dao->reminderID, 'is_error' => $isError, 'message' => $errorMsg ? $errorMsg : "null", 'action_date_time' => $now);
                CRM_Core_BAO_ActionLog::create($logParams);
                // insert activity log record if needed
                if ($actionSchedule->record_activity && !$isError) {
                    $activityParams = array('subject' => $actionSchedule->title, 'details' => $actionSchedule->body_html, 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $dao->contactID, 'target_contact_id' => $dao->contactID, 'activity_date_time' => date('YmdHis'), 'status_id' => $activityStatusID, 'activity_type_id' => $activityTypeID, 'source_record_id' => $dao->entityID);
                    $activity = CRM_Activity_BAO_Activity::create($activityParams);
                    //file reminder on case if source activity is a case activity
                    if (!empty($dao->case_id)) {
                        $caseActivityParams = array();
                        $caseActivityParams['case_id'] = $dao->case_id;
                        $caseActivityParams['activity_id'] = $activity->id;
                        CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
                    }
                }
            }
            $dao->free();
        }
    }
Esempio n. 19
0
 function addVacancies($cid)
 {
     //sample data for HRRecruitment table
     $grpParams['name'] = 'vacancy_status';
     $optionValues = $vacancyPermissionContactIds = array();
     $caseStatuses = CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, " AND grouping = 'Vacancy'");
     $vacancyStatuses = CRM_Core_OptionGroup::values('vacancy_status');
     //Filterout Rejected and Cancelled status while creating vacancy
     foreach (array('Cancelled', 'Rejected') as $status) {
         $key = array_search($status, $vacancyStatuses);
         unset($vacancyStatuses[$key]);
     }
     $totalcount = 6;
     $setNewVacancy = FALSE;
     $templatePosition = array();
     $randomVacancies = $this->randomVacancy();
     for ($i = 1; $i <= $totalcount; $i++) {
         $jobCount = mt_rand(0, 2);
         $position = $randomVacancies[$jobCount]['position'];
         $vacanciesValues = array('salary' => $randomVacancies[$jobCount]['salary'], 'position' => $position, 'description' => $this->randomItem('vacancydescription'), 'benefits' => $randomVacancies[$jobCount]['benefits'], 'requirements' => $randomVacancies[$jobCount]['requirements'], 'location' => $this->randomItem('location'), 'is_template' => mt_rand(0, 1), 'status_id' => array_rand($vacancyStatuses, 1), 'start_date' => $this->randomDate('20130701', '20140101', 'YmdHis'), 'end_date' => $this->randomDate('20140102', '20151231', 'YmdHis'), 'created_id' => $cid, 'created_date' => $this->randomDate());
         if ($vacanciesValues['is_template'] == 1) {
             unset($vacanciesValues['status_id']);
             if (array_key_exists($position, $templatePosition)) {
                 //always create distict template
                 continue;
             }
             $templatePosition[$position] = NULL;
         } else {
             $setNewVacancy = TRUE;
         }
         //ensure that atleast there is one vacancy not all template
         if (!$setNewVacancy && $i == $totalcount) {
             $totalcount++;
         }
         $hrVacancies[] = $this->insertVacancyData('CRM_HRRecruitment_DAO_HRVacancy', $vacanciesValues);
     }
     //There are 6 sample Vacancies created, next is to create Entities - VacancyStage, VacancyPermission, Cases
     foreach ($hrVacancies as $key => $hrVacanciesObj) {
         $selectedCaseStatuses = array();
         $lastSelectedCaseStatus = NULL;
         $randCaseStatus = $caseStatuses;
         //Igonre Apply and Hired statuses while removing random status
         $ignoreCaseStatus = array(array_search('Apply', $randCaseStatus), array_search('Hired', $randCaseStatus));
         for ($i = 1; $i <= mt_rand(1, 6); $i++) {
             $randomValue = array_rand($randCaseStatus, 1);
             if (in_array($randomValue, $ignoreCaseStatus)) {
                 continue;
             }
             unset($randCaseStatus[$randomValue]);
         }
         $count = 1;
         foreach ($randCaseStatus as $caseStatus => $dontCare) {
             $vacancyStagesValues = array('case_status_id' => $caseStatus, 'vacancy_id' => $hrVacanciesObj->id, 'weight' => $count);
             $count++;
             $this->insertVacancyData('CRM_HRRecruitment_DAO_HRVacancyStage', $vacancyStagesValues);
         }
         //sample data for HRPermission table
         $vacancyPermissionContactIds[$hrVacanciesObj->id][] = $hrVacanciesObj->created_id;
         for ($i = 1; $i <= mt_rand(1, 4); $i++) {
             $vacancyPermissionValues = array('contact_id' => $this->randomContact(), 'vacancy_id' => $hrVacanciesObj->id, 'permission' => $this->randomItem('permission'));
             if ($vacancyPermissionValues['permission'] == 'manage Applicants' || $vacancyPermissionValues['permission'] == 'administer Vacancy') {
                 $vacancyPermissionContactIds[$hrVacanciesObj->id][] = $vacancyPermissionValues['contact_id'];
             }
             $this->insertVacancyData('CRM_HRRecruitment_DAO_HRVacancyPermission', $vacancyPermissionValues);
         }
         foreach (array('application_profile', 'evaluation_profile') as $profileName) {
             $ufgID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileName, 'id', 'name');
             $vacancyUFJoinValues = array('module' => 'Vacancy', 'entity_id' => $hrVacanciesObj->id, 'entity_table' => 'civicrm_hrvacancy', 'uf_group_id' => $ufgID, 'module_data' => $profileName);
             $this->insertVacancyData('CRM_Core_DAO_UFJoin', $vacancyUFJoinValues);
             $caseTypes = CRM_Case_PseudoConstant::caseType('name', 1, 'AND filter = 1');
             if (!$hrVacanciesObj->is_template) {
                 for ($i = 1; $i <= mt_rand(1, 4); $i++) {
                     $applicantID = $this->randomContact();
                     $caseParams['case_type_id'] = CRM_Utils_Array::key('Application', $caseTypes);
                     $caseParams['start_date'] = $this->randomDate($hrVacanciesObj->start_date, $hrVacanciesObj->end_date);
                     $caseParams['status_id'] = array_rand($randCaseStatus, 1);
                     $caseObj = CRM_Case_BAO_Case::create($caseParams);
                     $contactParams = array('case_id' => $caseObj->id, 'contact_id' => $applicantID);
                     CRM_Case_BAO_Case::addCaseToContact($contactParams);
                     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
                     $xmlProcessorParams = array('clientID' => $applicantID, 'creatorID' => $cid, 'standardTimeline' => 1, 'activityTypeName' => 'Open Case', 'caseID' => $caseObj->id, 'activity_date_time' => $caseParams['start_date']);
                     $xmlProcessor->run('Application', $xmlProcessorParams);
                     $aTypes = $xmlProcessor->get('Application', 'ActivityTypes');
                     $aTypes = array_rand(array_flip($aTypes), mt_rand(2, 5));
                     foreach ($aTypes as $aType) {
                         if (in_array($aType, array('Open Case', 'Assign Case Role', 'Link Cases'))) {
                             continue;
                         }
                         $index = array_rand($vacancyPermissionContactIds[$hrVacanciesObj->id], 1);
                         $aParam = array('source_contact_id' => $vacancyPermissionContactIds[$hrVacanciesObj->id][$index], 'activity_date_time' => $this->randomDate($hrVacanciesObj->start_date, $hrVacanciesObj->end_date, 'YmdHis'), 'activity_type_id' => $aType, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'));
                         if ($aType == 'Change Case Status') {
                             $aParam['last_status'] = $caseStatuses[$caseObj->status_id];
                             $caseObj->status_id = array_rand($caseStatuses, 1);
                             $caseObj->save();
                             $aParam['new_status'] = $caseStatuses[$caseObj->status_id];
                         }
                         $this->addActivityParamByType($aType, $aParam);
                         $result = civicrm_api3('Activity', 'create', $aParam);
                         $caseActivityParams = array('case_id' => $caseObj->id, 'activity_id' => $result['id']);
                         CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
                     }
                     $cgID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', 'application_case', 'id', 'name');
                     $result = civicrm_api3('CustomField', 'get', array('custom_group_id' => $cgID, 'name' => 'vacancy_id'));
                     civicrm_api3('custom_value', 'create', array("custom_{$result['id']}" => $hrVacanciesObj->id, 'entity_id' => $caseObj->id));
                 }
             }
         }
     }
 }
Esempio n. 20
0
 /**
  * Save a record about the delivery of a reminder email.
  *
  * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
  * sending the message and pass in the fully rendered text of the message.
  *
  * @param CRM_Core_DAO_ActionSchedule $actionSchedule
  * @param Civi\ActionSchedule\Mapping $mapping
  * @param int $contactID
  * @param int $entityID
  * @param int|NULL $caseID
  * @throws CRM_Core_Exception
  */
 protected static function createMailingActivity($actionSchedule, $mapping, $contactID, $entityID, $caseID)
 {
     $session = CRM_Core_Session::singleton();
     if ($mapping->getEntity() == 'civicrm_membership') {
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
     } else {
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
     }
     $activityParams = array('subject' => $actionSchedule->title, 'details' => $actionSchedule->body_html, 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $contactID, 'target_contact_id' => $contactID, 'activity_date_time' => CRM_Utils_Time::getTime('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'activity_type_id' => $activityTypeID, 'source_record_id' => $entityID);
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     //file reminder on case if source activity is a case activity
     if (!empty($caseID)) {
         $caseActivityParams = array();
         $caseActivityParams['case_id'] = $caseID;
         $caseActivityParams['activity_id'] = $activity->id;
         CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
     }
 }
Esempio n. 21
0
 public function addClient()
 {
     $caseId = CRM_Utils_Type::escape($_POST['caseID'], 'Positive');
     $contactId = CRM_Utils_Type::escape($_POST['contactID'], 'Positive');
     if (!$contactId || !CRM_Case_BAO_Case::accessCase($caseId)) {
         CRM_Utils_System::permissionDenied();
     }
     $params = array('case_id' => $caseId, 'contact_id' => $contactId);
     CRM_Case_BAO_Case::addCaseToContact($params);
     // add case relationships
     CRM_Case_BAO_Case::addCaseRelationships($caseId, $contactId);
     $session = CRM_Core_Session::singleton();
     $activityParams = array();
     $activityParams['source_contact_id'] = $session->get('userID');
     $activityParams['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Add Client To Case', 'name');
     $activityParams['activity_date_time'] = date('YmdHis');
     $activityParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activityParams['case_id'] = $caseId;
     $activityParams['is_auto'] = 0;
     $activityParams['subject'] = 'Client Added To Case';
     $activity = CRM_Activity_BAO_Activity::create($activityParams);
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $caseId);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     CRM_Utils_JSON::output(TRUE);
 }
 /**
  * @param CRM_Core_Form $form
  * @param $html_message
  * @param $contactIds
  *
  * @throws CRM_Core_Exception
  */
 public static function createActivities($form, $html_message, $contactIds)
 {
     //Added for CRM-12682: Add activity subject and campaign fields
     $formValues = $form->controller->exportValues($form->getName());
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name');
     $activityParams = array('subject' => $formValues['subject'], 'campaign_id' => CRM_Utils_Array::value('campaign_id', $formValues), 'source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'details' => $html_message);
     if (!empty($form->_activityId)) {
         $activityParams += array('id' => $form->_activityId);
     }
     if ($form->_cid) {
         $activity = CRM_Activity_BAO_Activity::create($activityParams);
         if (!empty($form->_caseId)) {
             $caseActivityParams = array('activity_id' => $activity->id, 'case_id' => $form->_caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
         }
     } else {
         // create  Print PDF activity for each selected contact. CRM-6886
         $activityIds = array();
         foreach ($contactIds as $contactId) {
             $activityID = CRM_Activity_BAO_Activity::create($activityParams);
             $activityIds[$contactId] = $activityID->id;
         }
     }
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
     //@todo why are we using $form->_contactIds here & contactIds above - need comment
     foreach ($form->_contactIds as $contactId) {
         $activityTargetParams = array('activity_id' => empty($activity->id) ? $activityIds[$contactId] : $activity->id, 'contact_id' => $contactId, 'record_type_id' => $targetID);
         CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
     }
 }
Esempio n. 23
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 static function endPostProcess(&$form, &$params, &$activity)
 {
     $activityId = $activity->id;
     $linkCaseID = CRM_Utils_Array::value('link_to_case_id', $params);
     //create a link between two cases.
     if ($activityId && $linkCaseID) {
         $caseParams = array('case_id' => $linkCaseID, 'activity_id' => $activityId);
         CRM_Case_BAO_Case::processCaseActivity($caseParams);
     }
 }
Esempio n. 24
0
 /**
  * Function to process the activities
  *
  * @param object $form         form object
  * @param array  $params       associated array of the submitted values
  * @param array  $ids          array of ids
  * @param string $activityType activity Type
  * @param boolean $record   true if it is Record Activity 
  * @access public
  * @return
  */
 public function create(&$params)
 {
     // check required params
     if (!self::dataExists($params)) {
         CRM_Core_Error::fatal('Not enough data to create activity object,');
     }
     $activity = new CRM_Activity_DAO_Activity();
     if (!CRM_Utils_Array::value('status_id', $params)) {
         if (isset($params['activity_date_time']) && strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)) {
             $params['status_id'] = 2;
         } else {
             $params['status_id'] = 1;
         }
     }
     //set priority to Normal for Auto-populated activities (for Cases)
     if (!CRM_Utils_Array::value('priority_id', $params)) {
         require_once 'CRM/Core/PseudoConstant.php';
         $priority = CRM_Core_PseudoConstant::priority();
         $params['priority_id'] = array_search('Normal', $priority);
     }
     if (empty($params['id'])) {
         unset($params['id']);
     }
     if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
         $params['target_contact_id'] = array_unique($params['target_contact_id']);
     }
     if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
     }
     $activity->copyValues($params);
     // start transaction
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $result = $activity->save();
     if (is_a($result, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $result;
     }
     $activityId = $activity->id;
     // check and attach and files as needed
     require_once 'CRM/Core/BAO/File.php';
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
     // attempt to save activity assignment
     $resultAssignment = null;
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         require_once 'CRM/Activity/BAO/ActivityAssignment.php';
         $assignmentParams = array('activity_id' => $activityId);
         if (is_array($params['assignee_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityAssignment', $params, true)) {
                 // first delete existing assignments if any
                 self::deleteActivityAssignment($activityId);
             }
             foreach ($params['assignee_contact_id'] as $acID) {
                 if ($acID) {
                     $assignmentParams['assignee_contact_id'] = $acID;
                     $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
                     if (is_a($resultAssignment, 'CRM_Core_Error')) {
                         $transaction->rollback();
                         return $resultAssignment;
                     }
                 }
             }
         } else {
             $assignmentParams['assignee_contact_id'] = $params['assignee_contact_id'];
             if (CRM_Utils_Array::value('id', $params)) {
                 $assignment = new CRM_Activity_BAO_ActivityAssignment();
                 $assignment->activity_id = $activityId;
                 $assignment->find(true);
                 if ($assignment->assignee_contact_id != $params['assignee_contact_id']) {
                     $assignmentParams['id'] = $assignment->id;
                     $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
                 }
             } else {
                 $resultAssignment = CRM_Activity_BAO_ActivityAssignment::create($assignmentParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityAssignment', $params, true)) {
             self::deleteActivityAssignment($activityId);
         }
     }
     if (is_a($resultAssignment, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $resultAssignment;
     }
     // attempt to save activity targets
     $resultTarget = null;
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         $targetParams = array('activity_id' => $activityId);
         $resultTarget = array();
         if (is_array($params['target_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityTarget', $params, true)) {
                 // first delete existing targets if any
                 self::deleteActivityTarget($activityId);
             }
             foreach ($params['target_contact_id'] as $tid) {
                 if ($tid) {
                     $targetParams['target_contact_id'] = $tid;
                     $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
                     if (is_a($resultTarget, 'CRM_Core_Error')) {
                         $transaction->rollback();
                         return $resultTarget;
                     }
                 }
             }
         } else {
             $targetParams['target_contact_id'] = $params['target_contact_id'];
             if (CRM_Utils_Array::value('id', $params)) {
                 $target = new CRM_Activity_BAO_ActivityTarget();
                 $target->activity_id = $activityId;
                 $target->find(true);
                 if ($target->target_contact_id != $params['target_contact_id']) {
                     $targetParams['id'] = $target->id;
                     $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
                 }
             } else {
                 $resultTarget = CRM_Activity_BAO_ActivityTarget::create($targetParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityTarget', $params, true)) {
             self::deleteActivityTarget($activityId);
         }
     }
     // write to changelog before transation is committed/rolled
     // back (and prepare status to display)
     if (CRM_Utils_Array::value('id', $params)) {
         $logMsg = "Activity (id: {$result->id} ) updated with ";
     } else {
         $logMsg = "Activity created for ";
     }
     $msgs = array();
     if (isset($params['source_contact_id'])) {
         $msgs[] = "source={$params['source_contact_id']}";
     }
     if (CRM_Utils_Array::value('target_contact_id', $params)) {
         if (is_array($params['target_contact_id']) && !CRM_Utils_array::crmIsEmptyArray($params['target_contact_id'])) {
             $msgs[] = "target=" . implode(',', $params['target_contact_id']);
             // take only first target
             // will be used for recently viewed display
             $t = array_slice($params['target_contact_id'], 0, 1);
             $recentContactId = $t[0];
         } else {
             if (isset($params['target_contact_id'])) {
                 $msgs[] = "target={$params['target_contact_id']}";
                 // will be used for recently viewed display
                 $recentContactId = $params['target_contact_id'];
             }
         }
     } else {
         // at worst, take source for recently viewed display
         $recentContactId = $params['source_contact_id'];
     }
     if (isset($params['assignee_contact_id'])) {
         if (is_array($params['assignee_contact_id'])) {
             $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
         } else {
             $msgs[] = "assignee={$params['assignee_contact_id']}";
         }
     }
     $logMsg .= implode(', ', $msgs);
     self::logActivityAction($result, $logMsg);
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
     }
     $transaction->commit();
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         $recentOther = array();
         require_once 'CRM/Utils/Recent.php';
         if (CRM_Utils_Array::value('case_id', $params)) {
             $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
             $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home");
         } else {
             $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home";
             if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
                 $url = CRM_Utils_System::url('civicrm/contact/view/activity', $q);
                 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/activity', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home");
                 require_once 'CRM/Core/Permission.php';
                 if (CRM_Core_Permission::check("delete activities")) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home");
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/activity', $q);
                 if (CRM_Core_Permission::check("delete activities")) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home");
                 }
             }
         }
         if (!isset($activity->parent_id)) {
             require_once 'CRM/Contact/BAO/Contact.php';
             $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
             // add the recently created Activity
             $activityTypes = CRM_Core_Pseudoconstant::activityType(true, true);
             $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
             $title = "";
             if (isset($activitySubject)) {
                 $title = $activitySubject . ' - ';
             }
             $title = $title . $recentContactDisplay . ' (' . $activityTypes[$activity->activity_type_id] . ')';
             CRM_Utils_Recent::add($title, $url, $activity->id, 'Activity', $recentContactId, $recentContactDisplay, $recentOther);
         }
     }
     // reset the group contact cache since smart groups might be affected due to this
     require_once 'CRM/Contact/BAO/GroupContactCache.php';
     CRM_Contact_BAO_GroupContactCache::remove();
     if (CRM_Utils_Array::value('id', $params)) {
         CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
     } else {
         CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
     }
     // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
     $matches = array();
     if (preg_match('/\\[case #([0-9a-h]{7})\\]/', $params['subject'], $matches)) {
         $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
         $hash = $matches[1];
         $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('{$key}', id)), 1, 7) = '{$hash}'";
         $caseParams = array('activity_id' => $activity->id, 'case_id' => CRM_Core_DAO::singleValueQuery($query));
         if ($caseParams['case_id']) {
             require_once 'CRM/Case/BAO/Case.php';
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
         } else {
             self::logActivityAction($activity, "unknown case hash encountered: {$hash}");
         }
     }
     return $result;
 }