Merge pull request #18286 from sunilpawar/ui_30
[civicrm-core.git] / CRM / Contact / Form / Task / EmailTrait.php
index 97b4347027224aab94e0c12cee6c716f122fdc23..fb5e6ff51289720245aaca6104a66901b6528473 100644 (file)
@@ -206,44 +206,33 @@ trait CRM_Contact_Form_Task_EmailTrait {
 
     // check if we need to setdefaults and check for valid contact emails / communication preferences
     if (is_array($this->_allContactIds) && $setDefaults) {
-      $returnProperties = [
-        'sort_name' => 1,
-        'email' => 1,
-        'do_not_email' => 1,
-        'is_deceased' => 1,
-        'on_hold' => 1,
-        'display_name' => 1,
-        'preferred_mail_format' => 1,
-      ];
-
       // get the details for all selected contacts ( to, cc and bcc contacts )
-      list($this->_allContactDetails) = CRM_Utils_Token::getTokenDetails($this->_allContactIds,
-        $returnProperties,
-        FALSE,
-        FALSE
-      );
+      $allContactDetails = civicrm_api3('Contact', 'get', [
+        'id' => ['IN' => $this->_allContactIds],
+        'return' => ['sort_name', 'email', 'do_not_email', 'is_deceased', 'on_hold', 'display_name', 'preferred_mail_format'],
+        'options' => ['limit' => 0],
+      ])['values'];
+
+      // The contact task supports passing in email_id in a url. It supports a single email
+      // and is marked as having been related to CiviHR.
+      // The array will look like $this->_toEmail = ['email' => 'x', 'contact_id' => 2])
+      // If it exists we want to use the specified email which might be different to the primary email
+      // that we have.
+      if (!empty($this->_toEmail['contact_id']) && !empty($allContactDetails[$this->_toEmail['contact_id']])) {
+        $allContactDetails[$this->_toEmail['contact_id']]['email'] = $this->_toEmail['email'];
+      }
 
       // perform all validations on unique contact Ids
-      foreach (array_unique($this->_allContactIds) as $key => $contactId) {
-        $value = $this->_allContactDetails[$contactId];
+      foreach ($allContactDetails as $contactId => $value) {
         if ($value['do_not_email'] || empty($value['email']) || !empty($value['is_deceased']) || $value['on_hold']) {
           $this->setSuppressedEmail($contactId, $value);
         }
-        else {
-          $email = $value['email'];
-
-          // build array's which are used to setdefaults
-          if (in_array($contactId, $this->_toContactIds)) {
-            $this->_toContactDetails[$contactId] = $this->_contactDetails[$contactId] = $this->_allContactDetails[$contactId];
-            // If a particular address has been specified as the default, use that instead of contact's primary email
-            if (!empty($this->_toEmail) && $this->_toEmail['contact_id'] == $contactId) {
-              $email = $this->_toEmail['email'];
-            }
-            $toArray[] = [
-              'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
-              'id' => "$contactId::{$email}",
-            ];
-          }
+        elseif (in_array($contactId, $this->_toContactIds)) {
+          $this->_toContactDetails[$contactId] = $this->_contactDetails[$contactId] = $value;
+          $toArray[] = [
+            'text' => '"' . $value['sort_name'] . '" <' . $value['email'] . '>',
+            'id' => "$contactId::{$value['email']}",
+          ];
         }
       }
 
@@ -397,7 +386,6 @@ trait CRM_Contact_Form_Task_EmailTrait {
     // If we have had a contact email used here the value returned from the line above will be the
     // numerical key where as $from for use in the sendEmail in Activity needs to be of format of "To Name" <toemailaddress>
     $from = CRM_Utils_Mail::formatFromAddress($from);
-    $subject = $formValues['subject'];
 
     $ccArray = $formValues['cc_id'] ? explode(',', $formValues['cc_id']) : [];
     $cc = $this->getEmailString($ccArray);
@@ -407,12 +395,6 @@ trait CRM_Contact_Form_Task_EmailTrait {
     $bcc = $this->getEmailString($bccArray);
     $additionalDetails .= empty($bccArray) ? '' : "\nbcc : " . $this->getEmailUrlString($bccArray);
 
-    // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
-    if (isset($this->_caseId) && is_numeric($this->_caseId)) {
-      $hash = substr(sha1(CIVICRM_SITE_KEY . $this->_caseId), 0, 7);
-      $subject = "[case #$hash] $subject";
-    }
-
     // format contact details array to handle multiple emails from same contact
     $formattedContactDetails = [];
     foreach ($this->_contactIds as $key => $contactId) {
@@ -430,15 +412,10 @@ trait CRM_Contact_Form_Task_EmailTrait {
       $formattedContactDetails["{$contactId}::{$email}"] = $details;
     }
 
-    $contributionIds = [];
-    if ($this->getVar('_contributionIds')) {
-      $contributionIds = $this->getVar('_contributionIds');
-    }
-
     // send the mail
     list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail(
       $formattedContactDetails,
-      $subject,
+      $this->getSubject($formValues['subject']),
       $formValues['text_message'],
       $formValues['html_message'],
       NULL,
@@ -449,40 +426,13 @@ trait CRM_Contact_Form_Task_EmailTrait {
       $bcc,
       array_keys($this->_toContactDetails),
       $additionalDetails,
-      $contributionIds,
+      $this->getVar('_contributionIds') ?? [],
       CRM_Utils_Array::value('campaign_id', $formValues),
       $this->getVar('_caseId')
     );
 
-    $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['target_contact_id'] = $this->_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 = [];
-            $assignee = [$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).');
-            }
-          }
-        }
-      }
-
+      $followupStatus = $this->createFollowUpActivities($formValues, $activityId);
       $count_success = count($this->_toContactDetails);
       CRM_Core_Session::setStatus(ts('One message was sent successfully. ', [
         'plural' => '%count messages were sent successfully. ',
@@ -643,4 +593,64 @@ trait CRM_Contact_Form_Task_EmailTrait {
     return $attachments;
   }
 
+  /**
+   * Get the subject for the message.
+   *
+   * The case handling should possibly be on the case form.....
+   *
+   * @param string $subject
+   *
+   * @return string
+   */
+  protected function getSubject(string $subject):string {
+    // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
+    if (isset($this->_caseId) && is_numeric($this->_caseId)) {
+      $hash = substr(sha1(CIVICRM_SITE_KEY . $this->_caseId), 0, 7);
+      $subject = "[case #$hash] $subject";
+    }
+    return $subject;
+  }
+
+  /**
+   * Create any follow up activities.
+   *
+   * @param array $formValues
+   * @param int $activityId
+   *
+   * @return string
+   *
+   * @throws \CRM_Core_Exception
+   */
+  protected function createFollowUpActivities($formValues, $activityId): string {
+    $params = [];
+    $followupStatus = '';
+    $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['target_contact_id'] = $this->_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 = [];
+          $assignee = [$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).');
+          }
+        }
+      }
+    }
+    return $followupStatus;
+  }
+
 }