xref: /dokuwiki/inc/Mailer.class.php (revision c959e5ab963ba051e2d168d1c866a0659c90ed54)
1bb01c27cSAndreas Gohr<?php
2d4f83172SAndreas Gohr
3bb01c27cSAndreas Gohr/**
41d045709SAndreas Gohr * A class to build and send multi part mails (with HTML content and embedded
51d045709SAndreas Gohr * attachments). All mails are assumed to be in UTF-8 encoding.
61d045709SAndreas Gohr *
71d045709SAndreas Gohr * Attachments are handled in memory so this shouldn't be used to send huge
81d045709SAndreas Gohr * files, but then again mail shouldn't be used to send huge files either.
91d045709SAndreas Gohr *
10bb01c27cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11bb01c27cSAndreas Gohr */
12d4f83172SAndreas Gohr
13*c959e5abSsplitbrainuse dokuwiki\Input\Input;
1473dc0a89SAndreas Gohruse dokuwiki\MailUtils;
1524870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1624870174SAndreas Gohruse dokuwiki\Utf8\Clean;
17e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
18e1d9dcc8SAndreas Gohr
19a89c75afSAndreas Gohr/**
20a89c75afSAndreas Gohr * Mail Handling
21a89c75afSAndreas Gohr */
228c7c53b0SAndreas Gohrclass Mailer
238c7c53b0SAndreas Gohr{
2424870174SAndreas Gohr    protected $headers   = [];
2524870174SAndreas Gohr    protected $attach    = [];
26f41c79d7SAndreas Gohr    protected $html      = '';
27f41c79d7SAndreas Gohr    protected $text      = '';
28bb01c27cSAndreas Gohr
29f41c79d7SAndreas Gohr    protected $boundary  = '';
30f41c79d7SAndreas Gohr    protected $partid    = '';
3124870174SAndreas Gohr    protected $sendparam;
32bb01c27cSAndreas Gohr
33f41c79d7SAndreas Gohr    protected $allowhtml = true;
341d045709SAndreas Gohr
3524870174SAndreas Gohr    protected $replacements = ['text' => [], 'html' => []];
369ea45836SChristopher Smith
371d045709SAndreas Gohr    /**
381d045709SAndreas Gohr     * Constructor
391d045709SAndreas Gohr     *
409ea45836SChristopher Smith     * Initializes the boundary strings, part counters and token replacements
411d045709SAndreas Gohr     */
42d868eb89SAndreas Gohr    public function __construct()
43d868eb89SAndreas Gohr    {
449f3eca0bSAndreas Gohr        global $conf;
45585bf44eSChristopher Smith        /* @var Input $INPUT */
46585bf44eSChristopher Smith        global $INPUT;
479f3eca0bSAndreas Gohr
489f3eca0bSAndreas Gohr        $server = parse_url(DOKU_URL, PHP_URL_HOST);
49093fe67eSAndreas Gohr        if (!str_contains($server, '.')) $server .= '.localhost';
501d045709SAndreas Gohr
5124870174SAndreas Gohr        $this->partid   = substr(md5(uniqid(random_int(0, mt_getrandmax()), true)), 0, 8) . '@' . $server;
5224870174SAndreas Gohr        $this->boundary = '__________' . md5(uniqid(random_int(0, mt_getrandmax()), true));
539f3eca0bSAndreas Gohr
54749c0023SAndreas Gohr        $listid = implode('.', array_reverse(explode('/', DOKU_BASE))) . $server;
559f3eca0bSAndreas Gohr        $listid = strtolower(trim($listid, '.'));
5624870174SAndreas Gohr
5724870174SAndreas Gohr        $messageid = uniqid(random_int(0, mt_getrandmax()), true) . "@$server";
589f3eca0bSAndreas Gohr
592398a2b5SAndreas Gohr        $this->allowhtml = (bool)$conf['htmlmail'];
602398a2b5SAndreas Gohr
619f3eca0bSAndreas Gohr        // add some default headers for mailfiltering FS#2247
625f43dcf4SLukas Rademacher        if (!empty($conf['mailreturnpath'])) {
635f43dcf4SLukas Rademacher            $this->setHeader('Return-Path', $conf['mailreturnpath']);
645f43dcf4SLukas Rademacher        }
656a1f928fSAndreas Gohr        $this->setHeader('X-Mailer', 'DokuWiki');
66585bf44eSChristopher Smith        $this->setHeader('X-DokuWiki-User', $INPUT->server->str('REMOTE_USER'));
679f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Title', $conf['title']);
689f3eca0bSAndreas Gohr        $this->setHeader('X-DokuWiki-Server', $server);
699f3eca0bSAndreas Gohr        $this->setHeader('X-Auto-Response-Suppress', 'OOF');
709f3eca0bSAndreas Gohr        $this->setHeader('List-Id', $conf['title'] . ' <' . $listid . '>');
71d6e04b60SAndreas Gohr        $this->setHeader('Date', date('r'), false);
727c7659d2SPhilipp Specht        $this->setHeader('Message-Id', "<$messageid>");
739ea45836SChristopher Smith
749ea45836SChristopher Smith        $this->prepareTokenReplacements();
75bb01c27cSAndreas Gohr    }
76bb01c27cSAndreas Gohr
77bb01c27cSAndreas Gohr    /**
7873dc0a89SAndreas Gohr     * Resolve the @MAIL@/@USER@/@NAME@ placeholders in $conf['mailfrom'] and derive $conf['mailfromnobody'].
7973dc0a89SAndreas Gohr     *
8073dc0a89SAndreas Gohr     * Called once during init. The "nobody" variant is the address used when the resolved mailfrom would be
8173dc0a89SAndreas Gohr     * user-dependent (e.g. for subscriptions which must look like they come from a generic sender, not the actor).
8273dc0a89SAndreas Gohr     *
8373dc0a89SAndreas Gohr     * @todo Resolve lazily on first Mailer instantiation instead of eagerly at init time, so the explicit init.php
8473dc0a89SAndreas Gohr     *       call can go away and this method makes more sense here
8573dc0a89SAndreas Gohr     *
8673dc0a89SAndreas Gohr     *
8773dc0a89SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
8873dc0a89SAndreas Gohr     */
8973dc0a89SAndreas Gohr    public static function configInit(): void
9073dc0a89SAndreas Gohr    {
9173dc0a89SAndreas Gohr        global $conf;
9273dc0a89SAndreas Gohr        global $USERINFO;
93*c959e5abSsplitbrain        /** @var Input $INPUT */
9473dc0a89SAndreas Gohr        global $INPUT;
9573dc0a89SAndreas Gohr
9673dc0a89SAndreas Gohr        // auto constructed address
9773dc0a89SAndreas Gohr        $host = @parse_url(DOKU_URL, PHP_URL_HOST);
9873dc0a89SAndreas Gohr        if (!$host) $host = 'example.com';
9973dc0a89SAndreas Gohr        $noreply = 'noreply@' . $host;
10073dc0a89SAndreas Gohr
10173dc0a89SAndreas Gohr        $replace = [];
10273dc0a89SAndreas Gohr        if (!empty($USERINFO['mail'])) {
10373dc0a89SAndreas Gohr            $replace['@MAIL@'] = $USERINFO['mail'];
10473dc0a89SAndreas Gohr        } else {
10573dc0a89SAndreas Gohr            $replace['@MAIL@'] = $noreply;
10673dc0a89SAndreas Gohr        }
10773dc0a89SAndreas Gohr
10873dc0a89SAndreas Gohr        // use 'noreply' if no user
10973dc0a89SAndreas Gohr        $replace['@USER@'] = $INPUT->server->str('REMOTE_USER', 'noreply', true);
11073dc0a89SAndreas Gohr
11173dc0a89SAndreas Gohr        if (!empty($USERINFO['name'])) {
11273dc0a89SAndreas Gohr            $replace['@NAME@'] = $USERINFO['name'];
11373dc0a89SAndreas Gohr        } else {
11473dc0a89SAndreas Gohr            $replace['@NAME@'] = '';
11573dc0a89SAndreas Gohr        }
11673dc0a89SAndreas Gohr
11773dc0a89SAndreas Gohr        // apply replacements
11873dc0a89SAndreas Gohr        $from = str_replace(
11973dc0a89SAndreas Gohr            array_keys($replace),
12073dc0a89SAndreas Gohr            array_values($replace),
12173dc0a89SAndreas Gohr            $conf['mailfrom']
12273dc0a89SAndreas Gohr        );
12373dc0a89SAndreas Gohr
12473dc0a89SAndreas Gohr        // any replacements done? set different mailfromnone
12573dc0a89SAndreas Gohr        if ($from != $conf['mailfrom']) {
12673dc0a89SAndreas Gohr            $conf['mailfromnobody'] = $noreply;
12773dc0a89SAndreas Gohr        } else {
12873dc0a89SAndreas Gohr            $conf['mailfromnobody'] = $from;
12973dc0a89SAndreas Gohr        }
13073dc0a89SAndreas Gohr        $conf['mailfrom'] = $from;
13173dc0a89SAndreas Gohr    }
13273dc0a89SAndreas Gohr
13373dc0a89SAndreas Gohr    /**
134bb01c27cSAndreas Gohr     * Attach a file
135bb01c27cSAndreas Gohr     *
136a89c75afSAndreas Gohr     * @param string $path  Path to the file to attach
137a89c75afSAndreas Gohr     * @param string $mime  Mimetype of the attached file
138a89c75afSAndreas Gohr     * @param string $name The filename to use
139a89c75afSAndreas Gohr     * @param string $embed Unique key to reference this file from the HTML part
140bb01c27cSAndreas Gohr     */
141d868eb89SAndreas Gohr    public function attachFile($path, $mime, $name = '', $embed = '')
142d868eb89SAndreas Gohr    {
143bb01c27cSAndreas Gohr        if (!$name) {
14424870174SAndreas Gohr            $name = PhpString::basename($path);
145bb01c27cSAndreas Gohr        }
146bb01c27cSAndreas Gohr
14724870174SAndreas Gohr        $this->attach[] = [
148bb01c27cSAndreas Gohr            'data'  => file_get_contents($path),
149bb01c27cSAndreas Gohr            'mime'  => $mime,
150bb01c27cSAndreas Gohr            'name'  => $name,
151bb01c27cSAndreas Gohr            'embed' => $embed
15224870174SAndreas Gohr        ];
153bb01c27cSAndreas Gohr    }
154bb01c27cSAndreas Gohr
155bb01c27cSAndreas Gohr    /**
156bb01c27cSAndreas Gohr     * Attach a file
157bb01c27cSAndreas Gohr     *
158a89c75afSAndreas Gohr     * @param string $data  The file contents to attach
159a89c75afSAndreas Gohr     * @param string $mime  Mimetype of the attached file
160a89c75afSAndreas Gohr     * @param string $name  The filename to use
161a89c75afSAndreas Gohr     * @param string $embed Unique key to reference this file from the HTML part
162bb01c27cSAndreas Gohr     */
163d868eb89SAndreas Gohr    public function attachContent($data, $mime, $name = '', $embed = '')
164d868eb89SAndreas Gohr    {
165bb01c27cSAndreas Gohr        if (!$name) {
16624870174SAndreas Gohr            [, $ext] = explode('/', $mime);
167bb01c27cSAndreas Gohr            $name = count($this->attach) . ".$ext";
168bb01c27cSAndreas Gohr        }
169bb01c27cSAndreas Gohr
17024870174SAndreas Gohr        $this->attach[] = [
171bb01c27cSAndreas Gohr            'data'  => $data,
172bb01c27cSAndreas Gohr            'mime'  => $mime,
173bb01c27cSAndreas Gohr            'name'  => $name,
174bb01c27cSAndreas Gohr            'embed' => $embed
17524870174SAndreas Gohr        ];
176bb01c27cSAndreas Gohr    }
177bb01c27cSAndreas Gohr
178bb01c27cSAndreas Gohr    /**
179850dbf1fSAndreas Gohr     * Callback function to automatically embed images referenced in HTML templates
18042ea7f44SGerrit Uitslag     *
18142ea7f44SGerrit Uitslag     * @param array $matches
18242ea7f44SGerrit Uitslag     * @return string placeholder
183850dbf1fSAndreas Gohr     */
184d868eb89SAndreas Gohr    protected function autoEmbedCallBack($matches)
185d868eb89SAndreas Gohr    {
186850dbf1fSAndreas Gohr        static $embeds = 0;
187850dbf1fSAndreas Gohr        $embeds++;
188850dbf1fSAndreas Gohr
189850dbf1fSAndreas Gohr        // get file and mime type
190850dbf1fSAndreas Gohr        $media = cleanID($matches[1]);
19124870174SAndreas Gohr        [, $mime] = mimetype($media);
192850dbf1fSAndreas Gohr        $file = mediaFN($media);
193850dbf1fSAndreas Gohr        if (!file_exists($file)) return $matches[0]; //bad reference, keep as is
194850dbf1fSAndreas Gohr
195850dbf1fSAndreas Gohr        // attach it and set placeholder
196850dbf1fSAndreas Gohr        $this->attachFile($file, $mime, '', 'autoembed' . $embeds);
197850dbf1fSAndreas Gohr        return '%%autoembed' . $embeds . '%%';
198850dbf1fSAndreas Gohr    }
199850dbf1fSAndreas Gohr
200850dbf1fSAndreas Gohr    /**
2011d045709SAndreas Gohr     * Add an arbitrary header to the mail
2021d045709SAndreas Gohr     *
203a36fc348SAndreas Gohr     * If an empy value is passed, the header is removed
204a36fc348SAndreas Gohr     *
2051d045709SAndreas Gohr     * @param string $header the header name (no trailing colon!)
20659bc3b48SGerrit Uitslag     * @param string|string[] $value  the value of the header
2071d045709SAndreas Gohr     * @param bool   $clean  remove all non-ASCII chars and line feeds?
2081d045709SAndreas Gohr     */
209d868eb89SAndreas Gohr    public function setHeader($header, $value, $clean = true)
210d868eb89SAndreas Gohr    {
2119f3eca0bSAndreas Gohr        $header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
2121d045709SAndreas Gohr        if ($clean) {
213578b2c23SAndreas Gohr            $header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
214578b2c23SAndreas Gohr            $value  = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
2151d045709SAndreas Gohr        }
216a36fc348SAndreas Gohr
217a36fc348SAndreas Gohr        // empty value deletes
218b6c97c70SAndreas Gohr        if (is_array($value)) {
219093fe67eSAndreas Gohr            $value = array_map(trim(...), $value);
220b6c97c70SAndreas Gohr            $value = array_filter($value);
221b6c97c70SAndreas Gohr            if (!$value) $value = '';
222b6c97c70SAndreas Gohr        } else {
223a36fc348SAndreas Gohr            $value = trim($value);
224b6c97c70SAndreas Gohr        }
225a36fc348SAndreas Gohr        if ($value === '') {
226a36fc348SAndreas Gohr            if (isset($this->headers[$header])) unset($this->headers[$header]);
227a36fc348SAndreas Gohr        } else {
2281d045709SAndreas Gohr            $this->headers[$header] = $value;
2291d045709SAndreas Gohr        }
230a36fc348SAndreas Gohr    }
2311d045709SAndreas Gohr
2321d045709SAndreas Gohr    /**
2331d045709SAndreas Gohr     * Set additional parameters to be passed to sendmail
2341d045709SAndreas Gohr     *
2351d045709SAndreas Gohr     * Whatever is set here is directly passed to PHP's mail() command as last
2361d045709SAndreas Gohr     * parameter. Depending on the PHP setup this might break mailing alltogether
23742ea7f44SGerrit Uitslag     *
23842ea7f44SGerrit Uitslag     * @param string $param
2391d045709SAndreas Gohr     */
240d868eb89SAndreas Gohr    public function setParameters($param)
241d868eb89SAndreas Gohr    {
2421d045709SAndreas Gohr        $this->sendparam = $param;
2431d045709SAndreas Gohr    }
2441d045709SAndreas Gohr
2451d045709SAndreas Gohr    /**
246abbf0890SAndreas Gohr     * Set the text and HTML body and apply replacements
247abbf0890SAndreas Gohr     *
248abbf0890SAndreas Gohr     * This function applies a whole bunch of default replacements in addition
24904dcb5b2SChristopher Smith     * to the ones specified as parameters
250abbf0890SAndreas Gohr     *
251abbf0890SAndreas Gohr     * If you pass the HTML part or HTML replacements yourself you have to make
252abbf0890SAndreas Gohr     * sure you encode all HTML special chars correctly
253abbf0890SAndreas Gohr     *
254abbf0890SAndreas Gohr     * @param string $text     plain text body
255abbf0890SAndreas Gohr     * @param array  $textrep  replacements to apply on the text part
25664159a61SAndreas Gohr     * @param array  $htmlrep  replacements to apply on the HTML part, null to use $textrep (urls wrapped in <a> tags)
25759bc3b48SGerrit Uitslag     * @param string $html     the HTML body, leave null to create it from $text
258f08086ecSAndreas Gohr     * @param bool   $wrap     wrap the HTML in the default header/Footer
259abbf0890SAndreas Gohr     */
260d868eb89SAndreas Gohr    public function setBody($text, $textrep = null, $htmlrep = null, $html = null, $wrap = true)
261d868eb89SAndreas Gohr    {
262585bf44eSChristopher Smith
26376efd6d0SAndreas Gohr        $htmlrep = (array)$htmlrep;
26476efd6d0SAndreas Gohr        $textrep = (array)$textrep;
265abbf0890SAndreas Gohr
266abbf0890SAndreas Gohr        // create HTML from text if not given
267749c0023SAndreas Gohr        if ($html === null) {
268ba9c057bSAndreas Gohr            $html = $text;
269ba9c057bSAndreas Gohr            $html = hsc($html);
270ba2c2f17Sfurun            $html = preg_replace('/^----+$/m', '<hr >', $html);
271ba9c057bSAndreas Gohr            $html = nl2br($html);
272abbf0890SAndreas Gohr        }
273f08086ecSAndreas Gohr        if ($wrap) {
274749c0023SAndreas Gohr            $wrapper = rawLocale('mailwrap', 'html');
2753819cafdSfurun            $html = preg_replace('/\n-- <br \/>.*$/s', '', $html); //strip signature
2763819cafdSfurun            $html = str_replace('@EMAILSIGNATURE@', '', $html); //strip @EMAILSIGNATURE@
277749c0023SAndreas Gohr            $html = str_replace('@HTMLBODY@', $html, $wrapper);
278f08086ecSAndreas Gohr        }
279f08086ecSAndreas Gohr
280093fe67eSAndreas Gohr        if (!str_contains($text, '@EMAILSIGNATURE@')) {
2819ea45836SChristopher Smith            $text .= '@EMAILSIGNATURE@';
2823819cafdSfurun        }
283ba2c2f17Sfurun
28476efd6d0SAndreas Gohr        // copy over all replacements missing for HTML (autolink URLs)
28576efd6d0SAndreas Gohr        foreach ($textrep as $key => $value) {
28676efd6d0SAndreas Gohr            if (isset($htmlrep[$key])) continue;
2873e7e6067SKlap-in            if (media_isexternal($value)) {
28876efd6d0SAndreas Gohr                $htmlrep[$key] = '<a href="' . hsc($value) . '">' . hsc($value) . '</a>';
28976efd6d0SAndreas Gohr            } else {
29076efd6d0SAndreas Gohr                $htmlrep[$key] = hsc($value);
29176efd6d0SAndreas Gohr            }
292abbf0890SAndreas Gohr        }
293abbf0890SAndreas Gohr
294850dbf1fSAndreas Gohr        // embed media from templates
295a89c75afSAndreas Gohr        $html = preg_replace_callback(
296a89c75afSAndreas Gohr            '/@MEDIA\(([^\)]+)\)@/',
297093fe67eSAndreas Gohr            $this->autoEmbedCallBack(...),
298dccd6b2bSAndreas Gohr            $html
299a89c75afSAndreas Gohr        );
300850dbf1fSAndreas Gohr
3019ea45836SChristopher Smith        // add default token replacements
30224870174SAndreas Gohr        $trep = array_merge($this->replacements['text'], $textrep);
30324870174SAndreas Gohr        $hrep = array_merge($this->replacements['html'], $htmlrep);
304abbf0890SAndreas Gohr
305abbf0890SAndreas Gohr        // Apply replacements
306abbf0890SAndreas Gohr        foreach ($trep as $key => $substitution) {
307abbf0890SAndreas Gohr            $text = str_replace('@' . strtoupper($key) . '@', $substitution, $text);
308abbf0890SAndreas Gohr        }
309abbf0890SAndreas Gohr        foreach ($hrep as $key => $substitution) {
310abbf0890SAndreas Gohr            $html = str_replace('@' . strtoupper($key) . '@', $substitution, $html);
311abbf0890SAndreas Gohr        }
312abbf0890SAndreas Gohr
313abbf0890SAndreas Gohr        $this->setHTML($html);
314abbf0890SAndreas Gohr        $this->setText($text);
315abbf0890SAndreas Gohr    }
316abbf0890SAndreas Gohr
317abbf0890SAndreas Gohr    /**
318bb01c27cSAndreas Gohr     * Set the HTML part of the mail
319bb01c27cSAndreas Gohr     *
320bb01c27cSAndreas Gohr     * Placeholders can be used to reference embedded attachments
321abbf0890SAndreas Gohr     *
322abbf0890SAndreas Gohr     * You probably want to use setBody() instead
32342ea7f44SGerrit Uitslag     *
32442ea7f44SGerrit Uitslag     * @param string $html
325bb01c27cSAndreas Gohr     */
326d868eb89SAndreas Gohr    public function setHTML($html)
327d868eb89SAndreas Gohr    {
328bb01c27cSAndreas Gohr        $this->html = $html;
329bb01c27cSAndreas Gohr    }
330bb01c27cSAndreas Gohr
331bb01c27cSAndreas Gohr    /**
332bb01c27cSAndreas Gohr     * Set the plain text part of the mail
333abbf0890SAndreas Gohr     *
334abbf0890SAndreas Gohr     * You probably want to use setBody() instead
33542ea7f44SGerrit Uitslag     *
33642ea7f44SGerrit Uitslag     * @param string $text
337bb01c27cSAndreas Gohr     */
338d868eb89SAndreas Gohr    public function setText($text)
339d868eb89SAndreas Gohr    {
340bb01c27cSAndreas Gohr        $this->text = $text;
341bb01c27cSAndreas Gohr    }
342bb01c27cSAndreas Gohr
343bb01c27cSAndreas Gohr    /**
344a36fc348SAndreas Gohr     * Add the To: recipients
345a36fc348SAndreas Gohr     *
3468c253612SGerrit Uitslag     * @see cleanAddress
34759bc3b48SGerrit Uitslag     * @param string|string[]  $address Multiple adresses separated by commas or as array
348a36fc348SAndreas Gohr     */
349d868eb89SAndreas Gohr    public function to($address)
350d868eb89SAndreas Gohr    {
351a36fc348SAndreas Gohr        $this->setHeader('To', $address, false);
352a36fc348SAndreas Gohr    }
353a36fc348SAndreas Gohr
354a36fc348SAndreas Gohr    /**
355a36fc348SAndreas Gohr     * Add the Cc: recipients
356a36fc348SAndreas Gohr     *
3578c253612SGerrit Uitslag     * @see cleanAddress
35859bc3b48SGerrit Uitslag     * @param string|string[]  $address Multiple adresses separated by commas or as array
359a36fc348SAndreas Gohr     */
360d868eb89SAndreas Gohr    public function cc($address)
361d868eb89SAndreas Gohr    {
362a36fc348SAndreas Gohr        $this->setHeader('Cc', $address, false);
363a36fc348SAndreas Gohr    }
364a36fc348SAndreas Gohr
365a36fc348SAndreas Gohr    /**
366a36fc348SAndreas Gohr     * Add the Bcc: recipients
367a36fc348SAndreas Gohr     *
3688c253612SGerrit Uitslag     * @see cleanAddress
36959bc3b48SGerrit Uitslag     * @param string|string[]  $address Multiple adresses separated by commas or as array
370a36fc348SAndreas Gohr     */
371d868eb89SAndreas Gohr    public function bcc($address)
372d868eb89SAndreas Gohr    {
373a36fc348SAndreas Gohr        $this->setHeader('Bcc', $address, false);
374a36fc348SAndreas Gohr    }
375a36fc348SAndreas Gohr
376a36fc348SAndreas Gohr    /**
377a36fc348SAndreas Gohr     * Add the From: address
378a36fc348SAndreas Gohr     *
379a36fc348SAndreas Gohr     * This is set to $conf['mailfrom'] when not specified so you shouldn't need
380a36fc348SAndreas Gohr     * to call this function
381a36fc348SAndreas Gohr     *
3828c253612SGerrit Uitslag     * @see cleanAddress
383a36fc348SAndreas Gohr     * @param string  $address from address
384a36fc348SAndreas Gohr     */
385d868eb89SAndreas Gohr    public function from($address)
386d868eb89SAndreas Gohr    {
387a36fc348SAndreas Gohr        $this->setHeader('From', $address, false);
388a36fc348SAndreas Gohr    }
389a36fc348SAndreas Gohr
390a36fc348SAndreas Gohr    /**
391a36fc348SAndreas Gohr     * Add the mail's Subject: header
392a36fc348SAndreas Gohr     *
393a36fc348SAndreas Gohr     * @param string $subject the mail subject
394a36fc348SAndreas Gohr     */
395d868eb89SAndreas Gohr    public function subject($subject)
396d868eb89SAndreas Gohr    {
397a36fc348SAndreas Gohr        $this->headers['Subject'] = $subject;
398a36fc348SAndreas Gohr    }
399a36fc348SAndreas Gohr
400a36fc348SAndreas Gohr    /**
401102cdbd7SLarsGit223     * Return a clean name which can be safely used in mail address
402102cdbd7SLarsGit223     * fields. That means the name will be enclosed in '"' if it includes
403102cdbd7SLarsGit223     * a '"' or a ','. Also a '"' will be escaped as '\"'.
404102cdbd7SLarsGit223     *
405102cdbd7SLarsGit223     * @param string $name the name to clean-up
406102cdbd7SLarsGit223     * @see cleanAddress
407102cdbd7SLarsGit223     */
408d868eb89SAndreas Gohr    public function getCleanName($name)
409d868eb89SAndreas Gohr    {
4102b58f049SAndreas Gohr        $name = trim($name, " \t\"");
411102cdbd7SLarsGit223        $name = str_replace('"', '\"', $name, $count);
412093fe67eSAndreas Gohr        if ($count > 0 || str_contains($name, ',')) {
413102cdbd7SLarsGit223            $name = '"' . $name . '"';
414102cdbd7SLarsGit223        }
415102cdbd7SLarsGit223        return $name;
416102cdbd7SLarsGit223    }
417102cdbd7SLarsGit223
418102cdbd7SLarsGit223    /**
4191d045709SAndreas Gohr     * Sets an email address header with correct encoding
420bb01c27cSAndreas Gohr     *
421bb01c27cSAndreas Gohr     * Unicode characters will be deaccented and encoded base64
422bb01c27cSAndreas Gohr     * for headers. Addresses may not contain Non-ASCII data!
423bb01c27cSAndreas Gohr     *
424102cdbd7SLarsGit223     * If @$addresses is a string then it will be split into multiple
425102cdbd7SLarsGit223     * addresses. Addresses must be separated by a comma. If the display
426102cdbd7SLarsGit223     * name includes a comma then it MUST be properly enclosed by '"' to
427102cdbd7SLarsGit223     * prevent spliting at the wrong point.
428102cdbd7SLarsGit223     *
429bb01c27cSAndreas Gohr     * Example:
4308c253612SGerrit Uitslag     *   cc("föö <foo@bar.com>, me@somewhere.com","TBcc");
431102cdbd7SLarsGit223     *   to("foo, Dr." <foo@bar.com>, me@somewhere.com");
432bb01c27cSAndreas Gohr     *
43342ea7f44SGerrit Uitslag     * @param string|string[]  $addresses Multiple adresses separated by commas or as array
43442ea7f44SGerrit Uitslag     * @return false|string  the prepared header (can contain multiple lines)
435bb01c27cSAndreas Gohr     */
436d868eb89SAndreas Gohr    public function cleanAddress($addresses)
437d868eb89SAndreas Gohr    {
438bb01c27cSAndreas Gohr        $headers = '';
439b6c97c70SAndreas Gohr        if (!is_array($addresses)) {
440d31a1599SLarsGit223            $count = preg_match_all('/\s*(?:("[^"]*"[^,]+),*)|([^,]+)\s*,*/', $addresses, $matches, PREG_SET_ORDER);
44124870174SAndreas Gohr            $addresses = [];
442743792d0SLarsGit223            if ($count !== false && is_array($matches)) {
443102cdbd7SLarsGit223                foreach ($matches as $match) {
44424870174SAndreas Gohr                    $addresses[] = rtrim($match[0], ',');
445102cdbd7SLarsGit223                }
446b6c97c70SAndreas Gohr            }
447b6c97c70SAndreas Gohr        }
448b6c97c70SAndreas Gohr
449b6c97c70SAndreas Gohr        foreach ($addresses as $part) {
450b6c97c70SAndreas Gohr            $part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
451bb01c27cSAndreas Gohr            $part = trim($part);
452bb01c27cSAndreas Gohr
453bb01c27cSAndreas Gohr            // parse address
454bb01c27cSAndreas Gohr            if (preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
455bb01c27cSAndreas Gohr                $text = trim($matches[1]);
456bb01c27cSAndreas Gohr                $addr = $matches[2];
457bb01c27cSAndreas Gohr            } else {
45810da1f74SAndreas Gohr                $text = '';
459bb01c27cSAndreas Gohr                $addr = $part;
460bb01c27cSAndreas Gohr            }
461bb01c27cSAndreas Gohr            // skip empty ones
462bb01c27cSAndreas Gohr            if (empty($addr)) {
463bb01c27cSAndreas Gohr                continue;
464bb01c27cSAndreas Gohr            }
465bb01c27cSAndreas Gohr
466bb01c27cSAndreas Gohr            // FIXME: is there a way to encode the localpart of a emailaddress?
46724870174SAndreas Gohr            if (!Clean::isASCII($addr)) {
4684772cf38SAndreas Gohr                msg(hsc("E-Mail address <$addr> is not ASCII"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
469bb01c27cSAndreas Gohr                continue;
470bb01c27cSAndreas Gohr            }
471bb01c27cSAndreas Gohr
47273dc0a89SAndreas Gohr            if (!MailUtils::isValid($addr)) {
4734772cf38SAndreas Gohr                msg(hsc("E-Mail address <$addr> is not valid"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
474bb01c27cSAndreas Gohr                continue;
475bb01c27cSAndreas Gohr            }
476bb01c27cSAndreas Gohr
477bb01c27cSAndreas Gohr            // text was given
47830085ef3SYurii K            if (!empty($text) && !isWindows()) { // No named recipients for To: in Windows (see FS#652)
479bb01c27cSAndreas Gohr                // add address quotes
480bb01c27cSAndreas Gohr                $addr = "<$addr>";
481bb01c27cSAndreas Gohr
482bb01c27cSAndreas Gohr                if (defined('MAILHEADER_ASCIIONLY')) {
48324870174SAndreas Gohr                    $text = Clean::deaccent($text);
48424870174SAndreas Gohr                    $text = Clean::strip($text);
485bb01c27cSAndreas Gohr                }
486bb01c27cSAndreas Gohr
487093fe67eSAndreas Gohr                if (str_contains($text, ',') || !Clean::isASCII($text)) {
488bb01c27cSAndreas Gohr                    $text = '=?UTF-8?B?' . base64_encode($text) . '?=';
489bb01c27cSAndreas Gohr                }
490bb01c27cSAndreas Gohr            } else {
491bb01c27cSAndreas Gohr                $text = '';
492bb01c27cSAndreas Gohr            }
493bb01c27cSAndreas Gohr
494bb01c27cSAndreas Gohr            // add to header comma seperated
495bb01c27cSAndreas Gohr            if ($headers != '') {
496bb01c27cSAndreas Gohr                $headers .= ', ';
497bb01c27cSAndreas Gohr            }
498bb01c27cSAndreas Gohr            $headers .= $text . ' ' . $addr;
499bb01c27cSAndreas Gohr        }
500bb01c27cSAndreas Gohr
501b6c97c70SAndreas Gohr        $headers = trim($headers);
502bb01c27cSAndreas Gohr        if (empty($headers)) return false;
503bb01c27cSAndreas Gohr
504bb01c27cSAndreas Gohr        return $headers;
505bb01c27cSAndreas Gohr    }
506bb01c27cSAndreas Gohr
507bb01c27cSAndreas Gohr
508bb01c27cSAndreas Gohr    /**
509bb01c27cSAndreas Gohr     * Prepare the mime multiparts for all attachments
510bb01c27cSAndreas Gohr     *
511bb01c27cSAndreas Gohr     * Replaces placeholders in the HTML with the correct CIDs
51242ea7f44SGerrit Uitslag     *
51342ea7f44SGerrit Uitslag     * @return string mime multiparts
514bb01c27cSAndreas Gohr     */
515d868eb89SAndreas Gohr    protected function prepareAttachments()
516d868eb89SAndreas Gohr    {
517bb01c27cSAndreas Gohr        $mime = '';
518bb01c27cSAndreas Gohr        $part = 1;
519bb01c27cSAndreas Gohr        // embedded attachments
520bb01c27cSAndreas Gohr        foreach ($this->attach as $media) {
521ce9d2cc8SAndreas Gohr            $media['name'] = str_replace(':', '_', cleanID($media['name'], true));
522ce9d2cc8SAndreas Gohr
523bb01c27cSAndreas Gohr            // create content id
524bb01c27cSAndreas Gohr            $cid = 'part' . $part . '.' . $this->partid;
525bb01c27cSAndreas Gohr
526bb01c27cSAndreas Gohr            // replace wildcards
527bb01c27cSAndreas Gohr            if ($media['embed']) {
528bb01c27cSAndreas Gohr                $this->html = str_replace('%%' . $media['embed'] . '%%', 'cid:' . $cid, $this->html);
529bb01c27cSAndreas Gohr            }
530bb01c27cSAndreas Gohr
531bb01c27cSAndreas Gohr            $mime .= '--' . $this->boundary . MAILHEADER_EOL;
5321d8036c2SAndreas Gohr            $mime .= $this->wrappedHeaderLine('Content-Type', $media['mime'] . '; id="' . $cid . '"');
5331d8036c2SAndreas Gohr            $mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64');
5341d8036c2SAndreas Gohr            $mime .= $this->wrappedHeaderLine('Content-ID', "<$cid>");
535bb01c27cSAndreas Gohr            if ($media['embed']) {
5361d8036c2SAndreas Gohr                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename=' . $media['name']);
537bb01c27cSAndreas Gohr            } else {
5381d8036c2SAndreas Gohr                $mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename=' . $media['name']);
539bb01c27cSAndreas Gohr            }
540bb01c27cSAndreas Gohr            $mime .= MAILHEADER_EOL; //end of headers
541bb01c27cSAndreas Gohr            $mime .= chunk_split(base64_encode($media['data']), 74, MAILHEADER_EOL);
542bb01c27cSAndreas Gohr
543bb01c27cSAndreas Gohr            $part++;
544bb01c27cSAndreas Gohr        }
545bb01c27cSAndreas Gohr        return $mime;
546bb01c27cSAndreas Gohr    }
547bb01c27cSAndreas Gohr
5481d045709SAndreas Gohr    /**
5491d045709SAndreas Gohr     * Build the body and handles multi part mails
5501d045709SAndreas Gohr     *
5511d045709SAndreas Gohr     * Needs to be called before prepareHeaders!
5521d045709SAndreas Gohr     *
5531d045709SAndreas Gohr     * @return string the prepared mail body, false on errors
5541d045709SAndreas Gohr     */
555d868eb89SAndreas Gohr    protected function prepareBody()
556d868eb89SAndreas Gohr    {
5571d045709SAndreas Gohr
5582398a2b5SAndreas Gohr        // no HTML mails allowed? remove HTML body
5592398a2b5SAndreas Gohr        if (!$this->allowhtml) {
5602398a2b5SAndreas Gohr            $this->html = '';
5612398a2b5SAndreas Gohr        }
5622398a2b5SAndreas Gohr
563bb01c27cSAndreas Gohr        // check for body
564bb01c27cSAndreas Gohr        if (!$this->text && !$this->html) {
565bb01c27cSAndreas Gohr            return false;
566bb01c27cSAndreas Gohr        }
567bb01c27cSAndreas Gohr
568bb01c27cSAndreas Gohr        // add general headers
569bb01c27cSAndreas Gohr        $this->headers['MIME-Version'] = '1.0';
570bb01c27cSAndreas Gohr
5711d045709SAndreas Gohr        $body = '';
5721d045709SAndreas Gohr
573bb01c27cSAndreas Gohr        if (!$this->html && !count($this->attach)) { // we can send a simple single part message
574bb01c27cSAndreas Gohr            $this->headers['Content-Type']              = 'text/plain; charset=UTF-8';
575bb01c27cSAndreas Gohr            $this->headers['Content-Transfer-Encoding'] = 'base64';
576be3cc6abSAndreas Gohr            $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
577bb01c27cSAndreas Gohr        } else { // multi part it is
5781d045709SAndreas Gohr            $body .= "This is a multi-part message in MIME format." . MAILHEADER_EOL;
579bb01c27cSAndreas Gohr
580bb01c27cSAndreas Gohr            // prepare the attachments
581bb01c27cSAndreas Gohr            $attachments = $this->prepareAttachments();
582bb01c27cSAndreas Gohr
583bb01c27cSAndreas Gohr            // do we have alternative text content?
584bb01c27cSAndreas Gohr            if ($this->text && $this->html) {
585a36fc348SAndreas Gohr                $this->headers['Content-Type'] = 'multipart/alternative;' . MAILHEADER_EOL .
586a36fc348SAndreas Gohr                    '  boundary="' . $this->boundary . 'XX"';
587bb01c27cSAndreas Gohr                $body .= '--' . $this->boundary . 'XX' . MAILHEADER_EOL;
5881d045709SAndreas Gohr                $body .= 'Content-Type: text/plain; charset=UTF-8' . MAILHEADER_EOL;
5891d045709SAndreas Gohr                $body .= 'Content-Transfer-Encoding: base64' . MAILHEADER_EOL;
590bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
591be3cc6abSAndreas Gohr                $body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
592bb01c27cSAndreas Gohr                $body .= '--' . $this->boundary . 'XX' . MAILHEADER_EOL;
593a36fc348SAndreas Gohr                $body .= 'Content-Type: multipart/related;' . MAILHEADER_EOL .
594d6e04b60SAndreas Gohr                    '  boundary="' . $this->boundary . '";' . MAILHEADER_EOL .
595d6e04b60SAndreas Gohr                    '  type="text/html"' . MAILHEADER_EOL;
596bb01c27cSAndreas Gohr                $body .= MAILHEADER_EOL;
597bb01c27cSAndreas Gohr            }
598bb01c27cSAndreas Gohr
5991d045709SAndreas Gohr            $body .= '--' . $this->boundary . MAILHEADER_EOL;
6001d045709SAndreas Gohr            $body .= 'Content-Type: text/html; charset=UTF-8' . MAILHEADER_EOL;
6011d045709SAndreas Gohr            $body .= 'Content-Transfer-Encoding: base64' . MAILHEADER_EOL;
602bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
603be3cc6abSAndreas Gohr            $body .= chunk_split(base64_encode($this->html), 72, MAILHEADER_EOL);
604bb01c27cSAndreas Gohr            $body .= MAILHEADER_EOL;
605bb01c27cSAndreas Gohr            $body .= $attachments;
606bb01c27cSAndreas Gohr            $body .= '--' . $this->boundary . '--' . MAILHEADER_EOL;
607bb01c27cSAndreas Gohr
608bb01c27cSAndreas Gohr            // close open multipart/alternative boundary
609bb01c27cSAndreas Gohr            if ($this->text && $this->html) {
610bb01c27cSAndreas Gohr                $body .= '--' . $this->boundary . 'XX--' . MAILHEADER_EOL;
611bb01c27cSAndreas Gohr            }
612bb01c27cSAndreas Gohr        }
613bb01c27cSAndreas Gohr
614bb01c27cSAndreas Gohr        return $body;
615bb01c27cSAndreas Gohr    }
616bb01c27cSAndreas Gohr
617bb01c27cSAndreas Gohr    /**
618a36fc348SAndreas Gohr     * Cleanup and encode the headers array
619a36fc348SAndreas Gohr     */
620d868eb89SAndreas Gohr    protected function cleanHeaders()
621d868eb89SAndreas Gohr    {
622a36fc348SAndreas Gohr        global $conf;
623a36fc348SAndreas Gohr
624a36fc348SAndreas Gohr        // clean up addresses
625a36fc348SAndreas Gohr        if (empty($this->headers['From'])) $this->from($conf['mailfrom']);
62624870174SAndreas Gohr        $addrs = ['To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender'];
627a36fc348SAndreas Gohr        foreach ($addrs as $addr) {
628a36fc348SAndreas Gohr            if (isset($this->headers[$addr])) {
629a36fc348SAndreas Gohr                $this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
630a36fc348SAndreas Gohr            }
631a36fc348SAndreas Gohr        }
632a36fc348SAndreas Gohr
63345992a63SAndreas Gohr        if (isset($this->headers['Subject'])) {
634a36fc348SAndreas Gohr            // add prefix to subject
63554f30755SAndreas Gohr            if (empty($conf['mailprefix'])) {
63624870174SAndreas Gohr                if (PhpString::strlen($conf['title']) < 20) {
63754f30755SAndreas Gohr                    $prefix = '[' . $conf['title'] . ']';
63854f30755SAndreas Gohr                } else {
63924870174SAndreas Gohr                    $prefix = '[' . PhpString::substr($conf['title'], 0, 20) . '...]';
6408a215f09SAndreas Gohr                }
6418a215f09SAndreas Gohr            } else {
642a36fc348SAndreas Gohr                $prefix = '[' . $conf['mailprefix'] . ']';
64354f30755SAndreas Gohr            }
6446c16a3a9Sfiwswe            if (!str_starts_with($this->headers['Subject'], $prefix)) {
64545992a63SAndreas Gohr                $this->headers['Subject'] = $prefix . ' ' . $this->headers['Subject'];
646a36fc348SAndreas Gohr            }
647a36fc348SAndreas Gohr
648a36fc348SAndreas Gohr            // encode subject
649a36fc348SAndreas Gohr            if (defined('MAILHEADER_ASCIIONLY')) {
65024870174SAndreas Gohr                $this->headers['Subject'] = Clean::deaccent($this->headers['Subject']);
65124870174SAndreas Gohr                $this->headers['Subject'] = Clean::strip($this->headers['Subject']);
652a36fc348SAndreas Gohr            }
65324870174SAndreas Gohr            if (!Clean::isASCII($this->headers['Subject'])) {
65445992a63SAndreas Gohr                $this->headers['Subject'] = '=?UTF-8?B?' . base64_encode($this->headers['Subject']) . '?=';
655a36fc348SAndreas Gohr            }
656a36fc348SAndreas Gohr        }
657a36fc348SAndreas Gohr    }
6581d8036c2SAndreas Gohr
6591d8036c2SAndreas Gohr    /**
6601d8036c2SAndreas Gohr     * Returns a complete, EOL terminated header line, wraps it if necessary
6611d8036c2SAndreas Gohr     *
66242ea7f44SGerrit Uitslag     * @param string $key
66342ea7f44SGerrit Uitslag     * @param string $val
66442ea7f44SGerrit Uitslag     * @return string line
6651d8036c2SAndreas Gohr     */
666d868eb89SAndreas Gohr    protected function wrappedHeaderLine($key, $val)
667d868eb89SAndreas Gohr    {
6681d8036c2SAndreas Gohr        return wordwrap("$key: $val", 78, MAILHEADER_EOL . '  ') . MAILHEADER_EOL;
669a36fc348SAndreas Gohr    }
670a36fc348SAndreas Gohr
671a36fc348SAndreas Gohr    /**
672bb01c27cSAndreas Gohr     * Create a string from the headers array
6731d045709SAndreas Gohr     *
6741d045709SAndreas Gohr     * @returns string the headers
675bb01c27cSAndreas Gohr     */
676d868eb89SAndreas Gohr    protected function prepareHeaders()
677d868eb89SAndreas Gohr    {
678bb01c27cSAndreas Gohr        $headers = '';
679bb01c27cSAndreas Gohr        foreach ($this->headers as $key => $val) {
680749c0023SAndreas Gohr            if ($val === '' || $val === null) continue;
6811d8036c2SAndreas Gohr            $headers .= $this->wrappedHeaderLine($key, $val);
682bb01c27cSAndreas Gohr        }
683bb01c27cSAndreas Gohr        return $headers;
684bb01c27cSAndreas Gohr    }
685bb01c27cSAndreas Gohr
686bb01c27cSAndreas Gohr    /**
687bb01c27cSAndreas Gohr     * return a full email with all headers
688bb01c27cSAndreas Gohr     *
6891d045709SAndreas Gohr     * This is mainly intended for debugging and testing but could also be
6901d045709SAndreas Gohr     * used for MHT exports
6911d045709SAndreas Gohr     *
6921d045709SAndreas Gohr     * @return string the mail, false on errors
693bb01c27cSAndreas Gohr     */
694d868eb89SAndreas Gohr    public function dump()
695d868eb89SAndreas Gohr    {
696a36fc348SAndreas Gohr        $this->cleanHeaders();
697bb01c27cSAndreas Gohr        $body = $this->prepareBody();
6984d18e936SAndreas Gohr        if ($body === false) return false;
6991d045709SAndreas Gohr        $headers = $this->prepareHeaders();
700bb01c27cSAndreas Gohr
701bb01c27cSAndreas Gohr        return $headers . MAILHEADER_EOL . $body;
702bb01c27cSAndreas Gohr    }
7031d045709SAndreas Gohr
7041d045709SAndreas Gohr    /**
7059ea45836SChristopher Smith     * Prepare default token replacement strings
7069ea45836SChristopher Smith     *
7079ea45836SChristopher Smith     * Populates the '$replacements' property.
7089ea45836SChristopher Smith     * Should be called by the class constructor
7099ea45836SChristopher Smith     */
710d868eb89SAndreas Gohr    protected function prepareTokenReplacements()
711d868eb89SAndreas Gohr    {
7129ea45836SChristopher Smith        global $INFO;
7139ea45836SChristopher Smith        global $conf;
7149ea45836SChristopher Smith        /* @var Input $INPUT */
7159ea45836SChristopher Smith        global $INPUT;
7169ea45836SChristopher Smith        global $lang;
7179ea45836SChristopher Smith
7189ea45836SChristopher Smith        $ip   = clientIP();
7199ea45836SChristopher Smith        $cip  = gethostsbyaddrs($ip);
7208fa268b3SAndreas Gohr        $name = $INFO['userinfo']['name'] ?? '';
7218fa268b3SAndreas Gohr        $mail = $INFO['userinfo']['mail'] ?? '';
7229ea45836SChristopher Smith
72324870174SAndreas Gohr        $this->replacements['text'] = [
7249ea45836SChristopher Smith            'DATE' => dformat(),
7259ea45836SChristopher Smith            'BROWSER' => $INPUT->server->str('HTTP_USER_AGENT'),
7269ea45836SChristopher Smith            'IPADDRESS' => $ip,
7279ea45836SChristopher Smith            'HOSTNAME' => $cip,
7289ea45836SChristopher Smith            'TITLE' => $conf['title'],
7299ea45836SChristopher Smith            'DOKUWIKIURL' => DOKU_URL,
7309ea45836SChristopher Smith            'USER' => $INPUT->server->str('REMOTE_USER'),
73168491db9SPhy            'NAME' => $name,
73268491db9SPhy            'MAIL' => $mail
73324870174SAndreas Gohr        ];
73424870174SAndreas Gohr
73564159a61SAndreas Gohr        $signature = str_replace(
73664159a61SAndreas Gohr            '@DOKUWIKIURL@',
73764159a61SAndreas Gohr            $this->replacements['text']['DOKUWIKIURL'],
73864159a61SAndreas Gohr            $lang['email_signature_text']
73964159a61SAndreas Gohr        );
740774514c9SGerrit Uitslag        $this->replacements['text']['EMAILSIGNATURE'] = "\n-- \n" . $signature . "\n";
7419ea45836SChristopher Smith
74224870174SAndreas Gohr        $this->replacements['html'] = [
7439ea45836SChristopher Smith            'DATE' => '<i>' . hsc(dformat()) . '</i>',
7449ea45836SChristopher Smith            'BROWSER' => hsc($INPUT->server->str('HTTP_USER_AGENT')),
7459ea45836SChristopher Smith            'IPADDRESS' => '<code>' . hsc($ip) . '</code>',
7469ea45836SChristopher Smith            'HOSTNAME' => '<code>' . hsc($cip) . '</code>',
7479ea45836SChristopher Smith            'TITLE' => hsc($conf['title']),
7489ea45836SChristopher Smith            'DOKUWIKIURL' => '<a href="' . DOKU_URL . '">' . DOKU_URL . '</a>',
7499ea45836SChristopher Smith            'USER' => hsc($INPUT->server->str('REMOTE_USER')),
75068491db9SPhy            'NAME' => hsc($name),
75124870174SAndreas Gohr            'MAIL' => '<a href="mailto:"' . hsc($mail) . '">' . hsc($mail) . '</a>'
75224870174SAndreas Gohr        ];
753774514c9SGerrit Uitslag        $signature = $lang['email_signature_text'];
754774514c9SGerrit Uitslag        if (!empty($lang['email_signature_html'])) {
755774514c9SGerrit Uitslag            $signature = $lang['email_signature_html'];
756774514c9SGerrit Uitslag        }
757774514c9SGerrit Uitslag        $signature = str_replace(
75824870174SAndreas Gohr            ['@DOKUWIKIURL@', "\n"],
75924870174SAndreas Gohr            [$this->replacements['html']['DOKUWIKIURL'], '<br />'],
760774514c9SGerrit Uitslag            $signature
761774514c9SGerrit Uitslag        );
762774514c9SGerrit Uitslag        $this->replacements['html']['EMAILSIGNATURE'] = $signature;
7639ea45836SChristopher Smith    }
7649ea45836SChristopher Smith
7659ea45836SChristopher Smith    /**
7661d045709SAndreas Gohr     * Send the mail
7671d045709SAndreas Gohr     *
7681d045709SAndreas Gohr     * Call this after all data was set
7691d045709SAndreas Gohr     *
77028d2ad80SAndreas Gohr     * @triggers MAIL_MESSAGE_SEND
7711d045709SAndreas Gohr     * @return bool true if the mail was successfully passed to the MTA
7721d045709SAndreas Gohr     */
773d868eb89SAndreas Gohr    public function send()
774d868eb89SAndreas Gohr    {
7753f6872b1SMyron Turner        global $lang;
77628d2ad80SAndreas Gohr        $success = false;
777a36fc348SAndreas Gohr
77828d2ad80SAndreas Gohr        // prepare hook data
77924870174SAndreas Gohr        $data = [
78028d2ad80SAndreas Gohr            // pass the whole mail class to plugin
78128d2ad80SAndreas Gohr            'mail'    => $this,
78228d2ad80SAndreas Gohr            // pass references for backward compatibility
78328d2ad80SAndreas Gohr            'to'      => &$this->headers['To'],
78428d2ad80SAndreas Gohr            'cc'      => &$this->headers['Cc'],
78528d2ad80SAndreas Gohr            'bcc'     => &$this->headers['Bcc'],
78628d2ad80SAndreas Gohr            'from'    => &$this->headers['From'],
78728d2ad80SAndreas Gohr            'subject' => &$this->headers['Subject'],
78828d2ad80SAndreas Gohr            'body'    => &$this->text,
789a89c75afSAndreas Gohr            'params'  => &$this->sendparam,
79028d2ad80SAndreas Gohr            'headers' => '', // plugins shouldn't use this
79128d2ad80SAndreas Gohr            // signal if we mailed successfully to AFTER event
79228d2ad80SAndreas Gohr            'success' => &$success,
79324870174SAndreas Gohr        ];
79428d2ad80SAndreas Gohr
79528d2ad80SAndreas Gohr        // do our thing if BEFORE hook approves
796e1d9dcc8SAndreas Gohr        $evt = new Event('MAIL_MESSAGE_SEND', $data);
79728d2ad80SAndreas Gohr        if ($evt->advise_before(true)) {
79828d2ad80SAndreas Gohr            // clean up before using the headers
799a36fc348SAndreas Gohr            $this->cleanHeaders();
800a36fc348SAndreas Gohr
8011d045709SAndreas Gohr            // any recipients?
8027d34963bSAndreas Gohr            if (
8037d34963bSAndreas Gohr                trim($this->headers['To']) === '' &&
8041d045709SAndreas Gohr                trim($this->headers['Cc']) === '' &&
805a89c75afSAndreas Gohr                trim($this->headers['Bcc']) === ''
806a89c75afSAndreas Gohr            ) return false;
8071d045709SAndreas Gohr
8081d045709SAndreas Gohr            // The To: header is special
8096be717dbSMichael Hamann            if (array_key_exists('To', $this->headers)) {
8106be717dbSMichael Hamann                $to = (string)$this->headers['To'];
8111d045709SAndreas Gohr                unset($this->headers['To']);
8121d045709SAndreas Gohr            } else {
8131d045709SAndreas Gohr                $to = '';
8141d045709SAndreas Gohr            }
8151d045709SAndreas Gohr
8161d045709SAndreas Gohr            // so is the subject
8176be717dbSMichael Hamann            if (array_key_exists('Subject', $this->headers)) {
8186be717dbSMichael Hamann                $subject = (string)$this->headers['Subject'];
8191d045709SAndreas Gohr                unset($this->headers['Subject']);
8201d045709SAndreas Gohr            } else {
8211d045709SAndreas Gohr                $subject = '';
8221d045709SAndreas Gohr            }
8231d045709SAndreas Gohr
8241d045709SAndreas Gohr            // make the body
8251d045709SAndreas Gohr            $body = $this->prepareBody();
8264c89a7f6SAndreas Gohr            if ($body === false) return false;
8271d045709SAndreas Gohr
8281d045709SAndreas Gohr            // cook the headers
8291d045709SAndreas Gohr            $headers = $this->prepareHeaders();
83028d2ad80SAndreas Gohr            // add any headers set by legacy plugins
83128d2ad80SAndreas Gohr            if (trim($data['headers'])) {
83228d2ad80SAndreas Gohr                $headers .= MAILHEADER_EOL . trim($data['headers']);
83328d2ad80SAndreas Gohr            }
8341d045709SAndreas Gohr
8353f6872b1SMyron Turner            if (!function_exists('mail')) {
8363f6872b1SMyron Turner                $emsg = $lang['email_fail'] . $subject;
8373f6872b1SMyron Turner                error_log($emsg);
8383f6872b1SMyron Turner                msg(hsc($emsg), -1, __LINE__, __FILE__, MSG_MANAGERS_ONLY);
8393f6872b1SMyron Turner                $evt->advise_after();
8403f6872b1SMyron Turner                return false;
8413f6872b1SMyron Turner            }
8423f6872b1SMyron Turner
8431d045709SAndreas Gohr            // send the thing
844bfa6d256SAndreas Gohr            if ($to === '') $to = '(undisclosed-recipients)'; // #1422
845749c0023SAndreas Gohr            if ($this->sendparam === null) {
84628d2ad80SAndreas Gohr                $success = @mail($to, $subject, $body, $headers);
8471d045709SAndreas Gohr            } else {
84828d2ad80SAndreas Gohr                $success = @mail($to, $subject, $body, $headers, $this->sendparam);
8491d045709SAndreas Gohr            }
8501d045709SAndreas Gohr        }
85128d2ad80SAndreas Gohr        // any AFTER actions?
85228d2ad80SAndreas Gohr        $evt->advise_after();
85328d2ad80SAndreas Gohr        return $success;
85428d2ad80SAndreas Gohr    }
855bb01c27cSAndreas Gohr}
856