695 linhas
28 KiB
PHP
695 linhas
28 KiB
PHP
<?php
|
|
/**
|
|
* E-mail Center (API): Mail Provider for WHMCS 8.
|
|
*
|
|
* Sends every WHMCS email through the transactional API of the E-mail Center
|
|
* (POST /v1/email/messages). Install in modules/mail/mozout_email_center/ and choose it in
|
|
* System Settings > General Settings > Mail > Configure Mail Provider.
|
|
*
|
|
* Only the public API is used, with the customer's own key (Bearer). The key lives in the
|
|
* encrypted mail configuration of WHMCS and is never written to any log.
|
|
*
|
|
* Compatible with PHP 7.4 and 8.x.
|
|
*/
|
|
|
|
namespace WHMCS\Module\Mail;
|
|
|
|
use WHMCS\Exception\Mail\SendFailure;
|
|
use WHMCS\Exception\Module\InvalidConfiguration;
|
|
use WHMCS\Mail\Message;
|
|
use WHMCS\Module\Contracts\SenderModuleInterface;
|
|
use WHMCS\Module\MailSender\DescriptionTrait;
|
|
|
|
if (!defined('WHMCS')) {
|
|
die('This file cannot be accessed directly');
|
|
}
|
|
|
|
class mozout_email_center implements SenderModuleInterface
|
|
{
|
|
use DescriptionTrait;
|
|
|
|
const VERSION = '1.0.1';
|
|
const MODULE = 'mozout_email_center';
|
|
const MAX_ATTACHMENTS_BYTES = 5242880;
|
|
const MAX_RECIPIENTS = 50;
|
|
const MAX_HEADERS = 20;
|
|
|
|
/** Brands: name (English; translated on screen), API address. The key decides Sandbox or Production. */
|
|
public static function brands()
|
|
{
|
|
return [
|
|
'mozout' => ['MozOut', 'https://api.mozout.com'],
|
|
];
|
|
}
|
|
|
|
public function __construct()
|
|
{
|
|
$this->setDisplayName('E-mail Center (API)');
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Settings screen */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
public function settings()
|
|
{
|
|
$L = self::adminIsPortuguese() ? 'pt' : 'en';
|
|
$fixed = self::brand();
|
|
$brands = [];
|
|
foreach (self::brands() as $k => $b) {
|
|
$brands[$k] = self::t($L, $b[0]);
|
|
}
|
|
$brands['custom'] = self::t($L, 'Other address (below)');
|
|
|
|
$fields = [
|
|
'brand' => [
|
|
'FriendlyName' => self::t($L, 'Provider'),
|
|
'Type' => 'dropdown',
|
|
'Options' => $brands,
|
|
'Default' => 'mozout',
|
|
'Description' => self::t($L, 'The company where your E-mail Center account is.'),
|
|
],
|
|
'api_url' => [
|
|
'FriendlyName' => self::t($L, 'API address'),
|
|
'Type' => 'text',
|
|
'Size' => '50',
|
|
'Description' => self::t($L, 'Only for «Other address». Example: https://api.example.com'),
|
|
],
|
|
'api_key' => [
|
|
'FriendlyName' => self::t($L, 'API key'),
|
|
'Type' => 'password',
|
|
'Size' => '60',
|
|
'Description' => $fixed
|
|
? self::t($L, 'Create it in %s (%s) > API, with the email_center:write permission. A sandbox_ key simulates; prod_ sends.', $fixed['panel_name'], $fixed['panel'])
|
|
: self::t($L, 'Create it on the API page of your account, with the email_center:write permission. A sandbox_ key simulates; prod_ sends.'),
|
|
],
|
|
'from_email' => [
|
|
'FriendlyName' => self::t($L, 'Sender'),
|
|
'Type' => 'text',
|
|
'Size' => '50',
|
|
'Description' => self::t($L, 'Optional. An address at a domain verified in E-mail Center. Empty: the WHMCS sender is used, and it must also be at a verified domain.'),
|
|
],
|
|
'from_name' => [
|
|
'FriendlyName' => self::t($L, 'Sender name'),
|
|
'Type' => 'text',
|
|
'Size' => '50',
|
|
'Description' => self::t($L, 'Optional. Empty: the name WHMCS gives each email.'),
|
|
],
|
|
'test_to' => [
|
|
'FriendlyName' => self::t($L, 'Send the test to'),
|
|
'Type' => 'text',
|
|
'Size' => '50',
|
|
'Description' => self::t($L, 'Optional. Empty: the email of the administrator who clicks «Test».'),
|
|
],
|
|
'language' => [
|
|
'FriendlyName' => self::t($L, 'Error language'),
|
|
'Type' => 'dropdown',
|
|
'Options' => ['pt' => 'Português', 'en' => 'English'],
|
|
'Default' => $L,
|
|
'Description' => self::t($L, 'The language of the error messages in the email log.'),
|
|
],
|
|
];
|
|
if ($fixed) {
|
|
// Fixed brand (brand.php): the API address is known, so no provider or address fields.
|
|
unset($fields['brand'], $fields['api_url']);
|
|
}
|
|
return $fields;
|
|
}
|
|
|
|
/**
|
|
* «Test Configuration»: checks the key, the E-mail Center account and sends one real
|
|
* test email (simulated with a sandbox_ key). Any problem stops with a clear message.
|
|
*/
|
|
public function testConnection(array $params)
|
|
{
|
|
$lang = self::lang($params);
|
|
try {
|
|
$api = self::endpoint($params);
|
|
$key = self::key($params);
|
|
} catch (\Exception $e) {
|
|
throw new InvalidConfiguration($e->getMessage());
|
|
}
|
|
|
|
$token = $this->request($api, $key, 'GET', '/v1/token', null, null, $lang);
|
|
if ($token['status'] !== 200) {
|
|
throw new InvalidConfiguration(self::errorText($token, $lang));
|
|
}
|
|
$perms = isset($token['json']['data']['permissions']) ? (array) $token['json']['data']['permissions'] : [];
|
|
if (!in_array('email_center:write', $perms, true)) {
|
|
throw new InvalidConfiguration(self::t($lang, 'The key does not have the email_center:write permission. Create a key with that permission.'));
|
|
}
|
|
$mode = (string) ($token['json']['data']['mode'] ?? '');
|
|
|
|
$balance = $this->request($api, $key, 'GET', '/v1/email/balance', null, null, $lang);
|
|
if ($balance['status'] !== 200) {
|
|
throw new InvalidConfiguration(self::errorText($balance, $lang));
|
|
}
|
|
|
|
$to = trim((string) ($params['test_to'] ?? ''));
|
|
if ($to === '') {
|
|
$to = self::currentAdminEmail();
|
|
}
|
|
if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
|
|
throw new InvalidConfiguration(self::t($lang, 'Enter a valid address in «Send the test to».'));
|
|
}
|
|
|
|
$from = trim((string) ($params['from_email'] ?? ''));
|
|
if ($from === '') {
|
|
$from = trim((string) self::setting('SystemEmailsFromEmail'));
|
|
}
|
|
if ($from === '') {
|
|
$from = trim((string) self::setting('Email'));
|
|
}
|
|
$fromName = trim((string) ($params['from_name'] ?? ''));
|
|
if ($fromName === '') {
|
|
$fromName = trim((string) self::setting('SystemEmailsFromName')) ?: trim((string) self::setting('CompanyName'));
|
|
}
|
|
|
|
$simulated = $mode === 'sandbox';
|
|
$subject = self::t($lang, 'E-mail Center test');
|
|
$text = self::t($lang, 'Hello,') . "\n\n"
|
|
. self::t($lang, 'This is the test of sending WHMCS emails through E-mail Center. If you got it, everything is fine.') . "\n\n"
|
|
. self::t($lang, 'Key mode: %s', $simulated ? self::t($lang, 'Sandbox (simulated, nothing is really sent)') : self::t($lang, 'Production'));
|
|
$payload = [
|
|
'from' => $from,
|
|
'to' => [$to],
|
|
'subject' => $subject,
|
|
'text' => $text,
|
|
'html' => '<p>' . nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8')) . '</p>',
|
|
'headers' => ['X-WHMCS-Module' => 'mozout_email_center ' . self::VERSION],
|
|
];
|
|
if ($fromName !== '') {
|
|
$payload['from_name'] = $fromName;
|
|
}
|
|
$r = $this->request($api, $key, 'POST', '/v1/email/messages', $payload, self::uuid(), $lang);
|
|
if ($r['status'] === 422 && self::reason($r) === 'invalid_headers') {
|
|
unset($payload['headers']);
|
|
$r = $this->request($api, $key, 'POST', '/v1/email/messages', $payload, self::uuid(), $lang);
|
|
}
|
|
if ($r['status'] !== 201 && $r['status'] !== 200) {
|
|
throw new InvalidConfiguration(self::errorText($r, $lang));
|
|
}
|
|
$status = (string) ($r['json']['data']['status'] ?? '');
|
|
if ($status === 'failed') {
|
|
throw new InvalidConfiguration(self::failedText($r, $lang));
|
|
}
|
|
return ['success' => true, 'status' => $status, 'mode' => $mode];
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Sending */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
public function send(array $params, Message $message)
|
|
{
|
|
$lang = self::lang($params);
|
|
try {
|
|
$api = self::endpoint($params);
|
|
$key = self::key($params);
|
|
} catch (\Exception $e) {
|
|
throw new SendFailure($e->getMessage());
|
|
}
|
|
|
|
$payload = $this->buildPayload($params, $message, $lang);
|
|
|
|
$r = $this->request($api, $key, 'POST', '/v1/email/messages', $payload, self::uuid(), $lang, true);
|
|
if ($r['status'] === 422 && self::reason($r) === 'invalid_headers' && isset($payload['headers'])) {
|
|
// Some header is reserved by the provider: send again without the extra headers.
|
|
unset($payload['headers']);
|
|
$r = $this->request($api, $key, 'POST', '/v1/email/messages', $payload, self::uuid(), $lang, true);
|
|
}
|
|
if ($r['status'] !== 201 && $r['status'] !== 200) {
|
|
throw new SendFailure(self::errorText($r, $lang));
|
|
}
|
|
$status = (string) ($r['json']['data']['status'] ?? '');
|
|
if ($status === 'failed') {
|
|
throw new SendFailure(self::failedText($r, $lang));
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private function buildPayload(array $params, Message $message, $lang)
|
|
{
|
|
$originalFrom = trim((string) $message->getFromEmail());
|
|
$from = trim((string) ($params['from_email'] ?? ''));
|
|
if ($from === '') {
|
|
$from = $originalFrom;
|
|
}
|
|
if ($from === '') {
|
|
throw new SendFailure(self::t($lang, 'E-mail Center: the email has no sender.'));
|
|
}
|
|
$fromName = trim((string) ($params['from_name'] ?? ''));
|
|
if ($fromName === '') {
|
|
$fromName = trim((string) $message->getFromName());
|
|
}
|
|
|
|
$to = self::addresses($message->getRecipients('to'));
|
|
$cc = self::addresses($message->getRecipients('cc'));
|
|
$bcc = self::addresses($message->getRecipients('bcc'));
|
|
if (!$to && !$cc && !$bcc) {
|
|
throw new SendFailure(self::t($lang, 'E-mail Center: the email has no recipients.'));
|
|
}
|
|
if (!$to) {
|
|
// The API needs at least one «to»: move the first copy up.
|
|
if ($cc) {
|
|
$to = [array_shift($cc)];
|
|
} else {
|
|
$to = [array_shift($bcc)];
|
|
}
|
|
}
|
|
if (count($to) + count($cc) + count($bcc) > self::MAX_RECIPIENTS) {
|
|
throw new SendFailure(self::t($lang, 'E-mail Center: more than 50 recipients in one email. Reduce the copies (CC/BCC).'));
|
|
}
|
|
|
|
$payload = [
|
|
'from' => $from,
|
|
'to' => $to,
|
|
'subject' => (string) $message->getSubject(),
|
|
];
|
|
if ($fromName !== '') {
|
|
$payload['from_name'] = $fromName;
|
|
}
|
|
if ($cc) {
|
|
$payload['cc'] = $cc;
|
|
}
|
|
if ($bcc) {
|
|
$payload['bcc'] = $bcc;
|
|
}
|
|
|
|
$replyTo = trim((string) $message->getReplyToEmail());
|
|
if ($replyTo === '' && $originalFrom !== '' && strcasecmp($originalFrom, $from) !== 0) {
|
|
// A fixed sender was set: answers still go to the address WHMCS chose.
|
|
$replyTo = $originalFrom;
|
|
}
|
|
if ($replyTo !== '' && filter_var($replyTo, FILTER_VALIDATE_EMAIL)) {
|
|
$payload['reply_to'] = [$replyTo];
|
|
}
|
|
|
|
$html = (string) $message->getBody();
|
|
$text = (string) $message->getPlainText();
|
|
if (trim($html) !== '') {
|
|
$payload['html'] = $html;
|
|
}
|
|
if (trim($text) !== '') {
|
|
$payload['text'] = $text;
|
|
}
|
|
if (!isset($payload['html']) && !isset($payload['text'])) {
|
|
$payload['text'] = ' ';
|
|
}
|
|
|
|
$attachments = [];
|
|
$total = 0;
|
|
foreach ((array) $message->getAttachments() as $a) {
|
|
$name = (string) ($a['filename'] ?? 'attachment');
|
|
if (isset($a['data'])) {
|
|
$data = (string) $a['data'];
|
|
} elseif (!empty($a['filepath']) && is_readable($a['filepath'])) {
|
|
$data = (string) file_get_contents($a['filepath']);
|
|
} else {
|
|
continue;
|
|
}
|
|
$total += strlen($data);
|
|
$item = ['filename' => $name, 'content' => base64_encode($data)];
|
|
$type = self::mimeType($name);
|
|
if ($type !== '') {
|
|
$item['content_type'] = $type;
|
|
}
|
|
$attachments[] = $item;
|
|
}
|
|
if ($total > self::MAX_ATTACHMENTS_BYTES) {
|
|
throw new SendFailure(self::t($lang, 'E-mail Center: the attachments go over 5 MB in total (%s MB).', round($total / 1048576, 1)));
|
|
}
|
|
if ($attachments) {
|
|
$payload['attachments'] = $attachments;
|
|
}
|
|
|
|
$headers = [];
|
|
foreach ((array) $message->getHeaders() as $name => $value) {
|
|
$name = trim((string) $name);
|
|
if (!preg_match('~^(X-[A-Za-z0-9-]+|List-Unsubscribe|List-Unsubscribe-Post|In-Reply-To|References)$~i', $name)) {
|
|
continue;
|
|
}
|
|
if (preg_match('~^X-(Mailer|Priority|MS|Spam|Originating|Source|PHP)~i', $name)) {
|
|
continue;
|
|
}
|
|
$headers[$name] = (string) $value;
|
|
if (count($headers) >= self::MAX_HEADERS) {
|
|
break;
|
|
}
|
|
}
|
|
if ($headers) {
|
|
$payload['headers'] = $headers;
|
|
}
|
|
return $payload;
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* HTTP */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
/**
|
|
* One request to the API. Retries once, with the same Idempotency-Key, when there is no
|
|
* answer or the answer is 429/500/502/503, so a retry never sends twice.
|
|
*/
|
|
private function request($api, $key, $method, $path, $body, $idempotencyKey, $lang, $retry = false)
|
|
{
|
|
$attempts = $retry ? 2 : 1;
|
|
$result = null;
|
|
for ($i = 1; $i <= $attempts; $i++) {
|
|
$result = self::http($api, $key, $method, $path, $body, $idempotencyKey, $lang);
|
|
$s = $result['status'];
|
|
$again = $s === 0 || $s === 429 || $s === 500 || $s === 502 || $s === 503;
|
|
if (!$again || $i === $attempts) {
|
|
break;
|
|
}
|
|
$wait = 2;
|
|
if ($s === 429 && !empty($result['retry_after'])) {
|
|
$wait = min(10, max(1, (int) $result['retry_after']));
|
|
}
|
|
sleep($wait);
|
|
}
|
|
self::logCall($method . ' ' . $path, $body, $result, $key);
|
|
return $result;
|
|
}
|
|
|
|
private static function http($api, $key, $method, $path, $body, $idempotencyKey, $lang)
|
|
{
|
|
$ch = curl_init($api . $path);
|
|
$headers = [
|
|
'Authorization: Bearer ' . $key,
|
|
'Accept: application/json',
|
|
'Accept-Language: ' . ($lang === 'pt' ? 'pt' : 'en'),
|
|
'User-Agent: WHMCS-mozout_email_center/' . self::VERSION,
|
|
];
|
|
if ($idempotencyKey) {
|
|
$headers[] = 'Idempotency-Key: ' . $idempotencyKey;
|
|
}
|
|
if ($body !== null) {
|
|
$headers[] = 'Content-Type: application/json';
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
|
}
|
|
$retryAfter = 0;
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_CUSTOMREQUEST => $method,
|
|
CURLOPT_HTTPHEADER => $headers,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_CONNECTTIMEOUT => 10,
|
|
CURLOPT_TIMEOUT => 45,
|
|
CURLOPT_SSL_VERIFYPEER => true,
|
|
CURLOPT_SSL_VERIFYHOST => 2,
|
|
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
|
CURLOPT_HEADERFUNCTION => function ($c, $line) use (&$retryAfter) {
|
|
if (stripos($line, 'Retry-After:') === 0) {
|
|
$retryAfter = (int) trim(substr($line, 12));
|
|
}
|
|
return strlen($line);
|
|
},
|
|
]);
|
|
$raw = curl_exec($ch);
|
|
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$err = $raw === false ? curl_error($ch) : '';
|
|
curl_close($ch);
|
|
$json = is_string($raw) ? json_decode($raw, true) : null;
|
|
return [
|
|
'status' => $raw === false ? 0 : $status,
|
|
'json' => is_array($json) ? $json : null,
|
|
'raw' => is_string($raw) ? $raw : '',
|
|
'curl_error' => $err,
|
|
'retry_after' => $retryAfter,
|
|
];
|
|
}
|
|
|
|
/** Module log (System Logs > Module Log), without the key and without email bodies. */
|
|
private static function logCall($action, $body, $result, $key)
|
|
{
|
|
if (!function_exists('logModuleCall')) {
|
|
return;
|
|
}
|
|
$summary = $body;
|
|
if (is_array($summary)) {
|
|
foreach (['html', 'text'] as $k) {
|
|
if (isset($summary[$k])) {
|
|
$summary[$k] = '[' . strlen((string) $summary[$k]) . ' bytes]';
|
|
}
|
|
}
|
|
if (isset($summary['attachments'])) {
|
|
$summary['attachments'] = array_map(function ($a) {
|
|
return ($a['filename'] ?? '') . ' [' . strlen((string) ($a['content'] ?? '')) . ' b64]';
|
|
}, (array) $summary['attachments']);
|
|
}
|
|
}
|
|
$resp = $result['raw'] !== '' ? $result['raw'] : ('curl: ' . $result['curl_error']);
|
|
logModuleCall(self::MODULE, $action, $summary, mb_substr($resp, 0, 4000), '', [$key]);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Errors */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
private static function reason(array $r)
|
|
{
|
|
$d = $r['json']['error']['details'] ?? [];
|
|
return is_array($d) && isset($d['reason']) ? (string) $d['reason'] : '';
|
|
}
|
|
|
|
/** A clear sentence for the WHMCS email log: what happened and what to do. */
|
|
public static function errorText(array $r, $lang)
|
|
{
|
|
$status = (int) $r['status'];
|
|
if ($status === 0) {
|
|
return self::t($lang, 'E-mail Center: no answer from the API (%s). The email was not sent; WHMCS can try again.', $r['curl_error']);
|
|
}
|
|
$err = $r['json']['error'] ?? [];
|
|
$code = (string) ($err['code'] ?? '');
|
|
$apiMsg = trim((string) ($err['message'] ?? ''));
|
|
$details = is_array($err['details'] ?? null) ? $err['details'] : [];
|
|
$reason = (string) ($details['reason'] ?? '');
|
|
$ref = (string) ($err['correlation_id'] ?? '');
|
|
|
|
$hint = '';
|
|
if ($status === 401) {
|
|
$hint = self::t($lang, 'The API key is not valid, was revoked or has expired.');
|
|
} elseif ($code === 'insufficient_scope') {
|
|
$hint = self::t($lang, 'The key does not have the email_center:write permission.');
|
|
} elseif ($reason === 'email_account_required') {
|
|
$hint = self::t($lang, 'E-mail Center is not active on your account.');
|
|
} elseif ($code === 'ip_not_allowed') {
|
|
$hint = self::t($lang, 'The IP of this server is not on the key\'s IP list.');
|
|
} elseif ($status === 402 || $code === 'insufficient_credit' || $code === 'insufficient_credits') {
|
|
$hint = self::t($lang, 'Not enough email credits.');
|
|
} elseif (isset($details['limit']) && in_array($details['limit'], ['monthly_emails', 'monthly_recipients'], true)) {
|
|
$hint = self::t($lang, 'The monthly limit ran out.');
|
|
} elseif ($reason === 'all_recipients_suppressed') {
|
|
$hint = self::t($lang, 'All recipients are on the suppression list (bounces or complaints).');
|
|
} elseif ($status === 429) {
|
|
$hint = self::t($lang, 'Too many requests per minute; WHMCS can try later.');
|
|
} elseif ($status >= 500) {
|
|
$hint = self::t($lang, 'Temporary failure on the E-mail Center side; WHMCS can try later.');
|
|
}
|
|
|
|
$parts = [];
|
|
if ($hint !== '') {
|
|
$parts[] = $hint;
|
|
}
|
|
if ($apiMsg !== '' && $apiMsg !== $hint) {
|
|
$parts[] = $apiMsg;
|
|
}
|
|
if (!$parts) {
|
|
$parts[] = self::t($lang, 'Unexpected answer from the API.');
|
|
}
|
|
$tech = 'HTTP ' . $status . ($code !== '' ? ', ' . $code : '') . ($reason !== '' ? '/' . $reason : '');
|
|
if (!empty($details['field'])) {
|
|
$tech .= ', ' . (is_scalar($details['field']) ? $details['field'] : json_encode($details['field']));
|
|
}
|
|
if ($ref !== '') {
|
|
$tech .= ', ref ' . $ref;
|
|
}
|
|
return 'E-mail Center: ' . implode(' ', $parts) . ' (' . $tech . ')';
|
|
}
|
|
|
|
private static function failedText(array $r, $lang)
|
|
{
|
|
$d = $r['json']['data'] ?? [];
|
|
$e = $d['error'] ?? '';
|
|
if (is_array($e)) {
|
|
$e = $e['message'] ?? json_encode($e);
|
|
}
|
|
return self::t($lang, 'E-mail Center: sending failed')
|
|
. ($e !== '' ? ': ' . $e : '.') . ' (id ' . ($d['id'] ?? '?') . ')';
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Helpers */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
/**
|
|
* Fixed brand: when brand.php sits next to this file (brand editions), it returns
|
|
* ['key', 'name', 'name_en', 'api', 'panel', 'panel_name'] and the API address is always its «api».
|
|
* Without it the module works as a neutral one: provider list or a custom address.
|
|
*/
|
|
public static function brand()
|
|
{
|
|
static $brand = false;
|
|
if ($brand === false) {
|
|
$brand = null;
|
|
$file = __DIR__ . '/brand.php';
|
|
if (is_file($file)) {
|
|
$b = include $file;
|
|
if (is_array($b) && isset($b['api']) && preg_match('~^https://[a-z0-9.-]+(:[0-9]+)?/?$~i', (string) $b['api'])) {
|
|
$b['api'] = rtrim((string) $b['api'], '/');
|
|
$brand = $b + ['key' => '', 'name' => '', 'name_en' => '', 'panel' => '', 'panel_name' => ''];
|
|
}
|
|
}
|
|
}
|
|
return $brand;
|
|
}
|
|
|
|
private static function endpoint(array $params)
|
|
{
|
|
$fixed = self::brand();
|
|
if ($fixed) {
|
|
return $fixed['api'];
|
|
}
|
|
$brand = (string) ($params['brand'] ?? 'mozout');
|
|
$brands = self::brands();
|
|
if ($brand !== 'custom' && isset($brands[$brand])) {
|
|
return $brands[$brand][1];
|
|
}
|
|
$url = rtrim(trim((string) ($params['api_url'] ?? '')), '/');
|
|
if (!preg_match('~^https://[a-z0-9.-]+(:[0-9]+)?$~i', $url)) {
|
|
throw new \Exception(self::t(self::lang($params), 'E-mail Center: the API address must start with https:// and have no path (e.g. https://api.example.com).'));
|
|
}
|
|
return $url;
|
|
}
|
|
|
|
private static function key(array $params)
|
|
{
|
|
$key = trim((string) ($params['api_key'] ?? ''));
|
|
if (!preg_match('~^(sandbox|prod)_[A-Za-z0-9_-]{20,}$~', $key)) {
|
|
throw new \Exception(self::t(self::lang($params), 'E-mail Center: the API key is missing or not valid (it starts with sandbox_ or prod_).'));
|
|
}
|
|
return $key;
|
|
}
|
|
|
|
private static function addresses($list)
|
|
{
|
|
$out = [];
|
|
foreach ((array) $list as $k => $r) {
|
|
$email = is_array($r) ? (string) ($r[0] ?? $k) : (string) $k;
|
|
$email = trim($email);
|
|
if ($email !== '' && !in_array(strtolower($email), array_map('strtolower', $out), true)) {
|
|
$out[] = $email;
|
|
}
|
|
}
|
|
return $out;
|
|
}
|
|
|
|
private static function mimeType($name)
|
|
{
|
|
$map = [
|
|
'pdf' => 'application/pdf', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
|
|
'gif' => 'image/gif', 'txt' => 'text/plain', 'csv' => 'text/csv', 'zip' => 'application/zip',
|
|
'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
'xls' => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
'ics' => 'text/calendar', 'html' => 'text/html',
|
|
];
|
|
$ext = strtolower((string) pathinfo($name, PATHINFO_EXTENSION));
|
|
return $map[$ext] ?? '';
|
|
}
|
|
|
|
private static function uuid()
|
|
{
|
|
$b = random_bytes(16);
|
|
$b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
|
|
$b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
|
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
|
|
}
|
|
|
|
private static function setting($name)
|
|
{
|
|
try {
|
|
return \WHMCS\Config\Setting::getValue($name);
|
|
} catch (\Throwable $e) {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
private static function currentAdminEmail()
|
|
{
|
|
try {
|
|
$admin = (new \WHMCS\Authentication\CurrentUser())->admin();
|
|
if ($admin && !empty($admin->email)) {
|
|
return (string) $admin->email;
|
|
}
|
|
} catch (\Throwable $e) {
|
|
}
|
|
return '';
|
|
}
|
|
|
|
private static function adminIsPortuguese()
|
|
{
|
|
$l = isset($_SESSION['adminlang']) ? (string) $_SESSION['adminlang'] : '';
|
|
try {
|
|
$admin = (new \WHMCS\Authentication\CurrentUser())->admin();
|
|
if ($l === '' && $admin && !empty($admin->language)) {
|
|
$l = (string) $admin->language;
|
|
}
|
|
} catch (\Throwable $e) {
|
|
}
|
|
if ($l === '') {
|
|
$l = (string) self::setting('Language');
|
|
}
|
|
return self::langFile($l) === 'portuguese';
|
|
}
|
|
|
|
private static function lang(array $params)
|
|
{
|
|
$l = (string) ($params['language'] ?? '');
|
|
if ($l === 'pt' || $l === 'en') {
|
|
return $l;
|
|
}
|
|
return self::adminIsPortuguese() ? 'pt' : 'en';
|
|
}
|
|
|
|
/**
|
|
* Text in the chosen language. The code holds the English text, which is also the key in
|
|
* lang/english.php and lang/portuguese.php. $lang is 'pt', 'en' or a WHMCS language name:
|
|
* any name starting with «portuguese» (portuguese-pt, portuguese-br, ...) uses portuguese.php,
|
|
* the rest english.php. A missing key falls back to English. Extra arguments fill %s.
|
|
*/
|
|
private static function t($lang, $en, ...$args)
|
|
{
|
|
$file = self::langFile($lang);
|
|
$s = self::strings($file);
|
|
if (isset($s[$en])) {
|
|
$text = $s[$en];
|
|
} else {
|
|
$e = self::strings('english');
|
|
$text = isset($e[$en]) ? $e[$en] : $en;
|
|
}
|
|
return $args ? vsprintf($text, $args) : $text;
|
|
}
|
|
|
|
private static function langFile($lang)
|
|
{
|
|
$lang = strtolower((string) $lang);
|
|
return ($lang === 'pt' || strpos($lang, 'portuguese') === 0 || strpos($lang, 'pt-') === 0 || strpos($lang, 'pt_') === 0)
|
|
? 'portuguese' : 'english';
|
|
}
|
|
|
|
private static function strings($file)
|
|
{
|
|
static $cache = [];
|
|
if (!isset($cache[$file])) {
|
|
$cache[$file] = [];
|
|
$path = __DIR__ . '/lang/' . $file . '.php';
|
|
if (is_file($path)) {
|
|
$data = include $path;
|
|
if (is_array($data)) {
|
|
$cache[$file] = $data;
|
|
}
|
|
}
|
|
}
|
|
return $cache[$file];
|
|
}
|
|
}
|