diff --git a/.gitignore b/.gitignore index 622bce8..c2cb366 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,29 @@ -# Secrets -portfolio-private/smtp-config.php + +# ---- Secrets: never commit ---- +smtp-config.php .env +.env.* +*.htpasswd +.htpasswd +keys/ *.key *.pem +*.crt -# Container data (logs with visitor IPs, TLS keys, config) -config/ +# ---- Visitor data ---- *.log +log/ +logs/ +logrotate.status + +# ---- Runtime / temporary files ---- +portfolio-contact-* +*.tmp +*.swp +*~ +.DS_Store +Thumbs.db + # CVs (contain email and phone number) www/docs/*.pdf diff --git a/README.md b/README.md index 7ba29b6..c7b3229 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ePortfolio – Nelson Thomas -My personal portfolio, live at **[nelson-thomas.fr](https://nelson-thomas.fr)**. +My personal portfolio, live at **[www.nelson-thomas.fr](https://www.nelson-thomas.fr)**. I am an engineering student in Computer Science & Telecom at INP ENSEEIHT (Toulouse), on the apprenticeship track, working in networks and cybersecurity. This site is where I present who I am, what I have built and where I am heading, in one place I own and host myself. @@ -21,7 +21,8 @@ I am an engineering student in Computer Science & Telecom at INP ENSEEIHT (Toulo | **Career** | My CV in English and French, and my LinkedIn profile | | **Passions** | Self-hosting, offensive security training, photography, geopolitics | | **Civic engagement** | Volunteering and awareness actions, with hours tracked and links to the events | -| **Contact** | A form that sends messages straight to my inbox | +| **Contact** | A form that sends messages straight to my inbox, only after the visitor ticks a consent box | +| **404 page** | A custom "page not found" page in the style of the site | | **Legal notice** | A separate page, in English and French, with the publisher and hosting details and how personal data from the contact form is handled (GDPR) | ## Design choices @@ -37,6 +38,7 @@ I am an engineering student in Computer Science & Telecom at INP ENSEEIHT (Toulo ``` www/ the website itself (the only folder served publicly) portfolio-private/ configuration template and mail library for the contact form +nginx/ web server configuration of the linuxserver/nginx container (security headers, real visitor IP, masked IPs in logs, cache) ``` Secrets, server logs and CVs are deliberately kept out of this repository. diff --git a/nginx/site-confs/default.conf b/nginx/site-confs/default.conf new file mode 100644 index 0000000..71638dd --- /dev/null +++ b/nginx/site-confs/default.conf @@ -0,0 +1,90 @@ +## ePortfolio – nginx site config for the linuxserver/nginx container +## Install: copy to ./Portfolio/config/nginx/site-confs/default.conf +## then: docker exec nginx_Portfolio nginx -t && docker restart nginx_Portfolio +## Based on the image's default.conf.sample. Files in site-confs/ are included +## in the http { } block of /config/nginx/nginx.conf, so map and log_format can live here. + +# ---------- Access logs with the last part of the IP masked (see legal.html) ---------- +# 203.0.113.42 -> 203.0.113.0 | 2001:db8:abcd:12::1 -> 2001:db8:abcd:: +map $remote_addr $remote_addr_anon { + ~(?P\d+\.\d+\.\d+)\.\d+$ $ip.0; + ~(?P[^:]+:[^:]+:[^:]+): $ip::; + default 0.0.0.0; +} +log_format anon '$remote_addr_anon - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" "$http_user_agent"'; + +server { + listen 80 default_server; + listen [::]:80 default_server; + listen 443 ssl default_server; + listen [::]:443 ssl default_server; + + server_name _; + include /config/nginx/ssl.conf; + + # ---------- Real visitor IP behind Nginx Proxy Manager ---------- + # Without this, every visitor has the proxy's IP and the contact form's + # anti-spam limit (5 messages/hour/IP) would block everyone at once. + # Tighter: replace the three lines with the Docker network's subnet + # (docker network inspect proxy-portfolio | grep Subnet). + set_real_ip_from 172.16.0.0/12; + set_real_ip_from 10.0.0.0/8; + set_real_ip_from 192.168.0.0/16; + real_ip_header X-Forwarded-For; + real_ip_recursive on; + + access_log /config/log/nginx/access.log anon; + + root /config/www; + index index.html; + error_page 404 /404.html; + + # ---------- Security headers ---------- + # Everything (fonts, images, scripts, styles) is served from this domain, + # and no page uses inline styles or scripts, so the policy can be strict. + add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'; object-src 'none'" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + add_header X-Frame-Options "DENY" always; + # HSTS: Nginx Proxy Manager handles HTTPS, enable it there ("HSTS Enabled"). + + # A missing file is a real 404 (never index.html with a 200): + # otherwise a cache could store a page in place of an image. + location / { + try_files $uri $uri/ =404; + } + + # ---------- Browser cache ---------- + # "expires" does not cancel the add_header lines above (add_header would). + # CSS and JS are loaded with ?v=…: bump that number after editing them. + location ~* \.(?:css|js)$ { + expires 30d; + } + location ~* \.(?:woff2)$ { + expires 1y; + } + location ~* \.(?:png|jpe?g|svg|webp|ico)$ { + expires 7d; + } + location ~* \.(?:html|xml|txt)$ { + expires -1; # pages, sitemap, robots: always revalidated + } + + # ---------- PHP: only contact.php may run ---------- + location = /contact.php { + fastcgi_pass 127.0.0.1:9000; + include /etc/nginx/fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + client_max_body_size 32k; + } + location ~ \.php$ { + return 404; + } + + # Hidden files (.git, .htaccess, .env…), except Let's Encrypt challenges + location ~ /\.(?!well-known) { + return 404; + } +} diff --git a/portfolio-private/PHPMailer/PHPMailer.php b/portfolio-private/PHPMailer/PHPMailer.php index 2444bcf..5ccf8ff 100644 --- a/portfolio-private/PHPMailer/PHPMailer.php +++ b/portfolio-private/PHPMailer/PHPMailer.php @@ -59,6 +59,7 @@ class PHPMailer const ICAL_METHOD_REFRESH = 'REFRESH'; const ICAL_METHOD_COUNTER = 'COUNTER'; const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; + const RFC822_DATE_FORMAT = 'D, j M Y H:i:s O'; /** * Email priority. @@ -77,7 +78,7 @@ class PHPMailer public $CharSet = self::CHARSET_ISO88591; /** - * The MIME Content-type of the message. + * The MIME Content-Type of the message. * * @var string */ @@ -159,7 +160,7 @@ class PHPMailer public $Ical = ''; /** - * Value-array of "method" in Contenttype header "text/calendar" + * Value-array of "method" in Content-Type header "text/calendar" * * @var string[] */ @@ -561,9 +562,9 @@ class PHPMailer * string $body the email body * string $from email address of sender * string $extra extra information of possible use - * "smtp_transaction_id' => last smtp transaction id + * 'smtp_transaction_id' => last smtp transaction id * - * @var string + * @var callable|callable-string */ public $action_function = ''; @@ -711,7 +712,7 @@ class PHPMailer * * @var array */ - protected $language = []; + protected static $language = []; /** * The number of errors encountered. @@ -768,7 +769,7 @@ class PHPMailer * * @var string */ - const VERSION = '6.10.0'; + const VERSION = '7.1.1'; /** * Error severity: message only, continue processing. @@ -876,6 +877,7 @@ class PHPMailer private function mailPassthru($to, $subject, $body, $header, $params) { //Check overloading of mail function to avoid double-encoding + // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecatedRemoved if ((int)ini_get('mbstring.func_overload') & 1) { $subject = $this->secureHeader($subject); } else { @@ -987,6 +989,54 @@ class PHPMailer $this->Mailer = 'mail'; } + /** + * Extract sendmail path and parse to deal with known parameters. + * + * @param string $sendmailPath The sendmail path as set in php.ini + * + * @return string The sendmail path without the known parameters + */ + private function parseSendmailPath($sendmailPath) + { + $sendmailPath = trim((string)$sendmailPath); + if ($sendmailPath === '') { + return $sendmailPath; + } + + $parts = preg_split('/\s+/', $sendmailPath); + if (empty($parts)) { + return $sendmailPath; + } + + $command = array_shift($parts); + $remainder = []; + + // Parse only -t, -i, -oi and -f parameters. + for ($i = 0; $i < count($parts); ++$i) { + $part = $parts[$i]; + if (preg_match('/^-(i|oi|t)$/', $part, $matches)) { + continue; + } + if (preg_match('/^-f(.*)$/', $part, $matches)) { + $address = $matches[1]; + if ($address === '' && isset($parts[$i + 1]) && strpos($parts[$i + 1], '-') !== 0) { + $address = $parts[++$i]; + } + $this->Sender = $address; + continue; + } + + $remainder[] = $part; + } + + // The params that are not parsed are added back to the command. + if (!empty($remainder)) { + $command .= ' ' . implode(' ', $remainder); + } + + return $command; + } + /** * Send messages using $Sendmail. */ @@ -995,10 +1045,9 @@ class PHPMailer $ini_sendmail_path = ini_get('sendmail_path'); if (false === stripos($ini_sendmail_path, 'sendmail')) { - $this->Sendmail = '/usr/sbin/sendmail'; - } else { - $this->Sendmail = $ini_sendmail_path; + $ini_sendmail_path = '/usr/sbin/sendmail'; } + $this->Sendmail = $this->parseSendmailPath($ini_sendmail_path); $this->Mailer = 'sendmail'; } @@ -1010,10 +1059,9 @@ class PHPMailer $ini_sendmail_path = ini_get('sendmail_path'); if (false === stripos($ini_sendmail_path, 'qmail')) { - $this->Sendmail = '/var/qmail/bin/qmail-inject'; - } else { - $this->Sendmail = $ini_sendmail_path; + $ini_sendmail_path = '/var/qmail/bin/qmail-inject'; } + $this->Sendmail = $this->parseSendmailPath($ini_sendmail_path); $this->Mailer = 'qmail'; } @@ -1102,7 +1150,7 @@ class PHPMailer //At-sign is missing. $error_message = sprintf( '%s (%s): %s', - $this->lang('invalid_address'), + self::lang('invalid_address'), $kind, $address ); @@ -1187,7 +1235,7 @@ class PHPMailer if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { $error_message = sprintf( '%s: %s', - $this->lang('Invalid recipient kind'), + self::lang('Invalid recipient kind'), $kind ); $this->setError($error_message); @@ -1201,7 +1249,7 @@ class PHPMailer if (!static::validateAddress($address)) { $error_message = sprintf( '%s (%s): %s', - $this->lang('invalid_address'), + self::lang('invalid_address'), $kind, $address ); @@ -1220,56 +1268,62 @@ class PHPMailer return true; } - } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { - $this->ReplyTo[strtolower($address)] = [$address, $name]; + } else { + foreach ($this->ReplyTo as $replyTo) { + if (0 === strcasecmp($replyTo[0], $address)) { + return false; + } + } + $this->ReplyTo[] = [$address, $name]; return true; } - return false; } /** * Parse and validate a string containing one or more RFC822-style comma-separated email addresses * of the form "display name
" into an array of name/address pairs. - * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. + * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available and + * the deprecated $useimap argument is truthy. * Note that quotes in the name part are removed. * + * @deprecated This method will be removed in the next major release of PHPMailer. * @see https://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation * * @param string $addrstr The address list string - * @param bool $useimap Whether to use the IMAP extension to parse the list + * @param bool|null $useimap Deprecated in PHPMailer 6.11.0. + * Truthy values request the deprecated IMAP parser + * and trigger a deprecation warning. * @param string $charset The charset to use when decoding the address list string. * * @return array */ - public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591) + public static function parseAddresses($addrstr, $useimap = null, $charset = self::CHARSET_ISO88591) { + if ($useimap) { + trigger_error(self::lang('deprecated_argument') . '$useimap', E_USER_DEPRECATED); + } $addresses = []; - if ($useimap && function_exists('imap_rfc822_parse_adrlist')) { + if ($useimap !== false && function_exists('imap_rfc822_parse_adrlist')) { //Use this built-in parser if it's available + // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.imap_rfc822_parse_adrlistRemoved -- wrapped in function_exists() $list = imap_rfc822_parse_adrlist($addrstr, ''); // Clear any potential IMAP errors to get rid of notices being thrown at end of script. + // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.imap_errorsRemoved -- wrapped in function_exists() imap_errors(); foreach ($list as $address) { if ( '.SYNTAX-ERROR.' !== $address->host && static::validateAddress($address->mailbox . '@' . $address->host) ) { - //Decode the name part if it's present and encoded + //Decode the name part if it's present and maybe encoded if ( - property_exists($address, 'personal') && - //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled - defined('MB_CASE_UPPER') && - preg_match('/^=\?.*\?=$/s', $address->personal) + property_exists($address, 'personal') + && is_string($address->personal) + && $address->personal !== '' ) { - $origCharset = mb_internal_encoding(); - mb_internal_encoding($charset); - //Undo any RFC2047-encoded spaces-as-underscores - $address->personal = str_replace('_', '=20', $address->personal); - //Decode the name - $address->personal = mb_decode_mimeheader($address->personal); - mb_internal_encoding($origCharset); + $address->personal = static::decodeHeader($address->personal, $charset); } $addresses[] = [ @@ -1280,40 +1334,51 @@ class PHPMailer } } else { //Use this simpler parser - $list = explode(',', $addrstr); - foreach ($list as $address) { - $address = trim($address); - //Is there a separate name part? - if (strpos($address, '<') === false) { - //No separate name, just use the whole thing - if (static::validateAddress($address)) { - $addresses[] = [ - 'name' => '', - 'address' => $address, - ]; - } - } else { - list($name, $email) = explode('<', $address); - $email = trim(str_replace('>', '', $email)); - $name = trim($name); - if (static::validateAddress($email)) { - //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled - //If this name is encoded, decode it - if (defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $name)) { - $origCharset = mb_internal_encoding(); - mb_internal_encoding($charset); - //Undo any RFC2047-encoded spaces-as-underscores - $name = str_replace('_', '=20', $name); - //Decode the name - $name = mb_decode_mimeheader($name); - mb_internal_encoding($origCharset); - } - $addresses[] = [ - //Remove any surrounding quotes and spaces from the name - 'name' => trim($name, '\'" '), - 'address' => $email, - ]; - } + $addresses = static::parseSimplerAddresses($addrstr, $charset); + } + + return $addresses; + } + + /** + * Parse a string containing one or more RFC822-style comma-separated email addresses + * with the form "display name
" into an array of name/address pairs. + * Uses a simpler parser that does not require the IMAP extension but doesnt support + * the full RFC822 spec. For full RFC822 support, use the PHP IMAP extension. + * + * @param string $addrstr The address list string + * @param string $charset The charset to use when decoding the address list string. + * + * @return array + */ + protected static function parseSimplerAddresses($addrstr, $charset) + { + // Emit a runtime notice to recommend using the IMAP extension for full RFC822 parsing + trigger_error(self::lang('imap_recommended'), E_USER_NOTICE); + + $addresses = []; + $list = explode(',', $addrstr); + foreach ($list as $address) { + $address = trim($address); + //Is there a separate name part? + if (strpos($address, '<') === false) { + //No separate name, just use the whole thing + if (static::validateAddress($address)) { + $addresses[] = [ + 'name' => '', + 'address' => $address, + ]; + } + } else { + $parsed = static::parseEmailString($address); + $email = $parsed['email']; + if (static::validateAddress($email)) { + $name = static::decodeHeader($parsed['name'], $charset); + $addresses[] = [ + //Remove any surrounding quotes and spaces from the name + 'name' => trim($name, '\'" '), + 'address' => $email, + ]; } } } @@ -1321,6 +1386,42 @@ class PHPMailer return $addresses; } + /** + * Parse a string containing an email address with an optional name + * and divide it into a name and email address. + * + * @param string $input The email with name. + * + * @return array{name: string, email: string} + */ + private static function parseEmailString($input) + { + $input = trim((string)$input); + + if ($input === '') { + return ['name' => '', 'email' => '']; + } + + $pattern = '/^\s*(?:(?:"([^"]*)"|\'([^\']*)\'|([^<]*?))\s*)?<\s*([^>]+)\s*>\s*$/'; + if (preg_match($pattern, $input, $matches)) { + $name = ''; + // Double quotes including special scenarios. + if (isset($matches[1]) && $matches[1] !== '') { + $name = $matches[1]; + // Single quotes including special scenarios. + } elseif (isset($matches[2]) && $matches[2] !== '') { + $name = $matches[2]; + // Simplest scenario, name and email are in the format "Name ". + } elseif (isset($matches[3])) { + $name = trim($matches[3]); + } + + return ['name' => $name, 'email' => trim($matches[4])]; + } + + return ['name' => '', 'email' => $input]; + } + /** * Set the From and FromName properties. * @@ -1334,6 +1435,10 @@ class PHPMailer */ public function setFrom($address, $name = '', $auto = true) { + if (is_null($name)) { + //Helps avoid a deprecation warning in the preg_replace() below + $name = ''; + } $address = trim((string)$address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim //Don't validate now addresses with IDN. Will be done in send(). @@ -1345,7 +1450,7 @@ class PHPMailer ) { $error_message = sprintf( '%s (From): %s', - $this->lang('invalid_address'), + self::lang('invalid_address'), $address ); $this->setError($error_message); @@ -1532,9 +1637,11 @@ class PHPMailer ); } elseif (defined('INTL_IDNA_VARIANT_2003')) { //Fall back to this old, deprecated/removed encoding + // phpcs:ignore PHPCompatibility.Constants.RemovedConstants.intl_idna_variant_2003DeprecatedRemoved $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); } else { //Fall back to a default we don't know about + // phpcs:ignore PHPCompatibility.ParameterValues.NewIDNVariantDefault.NotSet $punycode = idn_to_ascii($domain, $errorcode); } if (false !== $punycode) { @@ -1601,7 +1708,7 @@ class PHPMailer && ini_get('mail.add_x_header') === '1' && stripos(PHP_OS, 'WIN') === 0 ) { - trigger_error($this->lang('buggy_php'), E_USER_WARNING); + trigger_error(self::lang('buggy_php'), E_USER_WARNING); } try { @@ -1631,7 +1738,7 @@ class PHPMailer call_user_func_array([$this, 'addAnAddress'], $params); } if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { - throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); + throw new Exception(self::lang('provide_address'), self::STOP_CRITICAL); } //Validate From, Sender, and ConfirmReadingTo addresses @@ -1648,7 +1755,7 @@ class PHPMailer if (!static::validateAddress($this->{$address_kind})) { $error_message = sprintf( '%s (%s): %s', - $this->lang('invalid_address'), + self::lang('invalid_address'), $address_kind, $this->{$address_kind} ); @@ -1670,11 +1777,13 @@ class PHPMailer $this->setMessageType(); //Refuse to send an empty message unless we are specifically allowing it if (!$this->AllowEmpty && empty($this->Body)) { - throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); + throw new Exception(self::lang('empty_message'), self::STOP_CRITICAL); } //Trim subject consistently $this->Subject = trim($this->Subject); + + //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) $this->MIMEHeader = ''; $this->MIMEBody = $this->createBody(); @@ -1749,7 +1858,7 @@ class PHPMailer return $this->mailSend($this->MIMEHeader, $this->MIMEBody); default: $sendMethod = $this->Mailer . 'Send'; - if (method_exists($this, $sendMethod)) { + if (!empty($this->Mailer) && method_exists($this, $sendMethod)) { return $this->{$sendMethod}($this->MIMEHeader, $this->MIMEBody); } @@ -1802,23 +1911,27 @@ class PHPMailer //PHP config has a sender address we can use $this->Sender = ini_get('sendmail_from'); } - //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + + $sendmailArgs = []; + + // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + // Also don't add the -f automatically unless it has been set either via Sender + // or sendmail_path. Otherwise, it can introduce new problems. + // @see http://github.com/PHPMailer/PHPMailer/issues/2298 if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { - if ($this->Mailer === 'qmail') { - $sendmailFmt = '%s -f%s'; - } else { - $sendmailFmt = '%s -oi -f%s -t'; - } - } else { - //allow sendmail to choose a default envelope sender. It may - //seem preferable to force it to use the From header as with - //SMTP, but that introduces new problems (see - //), and - //it has historically worked this way. - $sendmailFmt = '%s -oi -t'; + $sendmailArgs[] = '-f' . $this->Sender; } - $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); + // Qmail doesn't accept all the sendmail parameters + // @see https://github.com/PHPMailer/PHPMailer/issues/3189 + if ($this->Mailer !== 'qmail') { + $sendmailArgs[] = '-i'; + $sendmailArgs[] = '-t'; + } + + $resultArgs = (empty($sendmailArgs) ? '' : ' ' . implode(' ', $sendmailArgs)); + + $sendmail = trim(escapeshellcmd($this->Sendmail) . $resultArgs); $this->edebug('Sendmail path: ' . $this->Sendmail); $this->edebug('Sendmail command: ' . $sendmail); $this->edebug('Envelope sender: ' . $this->Sender); @@ -1828,33 +1941,35 @@ class PHPMailer foreach ($this->SingleToArray as $toAddr) { $mail = @popen($sendmail, 'w'); if (!$mail) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } $this->edebug("To: {$toAddr}"); fwrite($mail, 'To: ' . $toAddr . "\n"); fwrite($mail, $header); fwrite($mail, $body); $result = pclose($mail); - $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet); - $this->doCallback( - ($result === 0), - [[$addrinfo['address'], $addrinfo['name']]], - $this->cc, - $this->bcc, - $this->Subject, - $body, - $this->From, - [] - ); + $addrinfo = static::parseAddresses($toAddr, null, $this->CharSet); + foreach ($addrinfo as $addr) { + $this->doCallback( + ($result === 0), + [[$addr['address'], $addr['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + } $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); if (0 !== $result) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } } else { $mail = @popen($sendmail, 'w'); if (!$mail) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fwrite($mail, $header); fwrite($mail, $body); @@ -1871,7 +1986,7 @@ class PHPMailer ); $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); if (0 !== $result) { - throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } @@ -2000,7 +2115,8 @@ class PHPMailer $this->Sender = ini_get('sendmail_from'); } if (!empty($this->Sender) && static::validateAddress($this->Sender)) { - if (self::isShellSafe($this->Sender)) { + $phpmailer_path = ini_get('sendmail_path'); + if (self::isShellSafe($this->Sender) && strpos($phpmailer_path, ' -f') === false) { $params = sprintf('-f%s', $this->Sender); } $old_from = ini_get('sendmail_from'); @@ -2010,17 +2126,19 @@ class PHPMailer if ($this->SingleTo && count($toArr) > 1) { foreach ($toArr as $toAddr) { $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); - $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet); - $this->doCallback( - $result, - [[$addrinfo['address'], $addrinfo['name']]], - $this->cc, - $this->bcc, - $this->Subject, - $body, - $this->From, - [] - ); + $addrinfo = static::parseAddresses($toAddr, null, $this->CharSet); + foreach ($addrinfo as $addr) { + $this->doCallback( + $result, + [[$addr['address'], $addr['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + } } } else { $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); @@ -2030,7 +2148,7 @@ class PHPMailer ini_set('sendmail_from', $old_from); } if (!$result) { - throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); + throw new Exception(self::lang('instantiate'), self::STOP_CRITICAL); } return true; @@ -2116,12 +2234,12 @@ class PHPMailer $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; $bad_rcpt = []; if (!$this->smtpConnect($this->SMTPOptions)) { - throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); + throw new Exception(self::lang('smtp_connect_failed'), self::STOP_CRITICAL); } //If we have recipient addresses that need Unicode support, //but the server doesn't support it, stop here if ($this->UseSMTPUTF8 && !$this->smtp->getServerExt('SMTPUTF8')) { - throw new Exception($this->lang('no_smtputf8'), self::STOP_CRITICAL); + throw new Exception(self::lang('no_smtputf8'), self::STOP_CRITICAL); } //Sender already validated in preSend() if ('' === $this->Sender) { @@ -2133,7 +2251,7 @@ class PHPMailer $this->smtp->xclient($this->SMTPXClient); } if (!$this->smtp->mail($smtp_from)) { - $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + $this->setError(self::lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); } @@ -2155,7 +2273,7 @@ class PHPMailer //Only send the DATA command if we have viable recipients if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { - throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); + throw new Exception(self::lang('data_not_accepted'), self::STOP_CRITICAL); } $smtp_transaction_id = $this->smtp->getLastTransactionID(); @@ -2186,7 +2304,7 @@ class PHPMailer foreach ($bad_rcpt as $bad) { $errstr .= $bad['to'] . ': ' . $bad['error']; } - throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); + throw new Exception(self::lang('recipients_failed') . $errstr, self::STOP_CONTINUE); } return true; @@ -2240,7 +2358,7 @@ class PHPMailer $hostinfo ) ) { - $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); + $this->edebug(self::lang('invalid_hostentry') . ' ' . trim($hostentry)); //Not a valid host entry continue; } @@ -2252,7 +2370,7 @@ class PHPMailer //Check the host name is a valid name or IP address before trying to use it if (!static::isValidHost($hostinfo[2])) { - $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); + $this->edebug(self::lang('invalid_host') . ' ' . $hostinfo[2]); continue; } $prefix = ''; @@ -2272,7 +2390,7 @@ class PHPMailer if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled if (!$sslext) { - throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); + throw new Exception(self::lang('extension_missing') . 'openssl', self::STOP_CRITICAL); } } $host = $hostinfo[2]; @@ -2324,7 +2442,7 @@ class PHPMailer $this->oauth ) ) { - throw new Exception($this->lang('authenticate')); + throw new Exception(self::lang('authenticate')); } return true; @@ -2374,7 +2492,7 @@ class PHPMailer * * @return bool Returns true if the requested language was loaded, false otherwise. */ - public function setLanguage($langcode = 'en', $lang_path = '') + public static function setLanguage($langcode = 'en', $lang_path = '') { //Backwards compatibility for renamed language codes $renamed_langcodes = [ @@ -2397,7 +2515,7 @@ class PHPMailer 'authenticate' => 'SMTP Error: Could not authenticate.', 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' . ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . - ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', + ' your php.ini, switch to macOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'data_not_accepted' => 'SMTP Error: data not accepted.', 'empty_message' => 'Message body empty', @@ -2423,6 +2541,9 @@ class PHPMailer 'smtp_error' => 'SMTP server error: ', 'variable_set' => 'Cannot set or reset variable: ', 'no_smtputf8' => 'Server does not support SMTPUTF8 needed to send to Unicode addresses', + 'imap_recommended' => 'Using simplified address parser is not recommended. ' . + 'Install the PHP IMAP extension for full RFC822 parsing.', + 'deprecated_argument' => 'Deprecated Argument: ', ]; if (empty($lang_path)) { //Calculate an absolute path so it can work if CWD is not here @@ -2489,7 +2610,7 @@ class PHPMailer } } } - $this->language = $PHPMAILER_LANG; + self::$language = $PHPMAILER_LANG; return $foundlang; //Returns false if language not found } @@ -2501,11 +2622,11 @@ class PHPMailer */ public function getTranslations() { - if (empty($this->language)) { - $this->setLanguage(); // Set the default language. + if (empty(self::$language)) { + self::setLanguage(); // Set the default language. } - return $this->language; + return self::$language; } /** @@ -2526,7 +2647,22 @@ class PHPMailer $addresses[] = $this->addrFormat($address); } - return $type . ': ' . implode(', ', $addresses) . static::$LE; + //Fold between addresses so that no line exceeds the RFC 2822 line length limit + $header = $type . ': ' . array_shift($addresses); + $lineLength = strlen($header); + foreach ($addresses as $address) { + //The address goes after ', ' and must still leave room for the ',' that ends + //the line if the next address gets folded + if ($lineLength + strlen(', ') + strlen($address) + strlen(',') > static::MAX_LINE_LENGTH) { + $header .= ',' . static::$LE . ' ' . $address; + $lineLength = strlen(' ') + strlen($address); + } else { + $header .= ', ' . $address; + $lineLength += strlen(', ') + strlen($address); + } + } + + return $header . static::$LE; } /** @@ -2731,7 +2867,10 @@ class PHPMailer { $result = ''; - $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate); + $result .= $this->headerLine( + 'Date', + self::sanitiseDate($this->MessageDate) + ); //The To header is created automatically by mail(), so needs to be omitted here if ('mail' !== $this->Mailer) { @@ -2800,7 +2939,7 @@ class PHPMailer ); } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') { //Some string - $result .= $this->headerLine('X-Mailer', trim($this->XMailer)); + $result .= $this->headerLine('X-Mailer', $this->secureHeader(trim($this->XMailer))); } //Other values result in no X-Mailer header if ('' !== $this->ConfirmReadingTo) { @@ -2850,13 +2989,20 @@ class PHPMailer break; default: //Catches case 'plain': and case '': - $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); + $result .= $this->textLine( + 'Content-Type: ' . + $this->secureHeader($this->ContentType) . + '; charset=' . $this->secureHeader($this->CharSet) + ); $ismultipart = false; break; } + if (!$this->validateEncoding($this->Encoding)) { + throw new Exception(self::lang('encoding') . $this->Encoding); + } //RFC1341 part 5 says 7bit is assumed if not specified if (static::ENCODING_7BIT !== $this->Encoding) { - //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE + //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit, or binary CTE if ($ismultipart) { if (static::ENCODING_8BIT === $this->Encoding) { $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT); @@ -2896,6 +3042,7 @@ class PHPMailer $bytes = ''; if (function_exists('random_bytes')) { try { + // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.random_bytesFound -- Wrapped in function_exists. $bytes = random_bytes($len); } catch (\Exception $e) { //Do nothing @@ -2928,12 +3075,11 @@ class PHPMailer //Create unique IDs and preset boundaries $this->setBoundaries(); - if ($this->sign_key_file) { - $body .= $this->getMailMIME() . static::$LE; - } - $this->setWordWrap(); + if (!$this->validateEncoding($this->Encoding)) { + throw new Exception(self::lang('encoding') . $this->Encoding); + } $bodyEncoding = $this->Encoding; $bodyCharSet = $this->CharSet; //Can we do a 7-bit downgrade? @@ -2963,6 +3109,12 @@ class PHPMailer if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) { $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE; } + + if ($this->sign_key_file) { + $this->Encoding = $bodyEncoding; + $body .= $this->getMailMIME() . static::$LE; + } + //Use this as a preamble in all multipart message types $mimepre = ''; switch ($this->message_type) { @@ -3144,12 +3296,12 @@ class PHPMailer if ($this->isError()) { $body = ''; if ($this->exceptions) { - throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); + throw new Exception(self::lang('empty_message'), self::STOP_CRITICAL); } } elseif ($this->sign_key_file) { try { if (!defined('PKCS7_TEXT')) { - throw new Exception($this->lang('extension_missing') . 'openssl'); + throw new Exception(self::lang('extension_missing') . 'openssl'); } $file = tempnam(sys_get_temp_dir(), 'srcsign'); @@ -3183,11 +3335,12 @@ class PHPMailer @unlink($signed); //The message returned by openssl contains both headers and body, so need to split them up $parts = explode("\n\n", $body, 2); - $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE; - $body = $parts[1]; + //openssl emits bare LF breaks, which SMTP servers may reject + $this->MIMEHeader .= static::normalizeBreaks($parts[0]) . static::$LE . static::$LE; + $body = static::normalizeBreaks($parts[1]); } else { @unlink($signed); - throw new Exception($this->lang('signing') . openssl_error_string()); + throw new Exception(self::lang('signing') . openssl_error_string()); } } catch (Exception $exc) { $body = ''; @@ -3332,7 +3485,7 @@ class PHPMailer ) { try { if (!static::fileIsAccessible($path)) { - throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); + throw new Exception(self::lang('file_access') . $path, self::STOP_CONTINUE); } //If a MIME type is not specified, try to work it out from the file name @@ -3345,7 +3498,7 @@ class PHPMailer $name = $filename; } if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); + throw new Exception(self::lang('encoding') . $encoding); } $this->attachment[] = [ @@ -3506,11 +3659,11 @@ class PHPMailer { try { if (!static::fileIsAccessible($path)) { - throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); + throw new Exception(self::lang('file_open') . $path, self::STOP_CONTINUE); } $file_buffer = file_get_contents($path); if (false === $file_buffer) { - throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); + throw new Exception(self::lang('file_open') . $path, self::STOP_CONTINUE); } $file_buffer = $this->encodeString($file_buffer, $encoding); @@ -3563,9 +3716,9 @@ class PHPMailer $encoded = $this->encodeQP($str); break; default: - $this->setError($this->lang('encoding') . $encoding); + $this->setError(self::lang('encoding') . $encoding); if ($this->exceptions) { - throw new Exception($this->lang('encoding') . $encoding); + throw new Exception(self::lang('encoding') . $encoding); } break; } @@ -3671,6 +3824,42 @@ class PHPMailer return trim(static::normalizeBreaks($encoded)); } + /** + * Decode an RFC2047-encoded header value + * Attempts multiple strategies so it works even when the mbstring extension is disabled. + * + * @param string $value The header value to decode + * @param string $charset The target charset to convert to, defaults to ISO-8859-1 for BC + * + * @return string The decoded header value + */ + public static function decodeHeader($value, $charset = self::CHARSET_ISO88591) + { + if (!is_string($value) || $value === '') { + return ''; + } + // Detect the presence of any RFC2047 encoded-words + $hasEncodedWord = (bool) preg_match('/=\?.*\?=/s', $value); + if ($hasEncodedWord && defined('MB_CASE_UPPER')) { + $origCharset = mb_internal_encoding(); + // Always decode to UTF-8 to provide a consistent, modern output encoding. + mb_internal_encoding($charset); + if (PHP_VERSION_ID < 80300) { + // Undo any RFC2047-encoded spaces-as-underscores. + $value = str_replace('_', '=20', $value); + } else { + // PHP 8.3+ already interprets underscores as spaces. Remove additional + // linear whitespace between adjacent encoded words to avoid double spacing. + $value = preg_replace('/(\?=)\s+(=\?)/', '$1$2', $value); + } + // Decode the header value + $value = mb_decode_mimeheader($value); + mb_internal_encoding($origCharset); + } + + return $value; + } + /** * Check if a string contains multi-byte characters. * @@ -3840,7 +4029,7 @@ class PHPMailer } if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); + throw new Exception(self::lang('encoding') . $encoding); } //Append to $attachment array @@ -3899,7 +4088,7 @@ class PHPMailer ) { try { if (!static::fileIsAccessible($path)) { - throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); + throw new Exception(self::lang('file_access') . $path, self::STOP_CONTINUE); } //If a MIME type is not specified, try to work it out from the file name @@ -3908,7 +4097,7 @@ class PHPMailer } if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); + throw new Exception(self::lang('encoding') . $encoding); } $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); @@ -3974,7 +4163,7 @@ class PHPMailer } if (!$this->validateEncoding($encoding)) { - throw new Exception($this->lang('encoding') . $encoding); + throw new Exception(self::lang('encoding') . $encoding); } //Append to $attachment array @@ -4011,7 +4200,7 @@ class PHPMailer protected function validateEncoding($encoding) { return in_array( - $encoding, + strtolower($encoding), [ self::ENCODING_7BIT, self::ENCODING_QUOTED_PRINTABLE, @@ -4231,7 +4420,7 @@ class PHPMailer } if (strpbrk($name . $value, "\r\n") !== false) { if ($this->exceptions) { - throw new Exception($this->lang('invalid_header')); + throw new Exception(self::lang('invalid_header')); } return false; @@ -4255,15 +4444,15 @@ class PHPMailer if ('smtp' === $this->Mailer && null !== $this->smtp) { $lasterror = $this->smtp->getError(); if (!empty($lasterror['error'])) { - $msg .= ' ' . $this->lang('smtp_error') . $lasterror['error']; + $msg .= ' ' . self::lang('smtp_error') . $lasterror['error']; if (!empty($lasterror['detail'])) { - $msg .= ' ' . $this->lang('smtp_detail') . $lasterror['detail']; + $msg .= ' ' . self::lang('smtp_detail') . $lasterror['detail']; } if (!empty($lasterror['smtp_code'])) { - $msg .= ' ' . $this->lang('smtp_code') . $lasterror['smtp_code']; + $msg .= ' ' . self::lang('smtp_code') . $lasterror['smtp_code']; } if (!empty($lasterror['smtp_code_ex'])) { - $msg .= ' ' . $this->lang('smtp_code_ex') . $lasterror['smtp_code_ex']; + $msg .= ' ' . self::lang('smtp_code_ex') . $lasterror['smtp_code_ex']; } } } @@ -4271,7 +4460,7 @@ class PHPMailer } /** - * Return an RFC 822 formatted date. + * Return the current date and time as an RFC 822 formatted date. * * @return string */ @@ -4281,7 +4470,51 @@ class PHPMailer //Will default to UTC if it's not set properly in php.ini date_default_timezone_set(@date_default_timezone_get()); - return date('D, j M Y H:i:s O'); + return date(self::RFC822_DATE_FORMAT); + } + + /** + * Normalise a user-supplied date into a correctly-formatted RFC 5322 date value + * string suitable for use in the Date header. + * + * Accepts: + * - A {@see \DateTime} (or \DateTimeImmutable) object + * - Any date/time string understood by PHP's DateTime constructor (RFC 5322, ISO 8601, + * Unix timestamp with leading "@", natural-language strings, etc.) + * + * Dates in the future are not permitted for email headers; if the parsed date is later + * than "now" the method falls back to the current time via {@see self::rfcDate()}. + * An empty value, a non-string/non-DateTime argument, or any value that cannot be + * parsed will likewise fall back to {@see self::rfcDate()}. + * + * @param \DateTime|\DateTimeImmutable|string $date The date to normalise + * + * @return string An RFC 5322-formatted date string + */ + private static function sanitiseDate($date) + { + try { + //Ensure the default timezone is set properly + date_default_timezone_set(@date_default_timezone_get()); + + if ($date instanceof \DateTimeInterface) { + $dt = $date; + } elseif (is_string($date) && $date !== '') { + $dt = new \DateTime($date); + } else { + //Empty string, null, or any unsupported type + return self::rfcDate(); + } + + //Reject future dates — they are invalid for outgoing message headers + if ($dt->getTimestamp() > time()) { + return self::rfcDate(); + } + + return $dt->format(self::RFC822_DATE_FORMAT); + } catch (\Exception $e) { + return self::rfcDate(); + } } /** @@ -4388,21 +4621,21 @@ class PHPMailer * * @return string */ - protected function lang($key) + protected static function lang($key) { - if (count($this->language) < 1) { - $this->setLanguage(); //Set the default language + if (count(self::$language) < 1) { + self::setLanguage(); //Set the default language } - if (array_key_exists($key, $this->language)) { + if (array_key_exists($key, self::$language)) { if ('smtp_connect_failed' === $key) { //Include a link to troubleshooting docs on SMTP connection failure. //This is by far the biggest cause of support questions //but it's usually not PHPMailer's fault. - return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; + return self::$language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; } - return $this->language[$key]; + return self::$language[$key]; } //Return the key as a fallback @@ -4417,7 +4650,7 @@ class PHPMailer */ private function getSmtpErrorMessage($base_key) { - $message = $this->lang($base_key); + $message = self::lang($base_key); $error = $this->smtp->getError(); if (!empty($error['error'])) { $message .= ' ' . $error['error']; @@ -4461,7 +4694,7 @@ class PHPMailer //Ensure name is not empty, and that neither name nor value contain line breaks if (empty($name) || strpbrk($name . $value, "\r\n") !== false) { if ($this->exceptions) { - throw new Exception($this->lang('invalid_header')); + throw new Exception(self::lang('invalid_header')); } return false; @@ -4492,10 +4725,10 @@ class PHPMailer * Converts data-uri images into embedded attachments. * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. * - * @param string $message HTML message string - * @param string $basedir Absolute path to a base directory to prepend to relative paths to images - * @param bool|callable $advanced Whether to use the internal HTML to text converter - * or your own custom converter + * @param string $message HTML message string + * @param string $basedir Absolute path to a base directory to prepend to relative paths to images + * @param bool|callable $advanced Whether to use the internal HTML to text converter + * or your own custom converter * @return string The transformed message body * * @throws Exception @@ -4504,6 +4737,12 @@ class PHPMailer */ public function msgHTML($message, $basedir = '', $advanced = false) { + $cid_domain = 'phpmailer.0'; + if (filter_var($this->From, FILTER_VALIDATE_EMAIL)) { + //prepend with a character to create valid RFC822 string in order to validate + $cid_domain = substr($this->From, strrpos($this->From, '@') + 1); + } + preg_match_all('/(? 1 && '/' !== substr($basedir, -1)) { @@ -4525,7 +4764,7 @@ class PHPMailer } //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places //will only be embedded once, even if it used a different encoding - $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2 + $cid = substr(hash('sha256', $data), 0, 32) . '@' . $cid_domain; //RFC2392 S 2 if (!$this->cidExists($cid)) { $this->addStringEmbeddedImage( @@ -4559,7 +4798,7 @@ class PHPMailer $directory = ''; } //RFC2392 S 2 - $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0'; + $cid = substr(hash('sha256', $url), 0, 32) . '@' . $cid_domain; if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { $basedir .= '/'; } @@ -4854,7 +5093,7 @@ class PHPMailer return true; } - $this->setError($this->lang('variable_set') . $name); + $this->setError(self::lang('variable_set') . $name); return false; } @@ -4992,7 +5231,7 @@ class PHPMailer { if (!defined('PKCS7_TEXT')) { if ($this->exceptions) { - throw new Exception($this->lang('extension_missing') . 'openssl'); + throw new Exception(self::lang('extension_missing') . 'openssl'); } return ''; @@ -5007,12 +5246,14 @@ class PHPMailer } if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { if (\PHP_MAJOR_VERSION < 8) { + // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.openssl_pkey_freeDeprecated openssl_pkey_free($privKey); } return base64_encode($signature); } if (\PHP_MAJOR_VERSION < 8) { + // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.openssl_pkey_freeDeprecated openssl_pkey_free($privKey); } diff --git a/portfolio-private/PHPMailer/SMTP.php b/portfolio-private/PHPMailer/SMTP.php index 7226ee9..f9dc747 100644 --- a/portfolio-private/PHPMailer/SMTP.php +++ b/portfolio-private/PHPMailer/SMTP.php @@ -34,8 +34,9 @@ class SMTP * The PHPMailer SMTP version number. * * @var string + * @deprecated This constant will be removed in PHPMailer 8.0. Use `PHPMailer::VERSION` instead. */ - const VERSION = '6.10.0'; + const VERSION = '7.1.1'; /** * SMTP line break constant. @@ -205,6 +206,7 @@ class SMTP 'Haraka' => '/[\d]{3} Message Queued \((.*)\)/', 'ZoneMTA' => '/[\d]{3} Message queued as (.*)/', 'Mailjet' => '/[\d]{3} OK queued as (.*)/', + 'Gsmtp' => '/[\d]{3} 2\.0\.0 OK (.*) - gsmtp/', ]; /** @@ -273,6 +275,14 @@ class SMTP */ protected $last_reply = ''; + /** + * The last command sent to the server. + * Used to avoid sending QUIT while a DATA command is still in progress. + * + * @var string + */ + protected $state = ''; + /** * Output debugging info via a user-selected method. * @@ -493,7 +503,9 @@ class SMTP //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT //so add them back in manually if we can if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { + // phpcs:ignore PHPCompatibility.Constants.NewConstants.stream_crypto_method_tlsv1_2_clientFound $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + // phpcs:ignore PHPCompatibility.Constants.NewConstants.stream_crypto_method_tlsv1_1_clientFound $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; } @@ -632,11 +644,49 @@ class SMTP if (null === $OAuth) { return false; } - $oauth = $OAuth->getOauth64(); - - //Start authentication - if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { - return false; + try { + $oauth = $OAuth->getOauth64(); + } catch (\Exception $e) { + // We catch all exceptions and convert them to PHPMailer exceptions to be able to + // handle them correctly later + throw new Exception("SMTP authentication error", 0, $e); + } + /* + * An SMTP command line can have a maximum length of 512 bytes, including the command name, + * so the base64-encoded OAUTH token has a maximum length of: + * 512 - 13 (AUTH XOAUTH2) - 2 (CRLF) = 497 bytes + * If the token is longer than that, the command and the token must be sent separately as described in + * https://www.rfc-editor.org/rfc/rfc4954#section-4 + */ + if ($oauth === '') { + //Sending an empty auth token is legitimate, but it must be encoded as '=' + //to indicate it's not a 2-part command + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 =', 235)) { + return false; + } + } elseif (strlen($oauth) <= 497) { + //Authenticate using a token in the initial-response part + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { + return false; + } + } else { + //The token is too long, so we need to send it in two parts. + //Send the auth command without a token and expect a 334 + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2', 334)) { + return false; + } + //Send the token + if (!$this->sendCommand('OAuth TOKEN', $oauth, [235, 334])) { + return false; + } + //If the server answers with 334, send an empty line + //a reply other than a 235 means the authentication failed, so we don't need to send anything else + if ( + strpos($this->last_reply, '334') === 0 + && !$this->sendCommand('AUTH End', '', 235) + ) { + return false; + } } break; default: @@ -721,6 +771,7 @@ class SMTP { $this->server_caps = null; $this->helo_rply = null; + $this->state = ''; if (is_resource($this->smtp_conn)) { //Close the connection and cleanup fclose($this->smtp_conn); @@ -729,6 +780,25 @@ class SMTP } } + private function iterateLines($s) + { + $start = 0; + $length = strlen($s); + + for ($i = 0; $i < $length; $i++) { + $c = $s[$i]; + if ($c === "\n" || $c === "\r") { + yield substr($s, $start, $i - $start); + if ($c === "\r" && $i + 1 < $length && $s[$i + 1] === "\n") { + $i++; + } + $start = $i + 1; + } + } + + yield substr($s, $start); + } + /** * Send an SMTP DATA command. * Issues a data command and sends the msg_data to the server, @@ -757,15 +827,16 @@ class SMTP * NOTE: this does not count towards line-length limit. */ - //Normalize line breaks before exploding - $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data)); + //Iterate over lines with normalized line breaks + $lines = $this->iterateLines($msg_data); /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field * of the first line (':' separated) does not contain a space then it _should_ be a header, and we will * process all lines before a blank line as headers. */ - $field = substr($lines[0], 0, strpos($lines[0], ':')); + $first_line = $lines->current(); + $field = substr($first_line, 0, strpos($first_line, ':')); $in_headers = false; if (!empty($field) && strpos($field, ' ') === false) { $in_headers = true; @@ -959,7 +1030,12 @@ class SMTP */ public function quit($close_on_error = true) { - $noerror = $this->sendCommand('QUIT', 'QUIT', 221); + if ($this->state === 'DATA') { + //The server would take QUIT as part of an unfinished message, so just close the connection + $noerror = true; + } else { + $noerror = $this->sendCommand('QUIT', 'QUIT', 221); + } $err = $this->error; //Save any error if ($noerror || $close_on_error) { $this->close(); @@ -1062,6 +1138,7 @@ class SMTP return false; } + $this->state = $command; $this->client_send($commandstring . static::LE, $command); $this->last_reply = $this->get_lines(); @@ -1228,7 +1305,7 @@ class SMTP * 3. EHLO has been sent - * $name == 'HELO'|'EHLO': returns the server name * $name == any other string: if extension $name exists, returns True - * or its options (e.g. AUTH mechanisms supported). Otherwise returns False. + * or its options (e.g. AUTH mechanisms supported). Otherwise, returns False. * * @param string $name Name of SMTP extension or 'HELO'|'EHLO' * @@ -1309,7 +1386,16 @@ class SMTP //stream_select returns false when the `select` system call is interrupted //by an incoming signal, try the select again - if (stripos($message, 'interrupted system call') !== false) { + if ( + stripos($message, 'interrupted system call') !== false || + ( + // on applications with a different locale than english, the message above is not found because + // it's translated. So we also check for the SOCKET_EINTR constant which is defined under + // Windows and UNIX-like platforms (if available on the platform). + defined('SOCKET_EINTR') && + stripos($message, 'stream_select(): Unable to select [' . SOCKET_EINTR . ']') !== false + ) + ) { $this->edebug( 'SMTP -> get_lines(): retrying stream_select', self::DEBUG_LOWLEVEL diff --git a/portfolio-private/smtp-config.example.php b/portfolio-private/smtp-config.example.php index f525058..2f34984 100644 --- a/portfolio-private/smtp-config.example.php +++ b/portfolio-private/smtp-config.example.php @@ -14,13 +14,13 @@ return [ // (Proton: Settings > All settings > Proton Mail > IMAP/SMTP > SMTP tokens). // A @proton.me / @pm.me address will NOT work here: Proton only issues // SMTP tokens for custom-domain addresses. - 'smtp_user' => 'contact@nelson-thomas.fr', + 'smtp_user' => 'contact@your-domain.tld', // The token itself (not your Proton password). 'smtp_token' => 'PASTE_YOUR_SMTP_TOKEN_HERE', // Where the messages are delivered. Can be any of your addresses. - 'to' => 'nelson.thomas.contact@domain.com', + 'to' => 'you@example.com', // Only these sites may post to the form (scheme + host, no trailing slash). 'allowed_origins' => [ @@ -31,13 +31,6 @@ return [ // Anti-spam: messages allowed per visitor IP per hour. 'max_per_hour' => 5, - // Optional: name shown in the email ("... formulaire de contact de "). - // Leave empty to use the site's domain automatically. - 'site_name' => '', - - // Time zone used for the date at the bottom of the email. - 'timezone' => 'Europe/Paris', - // Random string used to anonymise IPs in the rate-limit files. // Generate one with: openssl rand -hex 16 'rate_salt' => 'CHANGE_ME_RANDOM_STRING', diff --git a/www/404.html b/www/404.html index 8d04e9f..4aec673 100644 --- a/www/404.html +++ b/www/404.html @@ -2,24 +2,32 @@ - + Page not found – Nelson Thomas - - - +Page not found – Nelson Thomas + + +
-
-
$ traceroute this-page
-
1nelson-thomas.frokReached the site
-
2* * *404This page does not exist
+ +

This page isn't on the network

+

The address you followed doesn't exist, or it has moved. Everything about me is on the home page.

+
+
$ traceroute /this-page
+
1nelson-thomas.fr2 mshome page found
+
2* * *request timed out
+
3!Hdestination unreachable
+
+ -

Page not found

-

The link may be old or mistyped.

- Back to the portfolio
+ + diff --git a/www/css/style.css b/www/css/style.css index 6bb7961..3b7c018 100644 --- a/www/css/style.css +++ b/www/css/style.css @@ -1,6 +1,6 @@ :root{ --night:#14122b; --surface:rgba(32,28,66,.72); --surface-2:#262249; --line:#3a3566; - --text:#ece8f7; --muted:#a8a3c9; --rose:#f0708a; --signal:#74d4e6; --todo:#f3c969; --proton:#6d4aff; --proton-soft:#8a6eff; + --text:#ece8f7; --muted:#a8a3c9; --rose:#f0708a; --signal:#74d4e6; --todo:#f3c969; --proton:#6d4aff; --proton-soft:#8a6eff; --accent:#a996ff; --display:"Chakra Petch", "Segoe UI", system-ui, sans-serif; --body:"IBM Plex Sans", "Segoe UI", system-ui, sans-serif; --mono:"IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace; @@ -10,17 +10,17 @@ } :root[data-theme="light"]{ --night:#f4f2fb; --surface:#ffffff; --surface-2:#ebe8f7; --line:#d3cfe8; - --text:#1c1936; --muted:#5c5780; --rose:#c43a5a; --signal:#12788c; --todo:#9a6b00; --proton:#6d4aff; --proton-soft:#5b3be6; + --text:#1c1936; --muted:#4a456c; --rose:#c43a5a; --signal:#12788c; --todo:#9a6b00; --proton:#6d4aff; --proton-soft:#5b3be6; --accent:#4326c4; } @media (prefers-color-scheme: light){ :root:not([data-theme="dark"]){ --night:#f4f2fb; --surface:#ffffff; --surface-2:#ebe8f7; --line:#d3cfe8; - --text:#1c1936; --muted:#5c5780; --rose:#c43a5a; --signal:#12788c; --todo:#9a6b00; --proton:#6d4aff; --proton-soft:#5b3be6; + --text:#1c1936; --muted:#4a456c; --rose:#c43a5a; --signal:#12788c; --todo:#9a6b00; --proton:#6d4aff; --proton-soft:#5b3be6; --accent:#4326c4; } } :root[data-theme="dark"]{ --night:#14122b; --surface:rgba(32,28,66,.72); --surface-2:#262249; --line:#3a3566; - --text:#ece8f7; --muted:#a8a3c9; --rose:#f0708a; --signal:#74d4e6; --todo:#f3c969; --proton:#6d4aff; --proton-soft:#8a6eff; + --text:#ece8f7; --muted:#a8a3c9; --rose:#f0708a; --signal:#74d4e6; --todo:#f3c969; --proton:#6d4aff; --proton-soft:#8a6eff; --accent:#a996ff; } *,*::before,*::after{box-sizing:inherit} body{margin:0;background-color:var(--night);color:var(--text);font:400 1rem/1.6 var(--body); @@ -67,7 +67,7 @@ p{margin:0 0 1rem;max-width:68ch} .hero{display:grid;grid-template-columns:1.1fr 1fr;gap:2.5rem;align-items:center;margin-bottom:3rem} .avatar{box-shadow:0 0 0 4px color-mix(in srgb,var(--proton) 25%,transparent);width:96px;height:96px;border-radius:50%;display:grid;place-items:center;font:700 1.8rem var(--display); background:var(--grad);color:#fff;margin-bottom:1.2rem} -.role{font:500 1.1rem var(--display);color:var(--proton-soft);margin-bottom:1rem} +.role{font:500 1.1rem var(--display);color:var(--accent);margin-bottom:1rem} .trace{background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:1.1rem 1.2rem;font:400 .86rem/1.75 var(--mono);overflow-x:auto} .trace .cmd{color:var(--muted);margin-bottom:.4rem} .trace .cmd b{color:var(--text);font-weight:500} @@ -111,7 +111,7 @@ input:focus,textarea:focus{outline:none;border-color:var(--proton-soft);box-shad input:user-invalid,textarea:user-invalid{border-color:var(--rose)} .hp{position:absolute;left:-9999px} .form button{display:inline-flex;align-items:center;gap:.55rem;font:600 1rem var(--body);cursor:pointer;border:0;padding:.75rem 1.4rem;border-radius:8px;background:var(--proton);color:#fff;transition:background-color .2s,transform .2s} -.form button:hover{background:var(--proton-soft)} +.form button:hover{background:#5b3be6} .form button:disabled{opacity:.6;cursor:wait} .status{margin:.9rem 0 0;font-size:.95rem;min-height:1.5em} .status.ok{color:var(--signal)} .status.err{color:var(--rose)} @@ -123,7 +123,7 @@ input:user-invalid,textarea:user-invalid{border-color:var(--rose)} .item:hover,.trace:hover,.form:hover{transform:translateY(-3px);border-color:var(--proton-soft); box-shadow:0 10px 28px -12px color-mix(in srgb,var(--proton) 55%,transparent)} .btn:hover{transform:translateY(-2px);border-color:var(--proton-soft);box-shadow:0 6px 18px -8px color-mix(in srgb,var(--proton) 70%,transparent)} - .btn.primary:hover{background:var(--proton-soft);filter:none} + .btn.primary:hover{background:#5b3be6;border-color:#5b3be6;filter:none} .item:hover .tags span{background:color-mix(in srgb,var(--proton) 22%,var(--surface-2));color:var(--text)} .form button:hover{transform:translateY(-1px)} } @@ -407,16 +407,22 @@ dl.facts dd{margin:0} nav a.active::after{transform:scaleY(1)} } @media (prefers-reduced-motion:reduce){nav,nav.open,.menu-btn span{transition:none}} +/* ===== 404 page ===== */ +.notfound{max-width:720px;margin:0 auto;padding:clamp(3rem,10vh,6rem) 1.25rem 4rem} +.notfound .code{font:700 clamp(4.5rem,18vw,8rem)/1 var(--display);color:var(--accent);letter-spacing:.02em;margin:0 0 .4rem} +.notfound h1{font-size:clamp(1.6rem,4.5vw,2.2rem);margin-bottom:.8rem} +.notfound .trace{margin:1.8rem 0 2rem} +.notfound .hop{opacity:1;animation:none} +.notfound .hop{grid-template-columns:1.3rem 8.8rem 2.8rem minmax(0,1fr);column-gap:.7rem} +@media (max-width:480px){.notfound .hop{grid-template-columns:1.1rem 8.6rem minmax(0,1fr);column-gap:.5rem}.notfound .hop .y{display:none}} +.notfound .hop.fail .h,.notfound .hop.fail span:last-child{color:var(--rose)} +.notfound .cta{margin-top:0} /* Career cards: keep the action buttons at the bottom */ #career .item{display:flex;flex-direction:column;align-items:flex-start} #career .item>.btn,#career .cv-links{margin-top:auto} #career .cv-links{display:flex;margin-bottom:0} -/* 404 page */ -.notfound{max-width:640px;min-height:100vh;display:grid;align-content:center;gap:1.2rem;padding:2rem 1.25rem} -.notfound h1{margin:0} - /* Former inline styles (moved here so a strict Content-Security-Policy can block inline CSS) */ .u-019d5f{left:4.76% !important;width:78.57% !important} .u-054622{animation-delay:.5s !important} diff --git a/www/img/og-card.png b/www/img/og-card.png deleted file mode 100644 index beddf51..0000000 Binary files a/www/img/og-card.png and /dev/null differ diff --git a/www/img/og-image.jpg b/www/img/og-image.jpg new file mode 100644 index 0000000..a54a400 Binary files /dev/null and b/www/img/og-image.jpg differ diff --git a/www/index.html b/www/index.html index 84a6ddc..d2bc3fd 100644 --- a/www/index.html +++ b/www/index.html @@ -4,23 +4,27 @@ - - - + - + - - + + + + + + + + Nelson Thomas – ePortfolio - - - + + +
@@ -482,6 +486,6 @@ - + diff --git a/www/js/notfound.js b/www/js/notfound.js new file mode 100644 index 0000000..21af173 --- /dev/null +++ b/www/js/notfound.js @@ -0,0 +1,4 @@ +(function(){ + var p=location.pathname; if(p.length>48)p=p.slice(0,45)+'…'; + document.getElementById('nf-path').textContent=p; +})(); diff --git a/www/legal.html b/www/legal.html index 18439e2..3df861f 100644 --- a/www/legal.html +++ b/www/legal.html @@ -7,9 +7,9 @@ Legal notice – Nelson Thomas Legal notice – Nelson Thomas - - - + + +
@@ -103,6 +103,6 @@

© 2026 Nelson Thomas. Toulouse, France.

- + diff --git a/www/robots.txt b/www/robots.txt index d79fc43..5cb8ccd 100644 --- a/www/robots.txt +++ b/www/robots.txt @@ -2,4 +2,4 @@ User-agent: * Allow: / Disallow: /contact.php -Sitemap: https://nelson-thomas.fr/sitemap.xml +Sitemap: https://www.nelson-thomas.fr/sitemap.xml diff --git a/www/sitemap.xml b/www/sitemap.xml index 0bfaf1c..94e64b5 100644 --- a/www/sitemap.xml +++ b/www/sitemap.xml @@ -1,4 +1,4 @@ - https://nelson-thomas.fr/2026-10-23 + https://www.nelson-thomas.fr/2026-10-26