['name' => 'čeština', 'locale' => 'cs_CZ', 'flag' => '🇨🇿', 'show_in_menu' => true, 'dir' => 'ltr'], 'de' => ['name' => 'Deutsch', 'locale' => 'de_DE', 'flag' => '🇩🇪', 'show_in_menu' => true, 'dir' => 'ltr'], 'en' => ['name' => 'English', 'locale' => 'en_GB', 'flag' => '🇬🇧', 'show_in_menu' => true, 'dir' => 'ltr'], 'pl' => ['name' => 'Polski', 'locale' => 'pl_PL', 'flag' => '🇵🇱', 'show_in_menu' => true, 'dir' => 'ltr'], 'ru' => ['name' => 'Русский', 'locale' => 'ru_RU', 'flag' => '🇷🇺', 'show_in_menu' => true, 'dir' => 'ltr'], 'tr' => ['name' => 'Türkçe', 'locale' => 'tr_TR', 'flag' => '🇹🇷', 'show_in_menu' => true, 'dir' => 'ltr'], 'uk' => ['name' => 'Українська', 'locale' => 'uk_UA', 'flag' => '🇺🇦', 'show_in_menu' => true, 'dir' => 'ltr'], ]; $language = 'en'; $locale = 'en_GB'; $dir = 'ltr'; if(isset($_REQUEST['lang']) && isset(LANGUAGES[$_REQUEST['lang']])){ $locale = LANGUAGES[$_REQUEST['lang']]['locale']; $language = $_REQUEST['lang']; $dir = LANGUAGES[$_REQUEST['lang']]['dir']; setcookie('language', $_REQUEST['lang'], ['expires' => 0, 'path' => '/', 'domain' => '', 'secure' => ($_SERVER['HTTPS'] ?? '' === 'on'), 'httponly' => true, 'samesite' => 'Strict']); }elseif(isset($_COOKIE['language']) && isset(LANGUAGES[$_COOKIE['language']])){ $locale = LANGUAGES[$_COOKIE['language']]['locale']; $language = $_COOKIE['language']; $dir = LANGUAGES[$_COOKIE['language']]['dir']; }elseif(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])){ $prefLocales = array_reduce( explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']), function (array $res, string $el) { list($l, $q) = array_merge(explode(';q=', $el), [1]); $res[$l] = (float) $q; return $res; }, []); arsort($prefLocales); foreach($prefLocales as $l => $q){ $lang = locale_lookup(array_keys(LANGUAGES), $l); if(!empty($lang)){ $locale = LANGUAGES[$lang]['locale']; $language = $lang; $dir = LANGUAGES[$lang]['dir']; setcookie('language', $lang, ['expires' => 0, 'path' => '/', 'domain' => '', 'secure' => ($_SERVER['HTTPS'] ?? '' === 'on'), 'httponly' => true, 'samesite' => 'Strict']); break; } } } putenv('LC_ALL='.$locale); setlocale(LC_ALL, $locale); bindtextdomain('mail-hosting', __DIR__.'/locale'); bind_textdomain_codeset('mail-hosting', 'UTF-8'); textdomain('mail-hosting'); require_once( __DIR__ . '/vendor/autoload.php' ); function get_inactivity_period_options(): array { return [ 1 => _('1 month'), 6 => _('6 months'), 12 => _('1 year'), 24 => _('2 years'), ]; } function generate_feedback_id( PDO $db ): string { $stmt = $db->prepare( 'SELECT 1 FROM mailbox WHERE feedback_id = ? LIMIT 1;' ); do { $feedback_id = substr( bin2hex( random_bytes( 8 ) ), 0, 15 ); $stmt->execute( [ $feedback_id ] ); } while ( $stmt->fetchColumn() ); return $feedback_id; } function get_db_instance(): PDO { static $db = null; if ( $db !== null ) { return $db; } try { $db = new PDO( 'mysql:host=' . DBHOST . ';dbname=' . DBNAME, DBUSER, DBPASS, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => PERSISTENT ] ); } catch ( PDOException ) { http_response_code( 500 ); die( _('No Connection to MySQL database!') ); } return $db; } function get_rsa_dkim_private_key_base64_der( string $private_key ): ?string { $key = openssl_pkey_get_private( $private_key ); if ( $key === false ) { return null; } $details = openssl_pkey_get_details( $key ); if ( ! is_array( $details ) || $details[ 'type' ] !== OPENSSL_KEYTYPE_RSA ) { return null; } if ( ! openssl_pkey_export( $key, $normalized_key ) ) { return null; } $encoded_key = preg_replace( '/-----BEGIN [^-]+-----|-----END [^-]+-----|\s+/', '', $normalized_key ); if ( ! is_string( $encoded_key ) || $encoded_key === '' || base64_decode( $encoded_key, true ) === false ) { return null; } return $encoded_key; } function get_rsa_dkim_public_key_base64( string $private_key ): ?string { $key = openssl_pkey_get_private( $private_key ); if ( $key === false ) { return null; } $details = openssl_pkey_get_details( $key ); if ( ! is_array( $details ) || $details[ 'type' ] !== OPENSSL_KEYTYPE_RSA ) { return null; } $encoded_key = preg_replace( '/-----BEGIN [^-]+-----|-----END [^-]+-----|\s+/', '', $details[ 'key' ] ); if ( ! is_string( $encoded_key ) || $encoded_key === '' || base64_decode( $encoded_key, true ) === false ) { return null; } return $encoded_key; } function generate_rsa_dkim_key(): array { $key = openssl_pkey_new( [ 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => 4096, ] ); if ( $key === false || ! openssl_pkey_export( $key, $private_key ) ) { throw new RuntimeException( 'Unable to generate RSA DKIM private key.' ); } return [ 'key' => $private_key, 'selector' => date( 'Ymd' ) . '-rsa', ]; } function z_base32_encode( string $input ): string { $map = [ 'y', 'b', 'n', 'd', 'r', 'f', 'g', '8', // 7 'e', 'j', 'k', 'm', 'c', 'p', 'q', 'x', // 15 'o', 't', '1', 'u', 'w', 'i', 's', 'z', // 23 'a', '3', '4', '5', 'h', '7', '6', '9', // 31 ]; if ( empty( $input ) ) { return ''; } $input = str_split( $input ); $binaryString = ''; $c = count( $input ); for ( $i = 0; $i < $c; ++$i ) { $binaryString .= str_pad( decbin( ord( $input[ $i ] ) ), 8, '0', STR_PAD_LEFT ); } $fiveBitBinaryArray = str_split( $binaryString, 5 ); $base32 = ''; $i = 0; $c = count( $fiveBitBinaryArray ); while ( $i < $c ) { $base32 .= $map[ bindec( $fiveBitBinaryArray[ $i ] ) ]; ++$i; } return $base32; } function totp_base32_encode( string $input ): string { $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; $encoded = ''; $buffer = 0; $bits = 0; for ( $i = 0, $length = strlen( $input ); $i < $length; ++$i ) { $buffer = ( $buffer << 8 ) | ord( $input[ $i ] ); $bits += 8; while ( $bits >= 5 ) { $bits -= 5; $encoded .= $alphabet[ ( $buffer >> $bits ) & 31 ]; } $buffer &= ( 1 << $bits ) - 1; } if ( $bits > 0 ) { $encoded .= $alphabet[ ( $buffer << ( 5 - $bits ) ) & 31 ]; } return $encoded; } function totp_base32_decode( string $input ): string|false { $input = strtoupper( rtrim( $input, '=' ) ); if ( $input === '' || ! preg_match( '/^[A-Z2-7]+$/', $input ) ) { return false; } $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; $decoded = ''; $buffer = 0; $bits = 0; for ( $i = 0, $length = strlen( $input ); $i < $length; ++$i ) { $buffer = ( $buffer << 5 ) | strpos( $alphabet, $input[ $i ] ); $bits += 5; if ( $bits >= 8 ) { $bits -= 8; $decoded .= chr( ( $buffer >> $bits ) & 255 ); } $buffer &= ( 1 << $bits ) - 1; } return $decoded === '' ? false : $decoded; } function generate_totp_secret(): string { return totp_base32_encode( random_bytes( 20 ) ); } function get_totp_provisioning_uri( string $account, string $secret ): string { $issuer = 'Mail Hosting'; $label = rawurlencode( "$issuer:$account" ); return "otpauth://totp/$label?secret=" . rawurlencode( $secret ) . '&issuer=' . rawurlencode( $issuer ) . '&algorithm=SHA1&digits=6&period=30'; } function get_totp_qr_data_uri( string $totp_uri ): string { $qrCode = new \Endroid\QrCode\QrCode( $totp_uri, new \Endroid\QrCode\Encoding\Encoding( 'UTF-8' ), \Endroid\QrCode\ErrorCorrectionLevel::Low, 220, 8 ); return ( new \Endroid\QrCode\Writer\PngWriter() )->write( $qrCode )->getDataUri(); } function verify_totp_code( string $secret, mixed $code, ?int $time = null ): bool { if ( ! is_string( $code ) || ! preg_match( '/^[0-9]{6}$/', $code ) ) { return false; } $key = totp_base32_decode( $secret ); if ( $key === false ) { return false; } $time ??= time(); $counter = intdiv( $time, 30 ); for ( $offset = -1; $offset <= 1; ++$offset ) { $step = $counter + $offset; $counter_bytes = pack( 'N2', ( $step >> 32 ) & 0xffffffff, $step & 0xffffffff ); $hash = hash_hmac( 'sha1', $counter_bytes, $key, true ); $offset_byte = ord( $hash[ 19 ] ) & 0x0f; $binary = ( ( ord( $hash[ $offset_byte ] ) & 0x7f ) << 24 ) | ( ( ord( $hash[ $offset_byte + 1 ] ) & 0xff ) << 16 ) | ( ( ord( $hash[ $offset_byte + 2 ] ) & 0xff ) << 8 ) | ( ord( $hash[ $offset_byte + 3 ] ) & 0xff ); $expected = str_pad( (string) ( $binary % 1000000 ), 6, '0', STR_PAD_LEFT ); if ( hash_equals( $expected, $code ) ) { return true; } } return false; } function send_captcha(): void { if ( CAPTCHA_DIFFICULTY === 0 || ! extension_loaded( 'gd' ) ) { return; } $db = get_db_instance(); $captchachars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $length = strlen( $captchachars ) - 1; $code = ''; for ( $i = 0; $i < 5; ++$i ) { $code .= $captchachars[ mt_rand( 0, $length ) ]; } $randid = mt_rand(); $time = time(); $stmt = $db->prepare( 'INSERT INTO captcha (id, time, code) VALUES (?, ?, ?);' ); $stmt->execute( [ $randid, $time, $code ] ); echo '
'._('Copy:').'
'; if ( CAPTCHA_DIFFICULTY === 1 ) { $im = imagecreatetruecolor( 55, 24 ); $bg = imagecolorallocate( $im, 0, 0, 0 ); $fg = imagecolorallocate( $im, 255, 255, 255 ); imagefill( $im, 0, 0, $bg ); imagestring( $im, 5, 5, 5, $code, $fg ); echo ''; echo '
'; } function check_captcha( string $challenge, string $captcha_code ): bool { $db = get_db_instance(); if ( CAPTCHA_DIFFICULTY > 0 ) { if ( empty( $challenge ) ) { return false; } $code = ''; $stmt = $db->prepare( 'SELECT code FROM captcha WHERE id=?;' ); $stmt->execute( [ $challenge ] ); $stmt->bindColumn( 1, $code ); if ( ! $stmt->fetch( PDO::FETCH_BOUND ) ) { return false; } $time = time(); $stmt = $db->prepare( 'DELETE FROM captcha WHERE id=? OR time < ?;' ); $stmt->execute( [ $challenge, $time - 600 ] ); if ( $captcha_code !== $code ) { if ( CAPTCHA_DIFFICULTY !== 3 || strrev( $captcha_code ) !== $code ) { return false; } } } return true; } function validate_email_list( array $targets, string &$msg = '' ): string { $alias_goto = ''; $targets = array_unique( $targets ); foreach ( $targets as $email ) { $validator = new EmailValidator(); if ( $validator->isValid( $email, new NoRFCWarningsValidation() ) ) { $alias_goto .= ",$email"; } else { $msg .= ''; } } return ltrim( $alias_goto, ',' ); } function check_domain_access( string &$email, string &$msg = '' ): bool { if ( ! $_SESSION[ 'email_admin_superadmin' ] ) { $db = get_db_instance(); $parser = new EmailParser( new EmailLexer() ); $parser->parse( $email ); $domain = $parser->getDomainPart(); $stmt = $db->prepare( 'SELECT target_domain FROM alias_domain WHERE alias_domain = ? AND active=1;' ); $stmt->execute( [ $domain ] ); if ( $tmp = $stmt->fetch( PDO::FETCH_ASSOC ) ) { $domain = $tmp[ 'target_domain' ]; $email = preg_replace( '~@[^@+]$~iu', "@$domain", $email ); } $managed_domains = []; $stmt = $db->prepare( 'SELECT domain FROM domain_admins WHERE username = ?;' ); $stmt->execute( [ $_SESSION[ 'email_admin_user' ] ] ); while ( $tmp = $stmt->fetch( PDO::FETCH_ASSOC ) ) { $managed_domains [] = $tmp[ 'domain' ]; } if ( ! in_array( $domain, $managed_domains, true ) ) { $msg .= ''; return false; } } return true; } function check_email_valid( string $email, string &$msg = '' ): bool { $validator = new EmailValidator(); if ( ! $validator->isValid( $email, new NoRFCWarningsValidation() ) ) { $msg .= ''; return false; } return true; } function create_mailbox_identity( PDO $db, string $identityAddress, string $mailboxUsername, string &$msg = '', bool $allowOtherDomains = false ): bool { $identityAddress = mb_strtolower( trim( $identityAddress ) ); $stmt = $db->prepare( 'SELECT username, domain, active FROM mailbox WHERE username = ?;' ); $stmt->execute( [ $mailboxUsername ] ); $mailbox = $stmt->fetch( PDO::FETCH_ASSOC ); if ( ! $mailbox || (int) $mailbox[ 'active' ] < 0 ) { $msg .= ''; return false; } $mailboxUsername = $mailbox[ 'username' ]; $mailboxDomain = $mailbox[ 'domain' ]; if ( ! check_email_valid( $identityAddress, $msg ) ) { return false; } $parser = new EmailParser( new EmailLexer() ); $parser->parse( $identityAddress ); $identityDomain = $parser->getDomainPart(); if ( ! $allowOtherDomains && mb_strtolower( $identityDomain ) !== mb_strtolower( $mailboxDomain ) ) { $msg .= ''; return false; } $stmt = $db->prepare( 'SELECT domain FROM domain WHERE domain = ? AND active = 1;' ); $stmt->execute( [ $identityDomain ] ); $identityDomain = $stmt->fetchColumn(); if ( ! is_string( $identityDomain ) ) { $msg .= ''; return false; } $stmt = $db->prepare( 'SELECT username FROM mailbox WHERE username = ? UNION SELECT address FROM alias WHERE address = ?;' ); $stmt->execute( [ $identityAddress, $identityAddress ] ); if ( $stmt->fetch() ) { $msg .= ''; return false; } $stmt = $db->prepare( 'INSERT INTO alias (address, goto, domain, created, modified, active, enforce_tls_in, identity) VALUES (?, ?, ?, NOW(), NOW(), ?, 1, ?);' ); $stmt->execute( [ $identityAddress, $mailboxUsername, $identityDomain, ( (int) $mailbox[ 'active' ] === 1 ? 1 : 0 ), $mailboxUsername ] ); return true; } function create_clearnet_onion_identity( PDO $db, string $mailboxUsername, string &$msg = '' ): bool { $stmt = $db->prepare( 'SELECT local_part, domain FROM mailbox WHERE username = ?;' ); $stmt->execute( [ $mailboxUsername ] ); $mailbox = $stmt->fetch( PDO::FETCH_ASSOC ); if ( ! $mailbox ) { $msg .= ''; return false; } if ( $mailbox[ 'domain' ] !== CLEARNET_SERVER ) { return true; } return create_mailbox_identity( $db, $mailbox[ 'local_part' ] . '@' . ONION_SERVER, $mailboxUsername, $msg, true ); } function parse_sender_address_list( string $value ): ?array { $validator = new EmailValidator(); $addresses = []; foreach ( preg_split( '/\R/', $value ) as $address ) { $address = trim( $address ); if ( $address === '' ) { continue; } if ( ! $validator->isValid( $address, new NoRFCWarningsValidation() ) ) { return null; } $addresses[] = mb_strtolower( $address ); } return array_values( array_unique( $addresses ) ); } function alt_links(): void { global $language; foreach(LANGUAGES as $lang => $data) { if($lang === $language){ continue; } echo ''; echo ''; } } function bytes_to_human_readable(int $bytes) : string { $suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; $size_class=(int) log($bytes, 1024); if($size_class!==0){ return sprintf('%1.1f', $bytes / pow(1024, $size_class)) . $suffix[$size_class]; }else{ return $bytes . $suffix[0]; } }