You are here

public function EmailMerge::flush in Forena Reports 8

Write the output to disk.

Return value

mixed

Overrides DocumentBase::flush

File

src/FrxPlugin/Document/EmailMerge.php, line 31

Class

EmailMerge
Provides MS Excel Exports

Namespace

Drupal\forena\FrxPlugin\Document

Code

public function flush() {
  $content = [];
  $body = $this->write_buffer;
  $doc = new \DOMDocument('1.0', 'UTF-8');
  $doc->strictErrorChecking = FALSE;
  libxml_use_internal_errors(true);
  $doc
    ->loadHTML($body);
  libxml_clear_errors();
  $xml = simplexml_import_dom($doc);
  if (!$xml) {
    return $content;
  }
  $docs = $xml
    ->xpath('.//*[@class="email-document"]');
  $this->prompt_subject = TRUE;
  $this->prompt_body = TRUE;

  /** @var \SimpleXMLElement $doc */
  if ($docs) {
    foreach ($docs as $doc) {

      // From
      $from = $doc
        ->xpath('.//*[@class="email-header-from"]');
      $from = $from ? html_entity_decode(strip_tags($from[0])) : '';

      // Subject
      $subject = $doc
        ->xpath('.//*[@class="email-header-subject"]');
      if ($subject) {
        $this->prompt_subject = FALSE;
      }
      $subject = $subject ? (string) $subject[0] : '';

      // To
      $to = $doc
        ->xpath('.//*[@class="email-header-to"]');
      $to = $to ? html_entity_decode(strip_tags($to[0]
        ->asXML())) : '';
      if ($to) {
        $this->prompt_to = FALSE;
      }
      $body = $doc
        ->xpath('.//*[@class="email-body"]');
      if ($body) {
        $this->prompt_body = FALSE;
      }
      $body = $body ? $body[0]
        ->asXML() : $body;

      // Assemble email
      $email = array(
        'to' => $to,
        'from' => $from,
        'parms' => array(
          'subject' => $subject,
          'body' => $body,
        ),
      );

      // Check for cc
      $cc = $doc
        ->xpath('.//*[@class="email-header-cc"]');
      if ($cc) {
        $email['parms']['headers']['Cc'] = html_entity_decode(strip_tags($cc[0]
          ->asXML()));
      }

      // Check for bcc
      $bcc = $doc
        ->xpath('.//*[@class="email-header-bcc"]');
      if ($bcc) {
        $email['parms']['headers']['Bcc'] = html_entity_decode(strip_tags($bcc[0]
          ->asXML()));
      }
      $this->emails[] = $email;
    }
  }
  $count = count($docs);
  $this->count = $count;
  if ($count) {
    $content['email_form'] = \Drupal::formBuilder()
      ->getForm(EmailMergeForm::class);
  }
  else {
    $this
      ->app()
      ->error(t('No mail merge information in report. Displaying report instead.'));
    $output = $body;
    $content = array(
      'content' => array(
        '#markup' => $output,
      ),
    );
  }
  return $content;
}