xref: /dokuwiki/inc/MailUtils.php (revision c959e5ab963ba051e2d168d1c866a0659c90ed54)
173dc0a89SAndreas Gohr<?php
273dc0a89SAndreas Gohr
373dc0a89SAndreas Gohrnamespace dokuwiki;
473dc0a89SAndreas Gohr
573dc0a89SAndreas Gohruse dokuwiki\Utf8\Conversion;
673dc0a89SAndreas Gohr
773dc0a89SAndreas Gohr/**
873dc0a89SAndreas Gohr * Stateless email-address utilities: obfuscation, validation, and quoted-printable body encoding.
973dc0a89SAndreas Gohr */
1073dc0a89SAndreas Gohrclass MailUtils
1173dc0a89SAndreas Gohr{
1273dc0a89SAndreas Gohr    /**
1373dc0a89SAndreas Gohr     * RFC 2822 atext characters (paras 3.4.1 & 3.2.4).
1473dc0a89SAndreas Gohr     *
1573dc0a89SAndreas Gohr     * NOTE: the unquoted '/' must remain unquoted to be usable as part of a
1673dc0a89SAndreas Gohr     * Lexer pattern; pick the surrounding pattern delimiters with care.
1773dc0a89SAndreas Gohr     */
1873dc0a89SAndreas Gohr    public const RFC2822_ATEXT = "0-9a-zA-Z!#$%&'*+/=?^_`{|}~-";
1973dc0a89SAndreas Gohr
2073dc0a89SAndreas Gohr    /**
2173dc0a89SAndreas Gohr     * Pattern for use in email detection and validation.
2273dc0a89SAndreas Gohr     *
2373dc0a89SAndreas Gohr     * Uses non-capturing groups since the parser does not allow captures.
2473dc0a89SAndreas Gohr     */
2573dc0a89SAndreas Gohr    public const PREG_PATTERN_VALID_EMAIL =
2673dc0a89SAndreas Gohr        '[' . self::RFC2822_ATEXT . ']+(?:\.[' . self::RFC2822_ATEXT . ']+)*'
2773dc0a89SAndreas Gohr        . '@(?i:[0-9a-z][0-9a-z-]*\.)+(?i:[a-z]{2,63})';
2873dc0a89SAndreas Gohr
2973dc0a89SAndreas Gohr    // region email-address obfuscation
3073dc0a89SAndreas Gohr
3173dc0a89SAndreas Gohr    /**
3273dc0a89SAndreas Gohr     * Return an obfuscated email address suitable for HTML text content
3373dc0a89SAndreas Gohr     * (link labels, titles).
3473dc0a89SAndreas Gohr     *
3573dc0a89SAndreas Gohr     * The caller MUST pass a raw, unescaped string; the result is
3673dc0a89SAndreas Gohr     * HTML-text-safe. Any query string after the first '?' is preserved
3773dc0a89SAndreas Gohr     * verbatim and is never run through the [at]/[dot]/[dash] substitution,
3873dc0a89SAndreas Gohr     * so dots and dashes inside body/subject values stay intact.
3973dc0a89SAndreas Gohr     *
4073dc0a89SAndreas Gohr     * @param string $email raw email address, optionally followed by ?query
4173dc0a89SAndreas Gohr     * @return string HTML-text-safe representation
4273dc0a89SAndreas Gohr     */
4373dc0a89SAndreas Gohr    public static function obfuscate(string $email): string
4473dc0a89SAndreas Gohr    {
4573dc0a89SAndreas Gohr        global $conf;
4673dc0a89SAndreas Gohr
4773dc0a89SAndreas Gohr        [$addr, $query] = sexplode('?', $email, 2);
4873dc0a89SAndreas Gohr        $out = self::obfuscateAddress($addr);
4973dc0a89SAndreas Gohr        // 'hex' output is already pure ASCII numeric entities → HTML-safe.
5073dc0a89SAndreas Gohr        // For 'none'/'visible' the address half still needs HTML escaping.
5173dc0a89SAndreas Gohr        if ($conf['mailguard'] !== 'hex') {
5273dc0a89SAndreas Gohr            $out = htmlspecialchars($out, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
5373dc0a89SAndreas Gohr        }
5473dc0a89SAndreas Gohr        if ($query !== null) {
5573dc0a89SAndreas Gohr            $out .= '?' . htmlspecialchars($query, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
5673dc0a89SAndreas Gohr        }
5773dc0a89SAndreas Gohr        return $out;
5873dc0a89SAndreas Gohr    }
5973dc0a89SAndreas Gohr
6073dc0a89SAndreas Gohr    /**
6173dc0a89SAndreas Gohr     * Return an obfuscated email address suitable for use as a mailto: href
6273dc0a89SAndreas Gohr     * value (HTML attribute context).
6373dc0a89SAndreas Gohr     *
6473dc0a89SAndreas Gohr     * Like obfuscate() but for HTML attribute context. The caller MUST pass a
6573dc0a89SAndreas Gohr     * raw, unescaped string. The address half is obfuscated per the mailguard
6673dc0a89SAndreas Gohr     * setting; in 'visible' mode the address (with its [at]/[dot] spaces) is
6773dc0a89SAndreas Gohr     * percent-encoded so the URL is well-formed. The query string is
6873dc0a89SAndreas Gohr     * preserved verbatim with only HTML-attribute escaping applied, so mail
6973dc0a89SAndreas Gohr     * clients receive correct subject/body separators.
7073dc0a89SAndreas Gohr     *
7173dc0a89SAndreas Gohr     * @param string $email raw email address, optionally followed by ?query
7273dc0a89SAndreas Gohr     * @return string HTML-attribute-safe URL fragment (without 'mailto:' prefix)
7373dc0a89SAndreas Gohr     */
7473dc0a89SAndreas Gohr    public static function obfuscateUrl(string $email): string
7573dc0a89SAndreas Gohr    {
7673dc0a89SAndreas Gohr        global $conf;
7773dc0a89SAndreas Gohr
7873dc0a89SAndreas Gohr        [$addr, $query] = sexplode('?', $email, 2);
7973dc0a89SAndreas Gohr        $addr = self::obfuscateAddress($addr);
8073dc0a89SAndreas Gohr        if ($conf['mailguard'] === 'visible') {
8173dc0a89SAndreas Gohr            $addr = rawurlencode($addr);
8273dc0a89SAndreas Gohr        }
8373dc0a89SAndreas Gohr        if ($conf['mailguard'] !== 'hex') {
8473dc0a89SAndreas Gohr            $addr = htmlspecialchars($addr, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
8573dc0a89SAndreas Gohr        }
8673dc0a89SAndreas Gohr        if ($query !== null) {
8773dc0a89SAndreas Gohr            $addr .= '?' . htmlspecialchars($query, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
8873dc0a89SAndreas Gohr        }
8973dc0a89SAndreas Gohr        return $addr;
9073dc0a89SAndreas Gohr    }
9173dc0a89SAndreas Gohr
9273dc0a89SAndreas Gohr    /**
9373dc0a89SAndreas Gohr     * Apply the configured mailguard mode to the address half of a mailto
9473dc0a89SAndreas Gohr     * target. Returns hex-mode output as numeric entities (HTML-safe);
9573dc0a89SAndreas Gohr     * visible/none modes return raw text that still needs HTML escaping.
9673dc0a89SAndreas Gohr     *
9773dc0a89SAndreas Gohr     * @param string $addr raw local@domain
9873dc0a89SAndreas Gohr     * @return string
9973dc0a89SAndreas Gohr     */
10073dc0a89SAndreas Gohr    protected static function obfuscateAddress(string $addr): string
10173dc0a89SAndreas Gohr    {
10273dc0a89SAndreas Gohr        global $conf;
10373dc0a89SAndreas Gohr
10473dc0a89SAndreas Gohr        return match ($conf['mailguard']) {
10573dc0a89SAndreas Gohr            'visible' => strtr($addr, ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ']),
10673dc0a89SAndreas Gohr            'hex' => Conversion::toHtml($addr, true),
10773dc0a89SAndreas Gohr            default => $addr,
10873dc0a89SAndreas Gohr        };
10973dc0a89SAndreas Gohr    }
11073dc0a89SAndreas Gohr
11173dc0a89SAndreas Gohr    // endregion
11273dc0a89SAndreas Gohr    // region outgoing-mail helpers
11373dc0a89SAndreas Gohr
11473dc0a89SAndreas Gohr    /**
11573dc0a89SAndreas Gohr     * Check if a given mail address is valid.
11673dc0a89SAndreas Gohr     *
11773dc0a89SAndreas Gohr     * @param string $email the address to check
11873dc0a89SAndreas Gohr     * @return bool true if address is valid
11973dc0a89SAndreas Gohr     */
12073dc0a89SAndreas Gohr    public static function isValid(string $email): bool
12173dc0a89SAndreas Gohr    {
12273dc0a89SAndreas Gohr        return \EmailAddressValidator::checkEmailAddress($email, true);
12373dc0a89SAndreas Gohr    }
12473dc0a89SAndreas Gohr
12573dc0a89SAndreas Gohr    /**
12673dc0a89SAndreas Gohr     * RFC 2045 quoted-printable encoding.
12773dc0a89SAndreas Gohr     *
12873dc0a89SAndreas Gohr     * @param string $sText
12973dc0a89SAndreas Gohr     * @param int $maxlen
13073dc0a89SAndreas Gohr     * @param bool $bEmulate_imap_8bit
13173dc0a89SAndreas Gohr     * @return string
13273dc0a89SAndreas Gohr     * @author umu <umuAThrz.tu-chemnitz.de>
13373dc0a89SAndreas Gohr     * @link   http://php.net/manual/en/function.imap-8bit.php#61216
13473dc0a89SAndreas Gohr     *
13573dc0a89SAndreas Gohr     */
13673dc0a89SAndreas Gohr    public static function quotedPrintableEncode(
13773dc0a89SAndreas Gohr        string $sText,
13873dc0a89SAndreas Gohr        int $maxlen = 74,
13973dc0a89SAndreas Gohr        bool $bEmulate_imap_8bit = true
140*c959e5abSsplitbrain    ): string {
14173dc0a89SAndreas Gohr        // split text into lines
14273dc0a89SAndreas Gohr        $aLines = preg_split("/(?:\r\n|\r|\n)/", $sText);
14373dc0a89SAndreas Gohr        $cnt = count($aLines);
14473dc0a89SAndreas Gohr
14573dc0a89SAndreas Gohr        for ($i = 0; $i < $cnt; $i++) {
14673dc0a89SAndreas Gohr            $sLine =& $aLines[$i];
14773dc0a89SAndreas Gohr            if ($sLine === '') continue; // do nothing, if empty
14873dc0a89SAndreas Gohr
14973dc0a89SAndreas Gohr            $sRegExp = '/[^\x09\x20\x21-\x3C\x3E-\x7E]/e';
15073dc0a89SAndreas Gohr
15173dc0a89SAndreas Gohr            // imap_8bit encodes x09 everywhere, not only at lineends,
15273dc0a89SAndreas Gohr            // for EBCDIC safeness encode !"#$@[\]^`{|}~,
15373dc0a89SAndreas Gohr            // for complete safeness encode every character :)
15473dc0a89SAndreas Gohr            if ($bEmulate_imap_8bit)
15573dc0a89SAndreas Gohr                $sRegExp = '/[^\x20\x21-\x3C\x3E-\x7E]/';
15673dc0a89SAndreas Gohr
15773dc0a89SAndreas Gohr            $sLine = preg_replace_callback(
15873dc0a89SAndreas Gohr                $sRegExp,
15973dc0a89SAndreas Gohr                static fn(array $matches): string => sprintf("=%02X", ord($matches[0])),
16073dc0a89SAndreas Gohr                $sLine
16173dc0a89SAndreas Gohr            );
16273dc0a89SAndreas Gohr
16373dc0a89SAndreas Gohr            // encode x09,x20 at lineends
16473dc0a89SAndreas Gohr            $iLength = strlen($sLine);
16573dc0a89SAndreas Gohr            $iLastChar = ord($sLine[$iLength - 1]);
16673dc0a89SAndreas Gohr
16773dc0a89SAndreas Gohr            // imap_8_bit does not encode x20 at the very end of a text,
16873dc0a89SAndreas Gohr            // here is, where I don't agree with imap_8_bit,
16973dc0a89SAndreas Gohr            // please correct me, if I'm wrong,
17073dc0a89SAndreas Gohr            // or comment next line for RFC2045 conformance, if you like
17173dc0a89SAndreas Gohr            if (!($bEmulate_imap_8bit && ($i == count($aLines) - 1))) {
17273dc0a89SAndreas Gohr                if (($iLastChar == 0x09) || ($iLastChar == 0x20)) {
17373dc0a89SAndreas Gohr                    $sLine[$iLength - 1] = '=';
17473dc0a89SAndreas Gohr                    $sLine .= ($iLastChar == 0x09) ? '09' : '20';
17573dc0a89SAndreas Gohr                }
17673dc0a89SAndreas Gohr            }
17773dc0a89SAndreas Gohr
17873dc0a89SAndreas Gohr            // imap_8bit encodes x20 before chr(13), too
17973dc0a89SAndreas Gohr            // although IMHO not requested by RFC2045, why not do it safer :)
18073dc0a89SAndreas Gohr            // and why not encode any x20 around chr(10) or chr(13)
18173dc0a89SAndreas Gohr            if ($bEmulate_imap_8bit) {
18273dc0a89SAndreas Gohr                $sLine = str_replace(' =0D', '=20=0D', $sLine);
18373dc0a89SAndreas Gohr                //$sLine=str_replace(' =0A','=20=0A',$sLine);
18473dc0a89SAndreas Gohr                //$sLine=str_replace('=0D ','=0D=20',$sLine);
18573dc0a89SAndreas Gohr                //$sLine=str_replace('=0A ','=0A=20',$sLine);
18673dc0a89SAndreas Gohr            }
18773dc0a89SAndreas Gohr
18873dc0a89SAndreas Gohr            // finally split into softlines no longer than $maxlen chars,
18973dc0a89SAndreas Gohr            // for even more safeness one could encode x09,x20
19073dc0a89SAndreas Gohr            // at the very first character of the line
19173dc0a89SAndreas Gohr            // and after soft linebreaks, as well,
19273dc0a89SAndreas Gohr            // but this wouldn't be caught by such an easy RegExp
19373dc0a89SAndreas Gohr            if ($maxlen) {
19473dc0a89SAndreas Gohr                preg_match_all('/.{1,' . ($maxlen - 2) . '}([^=]{0,2})?/', $sLine, $aMatch);
19573dc0a89SAndreas Gohr                $sLine = implode('=' . MAILHEADER_EOL, $aMatch[0]); // add soft crlf's
19673dc0a89SAndreas Gohr            }
19773dc0a89SAndreas Gohr        }
19873dc0a89SAndreas Gohr
19973dc0a89SAndreas Gohr        // join lines into text
20073dc0a89SAndreas Gohr        return implode(MAILHEADER_EOL, $aLines);
20173dc0a89SAndreas Gohr    }
20273dc0a89SAndreas Gohr
20373dc0a89SAndreas Gohr    // endregion
20473dc0a89SAndreas Gohr}
205