dev/core#2790 Move pdf postProcess function to the trait
authorEileen McNaughton <emcnaughton@wikimedia.org>
Tue, 14 Sep 2021 21:32:42 +0000 (09:32 +1200)
committerEileen McNaughton <emcnaughton@wikimedia.org>
Wed, 15 Sep 2021 00:45:48 +0000 (12:45 +1200)
CRM/Case/Form/Task/PDF.php
CRM/Contact/Form/Task/PDF.php
CRM/Contact/Form/Task/PDFLetterCommon.php
CRM/Contact/Form/Task/PDFTrait.php
CRM/Contribute/Form/Task/PDFLetter.php
CRM/Event/Form/Task/PDF.php
CRM/Member/Form/Task/PDFLetter.php

index 65954ea27294883634a9f7e584f0ebfa79ea212c..c8ad1631617798ef0f801bcd096e4997979b9584 100644 (file)
@@ -43,13 +43,6 @@ class CRM_Case_Form_Task_PDF extends CRM_Case_Form_Task {
     $this->setContactIDs();
   }
 
-  /**
-   * Process the form after the input has been submitted and validated.
-   */
-  public function postProcess() {
-    CRM_Contact_Form_Task_PDFLetterCommon::postProcess($this);
-  }
-
   /**
    * List available tokens for this form.
    *
index 03f040bff213bbd1f3347c53b526e4cb1165f5af..9688e912e3e6f573f843b5ebd75ee33fa0f848b5 100644 (file)
@@ -95,13 +95,6 @@ class CRM_Contact_Form_Task_PDF extends CRM_Contact_Form_Task {
     $this->addPDFElementsToForm();
   }
 
-  /**
-   * Process the form after the input has been submitted and validated.
-   */
-  public function postProcess() {
-    CRM_Contact_Form_Task_PDFLetterCommon::postProcess($this);
-  }
-
   /**
    * List available tokens for this form.
    *
index 2c1e432fd7519bd25b3b1f01f29a797df3b1b279..b32aac454ae9531a555c7db7be7c6e7aabd1dc77 100644 (file)
@@ -113,8 +113,11 @@ class CRM_Contact_Form_Task_PDFLetterCommon extends CRM_Core_Form_Task_PDFLetter
    * @throws \CRM_Core_Exception
    * @throws \CiviCRM_API3_Exception
    * @throws \API_Exception
+   *
+   * @deprecated
    */
   public static function postProcess(&$form): void {
+    CRM_Core_Error::deprecatedFunctionWarning('no alternative');
     $formValues = $form->controller->exportValues($form->getName());
     [$formValues, $categories, $html_message, $messageToken, $returnProperties] = self::processMessageTemplate($formValues);
     $html = $activityIds = [];
@@ -207,8 +210,11 @@ class CRM_Contact_Form_Task_PDFLetterCommon extends CRM_Core_Form_Task_PDFLetter
    *   and use-case.
    *
    * @throws CRM_Core_Exception
+   *
+   * @deprecated
    */
   public static function createActivities($form, $html_message, $contactIds, $subject, $campaign_id, $perContactHtml = []) {
+    CRM_Core_Error::deprecatedFunctionWarning('no alternative');
 
     $activityParams = [
       'subject' => $subject,
@@ -278,6 +284,8 @@ class CRM_Contact_Form_Task_PDFLetterCommon extends CRM_Core_Form_Task_PDFLetter
    * @param string $type
    * @return string
    * @throws \CRM_Core_Exception
+   *
+   * @deprecated
    */
   private static function getMimeType($type) {
     $mimeTypes = [
@@ -320,6 +328,8 @@ class CRM_Contact_Form_Task_PDFLetterCommon extends CRM_Core_Form_Task_PDFLetter
    * @return bool
    *   TRUE if the Download Document button was clicked (also defaults to TRUE
    *     if the form controller does not exist), else FALSE
+   *
+   * @deprecated
    */
   protected static function isLiveMode($form) {
     // CRM-21255 - Hrm, CiviCase 4+5 seem to report buttons differently...
index a32b94255ab5cd6a7acfd2f24cc991b28c19715b..189c6fbb89f12dcc8f3afc080a258b12fab3244f 100644 (file)
@@ -238,4 +238,188 @@ trait CRM_Contact_Form_Task_PDFTrait {
     return ($buttonName === '_qf_PDF_upload') || isset($c['values']['PDF']['buttons']['_qf_PDF_upload']);
   }
 
+  /**
+   * Process the form after the input has been submitted and validated.
+   *
+   * @throws \CRM_Core_Exception
+   * @throws \CiviCRM_API3_Exception
+   * @throws \API_Exception
+   */
+  public function postProcess(): void {
+    $form = $this;
+    $formValues = $form->controller->exportValues($form->getName());
+    [$formValues, $categories, $html_message, $messageToken, $returnProperties] = CRM_Contact_Form_Task_PDFLetterCommon::processMessageTemplate($formValues);
+    $html = $activityIds = [];
+
+    // CRM-16725 Skip creation of activities if user is previewing their PDF letter(s)
+    if ($this->isLiveMode()) {
+      $activityIds = $this->createActivities($form, $html_message, $form->_contactIds, $formValues['subject'], CRM_Utils_Array::value('campaign_id', $formValues));
+    }
+
+    if (!empty($formValues['document_file_path'])) {
+      [$html_message, $zip] = CRM_Utils_PDF_Document::unzipDoc($formValues['document_file_path'], $formValues['document_type']);
+    }
+
+    foreach ($form->_contactIds as $item => $contactId) {
+      $caseId = $form->getVar('_caseId');
+      if (empty($caseId) && !empty($form->_caseIds[$item])) {
+        $caseId = $form->_caseIds[$item];
+      }
+
+      $tokenHtml = CRM_Core_BAO_MessageTemplate::renderTemplate([
+        'contactId' => $contactId,
+        'messageTemplate' => ['msg_html' => $html_message],
+        'tokenContext' => $caseId ? ['caseId' => $caseId] : [],
+        'disableSmarty' => (!defined('CIVICRM_MAIL_SMARTY') || !CIVICRM_MAIL_SMARTY),
+      ])['html'];
+
+      $html[] = $tokenHtml;
+    }
+
+    $tee = NULL;
+    if ($this->isLiveMode() && Civi::settings()->get('recordGeneratedLetters') === 'combined-attached') {
+      if (count($activityIds) !== 1) {
+        throw new CRM_Core_Exception("When recordGeneratedLetters=combined-attached, there should only be one activity.");
+      }
+      $tee = CRM_Utils_ConsoleTee::create()->start();
+    }
+
+    $type = $formValues['document_type'];
+    $mimeType = $this->getMimeType($type);
+    // ^^ Useful side-effect: consistently throws error for unrecognized types.
+
+    $fileName = method_exists($form, 'getFileName') ? ($form->getFileName() . '.' . $type) : 'CiviLetter.' . $type;
+
+    if ($type === 'pdf') {
+      CRM_Utils_PDF_Utils::html2pdf($html, $fileName, FALSE, $formValues);
+    }
+    elseif (!empty($formValues['document_file_path'])) {
+      $fileName = pathinfo($formValues['document_file_path'], PATHINFO_FILENAME) . '.' . $type;
+      CRM_Utils_PDF_Document::printDocuments($html, $fileName, $type, $zip);
+    }
+    else {
+      CRM_Utils_PDF_Document::html2doc($html, $fileName, $formValues);
+    }
+
+    if ($tee) {
+      $tee->stop();
+      $content = file_get_contents($tee->getFileName(), NULL, NULL, NULL, 5);
+      if (empty($content)) {
+        throw new \CRM_Core_Exception("Failed to capture document content (type=$type)!");
+      }
+      foreach ($activityIds as $activityId) {
+        civicrm_api3('Attachment', 'create', [
+          'entity_table' => 'civicrm_activity',
+          'entity_id' => $activityId,
+          'name' => $fileName,
+          'mime_type' => $mimeType,
+          'options' => [
+            'move-file' => $tee->getFileName(),
+          ],
+        ]);
+      }
+    }
+
+    $form->postProcessHook();
+
+    CRM_Utils_System::civiExit();
+  }
+
+  /**
+   * Convert from a vague-type/file-extension to mime-type.
+   *
+   * @param string $type
+   * @return string
+   * @throws \CRM_Core_Exception
+   */
+  protected function getMimeType($type) {
+    $mimeTypes = [
+      'pdf' => 'application/pdf',
+      'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+      'odt' => 'application/vnd.oasis.opendocument.text',
+      'html' => 'text/html',
+    ];
+    if (isset($mimeTypes[$type])) {
+      return $mimeTypes[$type];
+    }
+    else {
+      throw new \CRM_Core_Exception("Cannot determine mime type");
+    }
+  }
+
+  /**
+   * @param CRM_Core_Form $form
+   * @param string $html_message
+   * @param array $contactIds
+   * @param string $subject
+   * @param int $campaign_id
+   * @param array $perContactHtml
+   *
+   * @return array
+   *   List of activity IDs.
+   *   There may be 1 or more, depending on the system-settings
+   *   and use-case.
+   *
+   * @throws CRM_Core_Exception
+   */
+  public function createActivities($form, $html_message, $contactIds, $subject, $campaign_id, $perContactHtml = []) {
+
+    $activityParams = [
+      'subject' => $subject,
+      'campaign_id' => $campaign_id,
+      'source_contact_id' => CRM_Core_Session::getLoggedInContactID(),
+      'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Print PDF Letter'),
+      'activity_date_time' => date('YmdHis'),
+      'details' => $html_message,
+    ];
+    if (!empty($form->_activityId)) {
+      $activityParams += ['id' => $form->_activityId];
+    }
+
+    $activityIds = [];
+    switch (Civi::settings()->get('recordGeneratedLetters')) {
+      case 'none':
+        return [];
+
+      case 'multiple':
+        // One activity per contact.
+        foreach ($contactIds as $i => $contactId) {
+          $fullParams = ['target_contact_id' => $contactId] + $activityParams;
+          if (!empty($form->_caseId)) {
+            $fullParams['case_id'] = $form->_caseId;
+          }
+          elseif (!empty($form->_caseIds[$i])) {
+            $fullParams['case_id'] = $form->_caseIds[$i];
+          }
+
+          if (isset($perContactHtml[$contactId])) {
+            $fullParams['details'] = implode('<hr>', $perContactHtml[$contactId]);
+          }
+          $activity = civicrm_api3('Activity', 'create', $fullParams);
+          $activityIds[$contactId] = $activity['id'];
+        }
+
+        break;
+
+      case 'combined':
+      case 'combined-attached':
+        // One activity with all contacts.
+        $fullParams = ['target_contact_id' => $contactIds] + $activityParams;
+        if (!empty($form->_caseId)) {
+          $fullParams['case_id'] = $form->_caseId;
+        }
+        elseif (!empty($form->_caseIds)) {
+          $fullParams['case_id'] = $form->_caseIds;
+        }
+        $activity = civicrm_api3('Activity', 'create', $fullParams);
+        $activityIds[] = $activity['id'];
+        break;
+
+      default:
+        throw new CRM_Core_Exception("Unrecognized option in recordGeneratedLetters: " . Civi::settings()->get('recordGeneratedLetters'));
+    }
+
+    return $activityIds;
+  }
+
 }
index 5d5785ce07aab81d52f434fbf940b718cbe288f3..8fc6c1a2e10daca866b8bd2f48bc38b1ee873d3e 100644 (file)
@@ -232,7 +232,7 @@ class CRM_Contribute_Form_Task_PDFLetter extends CRM_Contribute_Form_Task {
     }
 
     $contactIds = array_keys($contacts);
-    CRM_Contact_Form_Task_PDFLetterCommon::createActivities($this, $html_message, $contactIds, CRM_Utils_Array::value('subject', $formValues, ts('Thank you letter')), CRM_Utils_Array::value('campaign_id', $formValues), $contactHtml);
+    $this->createActivities($this, $html_message, $contactIds, CRM_Utils_Array::value('subject', $formValues, ts('Thank you letter')), CRM_Utils_Array::value('campaign_id', $formValues), $contactHtml);
     $html = array_diff_key($html, $emailedHtml);
 
     //CRM-19761
index 9ce1baed9c71cdfb82a34ebc1a8eaa1b1231c12c..778a195f2bab25cb68f6d8974a9bb8bcb6c4d7a3 100644 (file)
@@ -55,13 +55,6 @@ class CRM_Event_Form_Task_PDF extends CRM_Event_Form_Task {
     $this->assign('single', $this->_single);
   }
 
-  /**
-   * Process the form after the input has been submitted and validated.
-   */
-  public function postProcess() {
-    CRM_Contact_Form_Task_PDFLetterCommon::postProcess($this);
-  }
-
   /**
    * List available tokens for this form.
    *
index b435ebd3f715a635fc9a2b511d7b01d74f34bf71..71cd6d646e501aa1c6212626d2eb4cb9fcc80a40 100644 (file)
@@ -97,7 +97,7 @@ class CRM_Member_Form_Task_PDFLetter extends CRM_Member_Form_Task {
       $messageToken,
       $html_message
     );
-    CRM_Contact_Form_Task_PDFLetterCommon::createActivities($form, $html_message, $contactIDs, $formValues['subject'], CRM_Utils_Array::value('campaign_id', $formValues));
+    $form->createActivities($form, $html_message, $contactIDs, $formValues['subject'], CRM_Utils_Array::value('campaign_id', $formValues));
     CRM_Utils_PDF_Utils::html2pdf($html, $this->getFileName() . '.pdf', FALSE, $formValues);
 
     $form->postProcessHook();