1<?php
2
3namespace splitbrain\dokuwiki\plugin\smtp;
4
5/**
6 * Class Message
7 *
8 * Overrides the Message class with what we need to reuse the SMTP mailer without using
9 * their message composer
10 *
11 * @package splitbrain\dokuwiki\plugin\smtp
12 */
13class Message extends \Tx\Mailer\Message {
14
15    protected $from;
16    protected $rcpt;
17    protected $body;
18
19    /**
20     * @param string $from Sender Address
21     * @param string $rcpt all recipients (TO, CC, BCC)
22     * @param string $body the full message body including headers
23     */
24    public function __construct($from, $rcpt, $body) {
25        $this->from = $from;
26        $this->rcpt = $rcpt;
27        $this->body = $body;
28    }
29
30    /**
31     * Return the mail only part of the from address
32     *
33     * @return string
34     */
35    public function getFromEmail() {
36        if(preg_match('#(.*?)<(.*?)>#', $this->from, $matches)) {
37            return $matches[2];
38        }
39
40        return $this->from;
41    }
42
43    /**
44     * Get a list of all recipients (mail only part)
45     *
46     * @return array
47     */
48    public function getTo() {
49        $rcpt = array();
50
51        // We need the mail only part of all recipients
52        $addresses = explode(',', $this->rcpt);
53        foreach($addresses as $addr) {
54            // parse address
55            if(preg_match('#(.*?)<(.*?)>#', $addr, $matches)) {
56                $rcpt[] = trim($matches[2]);
57            } else {
58                $rcpt[] = trim($addr);
59            }
60        }
61
62        $rcpt = array_filter($rcpt);
63        $rcpt = array_unique($rcpt);
64        return $rcpt;
65    }
66
67    /**
68     * Return the whole message body ready to be send by DATA
69     *
70     * Includes end of data signature and strips the BCC header
71     *
72     * @return string
73     */
74    public function toString() {
75        // we need to remove the BCC header here
76        $lines = preg_split('/\r?\n/', $this->body);
77        $count = count($lines);
78        for($i=0; $i<$count; $i++) {
79            if(trim($lines[$i]) === '') break; // end of headers, we're done
80            if(substr($lines[$i],0, 4) == 'Bcc:') {
81                unset($lines[$i]); // we found the Bcc: header and remove it
82                while(substr($lines[++$i],0, 1) === ' ') {
83                    unset($lines[$i]); // indented lines are header continuation
84                }
85                break; // header removed, we're done
86            }
87        }
88        $body = join($this->CRLF, $lines);
89
90        return $body . $this->CRLF . $this->CRLF . "." . $this->CRLF;
91    }
92
93}
94