From f94186a20fb604e639aea7c9790db19a93bfa56b Mon Sep 17 00:00:00 2001 From: Markus Birth Date: Sun, 10 Jul 2016 23:01:21 +0200 Subject: [PATCH] Reduce complexity in MailOutput. --- lib/Frs/Output/MailOutput.php | 68 ++++++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 16 deletions(-) diff --git a/lib/Frs/Output/MailOutput.php b/lib/Frs/Output/MailOutput.php index 691da8f..b5fa3ae 100644 --- a/lib/Frs/Output/MailOutput.php +++ b/lib/Frs/Output/MailOutput.php @@ -7,6 +7,7 @@ use \Frs\Output\GenericOutput; class MailOutput extends GenericOutput { private $recipients = array(); + private $headers = array(); private $subject = ''; /** @@ -36,6 +37,55 @@ class MailOutput extends GenericOutput $this->subject = $newSubject; } + /** + * Sets the given header $key to $value. A Subject: header sets + * the subject via $this->setSubject(). A To: header is ignored. + * + * @param string $key Header name + * @param string $value Header contents + */ + public function setHeader($key, $value) + { + if (strtolower($key) == 'subject') { + $this->setSubject($value); + return; + } + if (strtolower($key) == 'to') { + // ignore for now (maybe set as recipient?) + return; + } + $this->headers[$key] = $value; + } + + /** + * Returns a header section (as string) of all currently set headers. + * + * @return string Header section. + */ + public function getHeaders() + { + $all_headers = ''; + foreach ($this->headers as $key=>$value) { + $all_headers .= $key . ': ' . $value . "\r\n"; + } + return $all_headers; + } + + /** + * Sets mail headers. If headers contain a Subject: line, the subject is set from that. + * + * @param string $headers All mail headers separated by newlines (CRLF or LF). + */ + public function setHeadersFromString($headers) + { + $header_lines = preg_split('/\r?\n/', $headers); + + foreach ($header_lines as $header_line) { + list($key, $value) = preg_split('/: /', $header_line, 2); + $this->setHeader($key, $value); + } + } + /** * Sends the prepared mail * @@ -45,24 +95,10 @@ class MailOutput extends GenericOutput { $mail_html = $this->getRenderedOutput(); // contains headers + body list($headers, $mailbody) = preg_split('/\r?\n\r?\n/', $mail_html, 2); - - $header_lines = preg_split('/\r?\n/', $headers); - $header_filtered = ''; - - foreach ($header_lines as $header_line) { - list($key, $value) = preg_split('/: /', $header_line, 2); - if (in_array(strtolower($key), array('subject', 'to'))) { - // Skip Subject and To headers as they're added by PHP - if (strtolower($key) == 'subject') { - $this->setSubject($value); - } - continue; - } - $header_filtered .= $header_line . "\r\n"; - } + $this->setHeadersFromString($headers); $recipients = implode(', ', $this->recipients); // TODO: Check if any recipients in the first place - $mail_sent = mail($recipients, $this->subject, $mailbody, $header_filtered); + $mail_sent = mail($recipients, $this->subject, $mailbody, $this->getHeaders()); return $mail_sent; } }