Send mail locally again: message_queue + PHPMailer over SMTP
Outbound email was relayed to the hub's /notify endpoint, so this install had
no SMTP configuration of its own and no way to see what had been sent. Bring
delivery back in-house, following the fotografia.andmore.pt stack rather than
inventing a second shape for it.
- Submodule bumped 603ff84 -> ea3616a, the pin fotografia already uses. That
is what provides functions_mail.php (shared transport), functions_settings.php
(platform_smtp_config + encrypted settings) and compat_secrets.php. Verified
no function-name collisions with this repo's own config/functions_settings.php:
platform-tools namespaces everything platform_*.
- PHPMailer 7.1.1 vendored at vendor/PHPMailer/src/. platform_mail_available()
looks for exactly this hand-vendored layout before falling back to composer's
autoloader, so the host needs no shell and no composer install. LGPL-2.1
license text included.
- config/functions_queue.php replaced: was a thin facade over the hub relay,
now fotografia's real queue. Rows are claimed atomically, retried with
exponential backoff up to max_attempts, and park in 'failed' with the real
SMTP rejection in last_error.
- SMTP resolution matches the fleet: .env wins for the SMTP_* constants, while
the actual send goes through platform_smtp_config($pdo), which is DB-first.
That ordering is deliberate -- the database is the half an operator can
change from the backoffice without shell access. Empty SMTP_HOST falls back
to PHP mail().
- Sistema -> Comunicações (views/sysadmin/comms.php): credentials plus a live
SMTP connection test and a verdict on what would happen to a message sent
right now. Secret-valued settings are write-only in the form and encrypted
at rest (AES-256-GCM, key from .env, never in the DB dump). Which keys count
as secret is platform_settings_is_secret()'s decision, not a list kept here.
- Sistema -> Mensagens (views/sysadmin/messages.php): the queue monitor.
Filters, per-message detail with last_error, and retry/cancel/archive.
Retry flushes inline so the operator sees the outcome immediately.
- cron.php drains the queue every 5 minutes, serialised with a lock file, and
runs retention once a day. Over HTTP it answers 404 until CRON_TOKEN is set
to something other than replace_me. Deliberately not a copy of fotografia's
cron: the session-reminder, download-digest and photo-archive steps have no
modules here and would be dead code.
- config/functions_notify_client.php deleted, and ANDMORE_ID_URL with it --
the hub relay was its only caller.
Verified without a database: PHP lint across the tree; PHPMailer builds a full
MIME message with RFC 2047 UTF-8 subject encoding from the three vendored files;
platform_mail_available() finds them; platform_mail_make() returns a correctly
configured mailer; the diagnosis states report Operacional / Não configurado.
NOT verified: the settings encryption round-trip -- this machine's PHP has no
openssl extension, so platform_secret_key() returns null and values pass through
in clear. The code degrades safely (stores the value rather than losing it) and
the Comunicações page warns when the key is unavailable.
Deployment: apply database/migration_20260913_message_queue.sql, set SMTP in
Comunicações or .env, set APP_SECRET_KEY, and schedule cron.php.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3626080599
commit
d5cb50b432
16 files changed
+8980
-134
No files matched your search
+35
-18
@@ -17,27 +17,44 @@ DB_NAME=fitme3070
|
|||||||
DB_USER=root
|
DB_USER=root
|
||||||
DB_PASS=
|
DB_PASS=
|
||||||
|
|
||||||
# ─── Notifications (email + SMS) ─────────────────────────────────────────────
|
# ─── Email / SMTP ───────────────────────────────────────────────
|
||||||
# Delivery is centralized at id.andmore.pt (/notify). This app does not send
|
# This app sends its own mail again (PHPMailer over SMTP) — nothing is relayed
|
||||||
# mail/SMS itself. Auth + endpoint are ANDMORE_ID_URL + NOTIFY_API_KEY below.
|
# through the hub any more. Anything set here WINS over the same setting in
|
||||||
|
# Sistema → Comunicações, so leave these blank if you want to manage SMTP from
|
||||||
|
# the backoffice. Empty SMTP_HOST falls back to PHP's mail().
|
||||||
|
SMTP_HOST=
|
||||||
|
SMTP_PORT=587
|
||||||
|
SMTP_SECURE=tls
|
||||||
|
SMTP_USERNAME=
|
||||||
|
SMTP_PASSWORD=
|
||||||
|
|
||||||
# ─── Backup ─────────────────────────────────────────────────────────────────
|
# ─── Encryption key for settings stored in the DB ─────────────────────────
|
||||||
BACKUP_TOKEN=replace_me
|
# smtp_password / twilio_token are AES-256-GCM encrypted at rest so they are not
|
||||||
BACKUP_KEEP_DAYS=7
|
# readable in a database dump. Without a key they are stored in plain text and
|
||||||
|
# the Comunicações page warns about it. Any long random string works.
|
||||||
|
# (BACKUP_TOKEN is used as a fallback when this is unset.)
|
||||||
|
APP_SECRET_KEY=
|
||||||
|
|
||||||
# ─── Andmore hub (notifications only) ────────────────────────────────────────
|
# ─── Twilio (SMS / WhatsApp) — optional ───────────────────────────────
|
||||||
# This install owns its own login: passwords live in users.password_hash and
|
# Leave empty unless the sms/whatsapp channels are actually used. Email works
|
||||||
# views/auth/login.php is a real form. The Andmore ID / SSO delegation was
|
# without them.
|
||||||
# removed — no IDENTITY_MODE, no SSO_* keys, no central sso_sessions table.
|
TWILIO_SID=
|
||||||
#
|
TWILIO_TOKEN=
|
||||||
# ANDMORE_ID_URL stays only because outbound email/SMS is still relayed through
|
TWILIO_SMS_FROM=
|
||||||
# the hub's /notify endpoint (see NOTIFY_API_KEY below).
|
TWILIO_WHATSAPP_FROM=
|
||||||
ANDMORE_ID_URL=https://hub.andmore.pt/
|
|
||||||
|
|
||||||
# ─── Notificações centralizadas (id.andmore.pt /notify) ──────────────────────
|
# ─── Dev safety nets (ignored when APP_ENV=prod) ───────────────────────
|
||||||
# App key for POST {ANDMORE_ID_URL}notify/send. Minted on id.andmore.pt →
|
# EMAIL_DEV_REDIRECT — send every message here instead of the real recipient.
|
||||||
# Notificações → Chaves de app.
|
# EMAIL_DEV_PRINT — skip SMTP entirely, log to logs/message_dev.log. Wins.
|
||||||
NOTIFY_API_KEY=
|
EMAIL_DEV_REDIRECT=
|
||||||
|
EMAIL_DEV_PRINT=false
|
||||||
|
|
||||||
|
# ─── Cron ────────────────────────────────────────────────────────
|
||||||
|
# cron.php drains the message queue every 5 minutes. Over the shell no token is
|
||||||
|
# needed. Over HTTP it is the only protection, and cron.php answers 404 until it
|
||||||
|
# is set to something other than replace_me:
|
||||||
|
# */5 * * * * curl -fsS "https://fitme3070.pt/cron.php?token=<CRON_TOKEN>"
|
||||||
|
CRON_TOKEN=replace_me
|
||||||
|
|
||||||
# ─── Hub social content endpoint (api/hub-content.php) ─────────────────────────
|
# ─── Hub social content endpoint (api/hub-content.php) ─────────────────────────
|
||||||
# Shared secret the hub social-post generator signs its pull requests with.
|
# Shared secret the hub social-post generator signs its pull requests with.
|
||||||
|
|||||||
+3
-14
@@ -13,9 +13,9 @@
|
|||||||
|
|
||||||
// ─── Environment ──────────────────────────────────────────────────────────────
|
// ─── Environment ──────────────────────────────────────────────────────────────
|
||||||
define('APP_ENV', env('APP_ENV', 'prod'));
|
define('APP_ENV', env('APP_ENV', 'prod'));
|
||||||
// Email/SMS delivery — including the dev redirect/print safety net — now lives at
|
// Email/SMS delivery — including the dev redirect/print safety net — happens in
|
||||||
// id.andmore.pt (/notify). See config/functions_notify_client.php. NOTIFY_API_KEY
|
// this app. See config/functions_queue.php (message_queue + PHPMailer over SMTP)
|
||||||
// (in .env) authenticates this app to the central service.
|
// and config/functions.php for the SMTP_* constants.
|
||||||
|
|
||||||
if (APP_ENV !== 'prod') {
|
if (APP_ENV !== 'prod') {
|
||||||
ini_set('display_errors', '1');
|
ini_set('display_errors', '1');
|
||||||
@@ -27,14 +27,3 @@ if (APP_ENV !== 'prod') {
|
|||||||
}
|
}
|
||||||
|
|
||||||
require_once __DIR__ . '/error_handler.php';
|
require_once __DIR__ . '/error_handler.php';
|
||||||
|
|
||||||
// ─── Andmore hub (notifications only) ────────────────────────────────────────
|
|
||||||
// This install owns its own identity: passwords live in `users.password_hash`
|
|
||||||
// and views/auth/login.php is a real form (see config/auth.php). The former
|
|
||||||
// Andmore ID / SSO delegation — config/sso.php, the am_sso cookie, the central
|
|
||||||
// sso_sessions table and the one-time ticket redeem — was removed.
|
|
||||||
//
|
|
||||||
// ANDMORE_ID_URL survives because outbound email/SMS is still centralized at
|
|
||||||
// the hub's /notify endpoint; see config/functions_notify_client.php. It has
|
|
||||||
// nothing to do with authentication anymore.
|
|
||||||
define('ANDMORE_ID_URL', rtrim(env('ANDMORE_ID_URL', 'https://hub.andmore.pt'), '/') . '/');
|
|
||||||
+31
-3
@@ -11,15 +11,15 @@ if (session_status() === PHP_SESSION_NONE) session_start();
|
|||||||
|
|
||||||
require_once __DIR__ . '/config.php'; // APP_ENV + hub notify URL + error_handler
|
require_once __DIR__ . '/config.php'; // APP_ENV + hub notify URL + error_handler
|
||||||
require_once __DIR__ . '/functions_settings.php'; // setting() + system_settings cache
|
require_once __DIR__ . '/functions_settings.php'; // setting() + system_settings cache
|
||||||
|
require_once __DIR__ . '/functions_secrets.php'; // setting_or_env()/setting_secret() + AES-GCM at rest
|
||||||
require_once __DIR__ . '/functions_db.php'; // generic DB helpers
|
require_once __DIR__ . '/functions_db.php'; // generic DB helpers
|
||||||
require_once __DIR__ . '/functions_user.php'; // auth_login/register, password reset, user creators
|
require_once __DIR__ . '/functions_user.php'; // auth_login/register, password reset, user creators
|
||||||
require_once __DIR__ . '/auth.php'; // require_login/admin/staff/sysadmin(), role helpers
|
require_once __DIR__ . '/auth.php'; // require_login/admin/staff/sysadmin(), role helpers
|
||||||
require_once __DIR__ . '/functions_throttle.php'; // per-IP attempt throttle for the auth endpoints
|
require_once __DIR__ . '/functions_throttle.php'; // per-IP attempt throttle for the auth endpoints
|
||||||
require_once __DIR__ . '/functions_migrations.php';// platform_update.php migrations runner
|
require_once __DIR__ . '/functions_migrations.php';// platform_update.php migrations runner
|
||||||
|
|
||||||
// Outbound delivery is centralized at id.andmore.pt — no local PHPMailer/SMTP.
|
// Outbound delivery happens in this app — PHPMailer over SMTP, no central relay.
|
||||||
require_once __DIR__ . '/functions_notify_client.php'; // notify_remote_send()
|
require_once __DIR__ . '/functions_queue.php'; // message_queue + enqueue_*/flush_message
|
||||||
require_once __DIR__ . '/functions_queue.php'; // enqueue_*/flush_message façade → relay
|
|
||||||
require_once __DIR__ . '/functions_csrf.php';
|
require_once __DIR__ . '/functions_csrf.php';
|
||||||
require_once __DIR__ . '/functions_html.php'; // allowlist HTML sanitiser (clean_richtext/clean_map_embed)
|
require_once __DIR__ . '/functions_html.php'; // allowlist HTML sanitiser (clean_richtext/clean_map_embed)
|
||||||
require_once __DIR__ . '/ci_compat.php'; // CI4 view-helper shim (script_tag/link_tag/view/esc/session)
|
require_once __DIR__ . '/ci_compat.php'; // CI4 view-helper shim (script_tag/link_tag/view/esc/session)
|
||||||
@@ -48,6 +48,34 @@ define('EMAIL_FROM', (string) setting('email_from', 'noreply
|
|||||||
define('EMAIL_FROM_NAME', (string) setting('email_from_name', 'FitMe 3070'));
|
define('EMAIL_FROM_NAME', (string) setting('email_from_name', 'FitMe 3070'));
|
||||||
define('EMAIL_SUBJECT_PREFIX', (string) setting('email_subject_prefix', '[FitMe 3070] '));
|
define('EMAIL_SUBJECT_PREFIX', (string) setting('email_subject_prefix', '[FitMe 3070] '));
|
||||||
|
|
||||||
|
// ─── SMTP ───────────────────────────────────────────────────────────
|
||||||
|
// .env wins, then system_settings (smtp_password encrypted at rest). These
|
||||||
|
// constants are what the diagnostics page shows; the actual send resolves
|
||||||
|
// through platform_smtp_config($pdo), which is DB-first — that is the value an
|
||||||
|
// operator can change from the backoffice without shell access.
|
||||||
|
// An empty SMTP_HOST makes PHPMailer fall back to PHP mail().
|
||||||
|
define('SMTP_HOST', setting_or_env('smtp_host', 'SMTP_HOST'));
|
||||||
|
define('SMTP_PORT', (int) (setting_or_env('smtp_port', 'SMTP_PORT', '587') ?: 587));
|
||||||
|
define('SMTP_SECURE', setting_or_env('smtp_secure', 'SMTP_SECURE', 'tls'));
|
||||||
|
define('SMTP_USERNAME', setting_or_env('smtp_username', 'SMTP_USERNAME'));
|
||||||
|
define('SMTP_PASSWORD', setting_secret('smtp_password', 'SMTP_PASSWORD'));
|
||||||
|
|
||||||
|
// ─── Twilio (SMS / WhatsApp) ───────────────────────────────────────
|
||||||
|
// Optional. Left empty the sms/whatsapp drivers refuse with a clear message
|
||||||
|
// instead of half-sending; email is unaffected.
|
||||||
|
define('TWILIO_SID', setting_or_env('twilio_sid', 'TWILIO_SID'));
|
||||||
|
define('TWILIO_TOKEN', setting_secret('twilio_token', 'TWILIO_TOKEN'));
|
||||||
|
define('TWILIO_SMS_FROM', setting_or_env('twilio_sms_from', 'TWILIO_SMS_FROM'));
|
||||||
|
define('TWILIO_WHATSAPP_FROM', setting_or_env('twilio_whatsapp_from', 'TWILIO_WHATSAPP_FROM'));
|
||||||
|
|
||||||
|
// ─── Dev safety nets ───────────────────────────────────────────────
|
||||||
|
// Only consulted when APP_ENV !== 'prod', so a misconfigured production install
|
||||||
|
// can never silently swallow mail.
|
||||||
|
// EMAIL_DEV_PRINT — skip SMTP entirely, write to logs/message_dev.log.
|
||||||
|
// EMAIL_DEV_REDIRECT — send everything to this address instead of the real one.
|
||||||
|
define('EMAIL_DEV_PRINT', filter_var(env('EMAIL_DEV_PRINT', 'false'), FILTER_VALIDATE_BOOLEAN));
|
||||||
|
define('EMAIL_DEV_REDIRECT', (string) env('EMAIL_DEV_REDIRECT', ''));
|
||||||
|
|
||||||
// ─── URL helper ───────────────────────────────────────────────────────────────
|
// ─── URL helper ───────────────────────────────────────────────────────────────
|
||||||
// Always use for Location: redirects and internal links.
|
// Always use for Location: redirects and internal links.
|
||||||
function base_url(string $path = ''): string {
|
function base_url(string $path = ''): string {
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
<?php
|
|
||||||
// Client for the centralized notification service at id.andmore.pt (/notify).
|
|
||||||
//
|
|
||||||
// fotografia no longer sends mail/SMS itself — delivery is centralized. This is
|
|
||||||
// the single egress point: it POSTs a message to {ANDMORE_ID_URL}notify/send.php
|
|
||||||
// authenticated with the per-app key (NOTIFY_API_KEY, minted on id.andmore.pt →
|
|
||||||
// Notificações → Chaves de app). The legacy enqueue_email()/flush_message() pair
|
|
||||||
// in config/functions_queue.php is now a thin façade over this.
|
|
||||||
//
|
|
||||||
// The app key is sent in the JSON body (not a header) to dodge Apache stripping
|
|
||||||
// the Authorization header on some setups.
|
|
||||||
|
|
||||||
function notify_remote_send(array $payload): array {
|
|
||||||
$base = defined('ANDMORE_ID_URL') ? ANDMORE_ID_URL : rtrim((string) env('ANDMORE_ID_URL', ''), '/') . '/';
|
|
||||||
$key = (string) env('NOTIFY_API_KEY', '');
|
|
||||||
if ($base === '' || $key === '') {
|
|
||||||
error_log('notify_remote_send: ANDMORE_ID_URL or NOTIFY_API_KEY not configured');
|
|
||||||
return ['ok' => false, 'error' => 'notify_not_configured'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$payload['app_key'] = $key;
|
|
||||||
$url = rtrim($base, '/') . '/notify/send.php';
|
|
||||||
|
|
||||||
$ch = curl_init($url);
|
|
||||||
curl_setopt_array($ch, [
|
|
||||||
CURLOPT_POST => true,
|
|
||||||
CURLOPT_RETURNTRANSFER => true,
|
|
||||||
CURLOPT_TIMEOUT => 20,
|
|
||||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
|
||||||
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
|
||||||
]);
|
|
||||||
$resp = curl_exec($ch);
|
|
||||||
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
||||||
$err = curl_error($ch);
|
|
||||||
curl_close($ch);
|
|
||||||
|
|
||||||
if ($resp === false) {
|
|
||||||
error_log("notify_remote_send: transport error ($err) calling $url");
|
|
||||||
return ['ok' => false, 'error' => 'transport_error'];
|
|
||||||
}
|
|
||||||
$data = json_decode($resp, true);
|
|
||||||
if (!is_array($data)) {
|
|
||||||
error_log("notify_remote_send: bad response (HTTP $code) from $url: " . substr((string) $resp, 0, 300));
|
|
||||||
return ['ok' => false, 'error' => 'bad_response', 'http' => $code];
|
|
||||||
}
|
|
||||||
if (empty($data['ok'])) {
|
|
||||||
error_log("notify_remote_send: notify error (HTTP $code): " . ($data['error'] ?? '?'));
|
|
||||||
}
|
|
||||||
return $data;
|
|
||||||
}
|
|
||||||
+534
-48
@@ -1,66 +1,552 @@
|
|||||||
<?php
|
<?php
|
||||||
// Outbound delivery — now centralized at id.andmore.pt (/notify).
|
// Local outbound message queue (email + SMS + WhatsApp) backed by `message_queue`.
|
||||||
//
|
//
|
||||||
// fotografia no longer runs its own SMTP/n8n queue. The local `message_queue`
|
// Delivery happens in this app — there is no central relay. Each channel has a
|
||||||
// table, the Monitor UI (views/sysadmin/messages.php) and the cron drainer
|
// small driver:
|
||||||
// (api/process_queue.php) were removed when delivery merged into id.andmore.pt.
|
// email → PHPMailer over SMTP (or PHP mail() when SMTP_HOST is empty)
|
||||||
|
// sms → Twilio Messages API, plain SMS sender
|
||||||
|
// whatsapp → Twilio Messages API, `whatsapp:` sender
|
||||||
//
|
//
|
||||||
// This file is a thin compatibility façade so the dozens of existing call sites
|
// Standard pattern for transactional sends (immediate delivery expected):
|
||||||
// keep working unchanged. They use the historical two-step contract:
|
// $id = enqueue_email([...]);
|
||||||
// $id = enqueue_email([...]); // stage the message
|
// return flush_message($id);
|
||||||
// return flush_message($id); // send it (now: relay to id.andmore.pt)
|
|
||||||
//
|
//
|
||||||
// enqueue_*() stages the payload in-request; flush_message() ships it through
|
// Standard pattern for broadcasts (deferred is acceptable):
|
||||||
// notify_remote_send() (see config/functions_notify_client.php) and returns the
|
// foreach ($recipients as $u) {
|
||||||
// real sent/failed result. Bulk callers that loop enqueue+flush still work.
|
// enqueue_email([...]);
|
||||||
|
// }
|
||||||
|
// // cron.php drains them within 5 minutes; no inline flush needed.
|
||||||
|
//
|
||||||
|
// Every row keeps its status, attempt count, last error and timestamps, so the
|
||||||
|
// Monitor page (views/sysadmin/messages.php) can show what was sent and retry
|
||||||
|
// what wasn't.
|
||||||
|
|
||||||
$GLOBALS['_notify_staged'] = [];
|
const MESSAGE_QUEUE_VALID_STATUSES = ['pending', 'sending', 'sent', 'failed', 'cancelled'];
|
||||||
$GLOBALS['_notify_seq'] = 0;
|
const MESSAGE_QUEUE_VALID_CHANNELS = ['email', 'sms', 'whatsapp'];
|
||||||
|
|
||||||
function enqueue_email(array $data): int { return _notify_stage('email', $data); }
|
// ─── Enqueue ─────────────────────────────────────────────────────────────────
|
||||||
function enqueue_sms(array $data): int { return _notify_stage('sms', $data); }
|
|
||||||
|
|
||||||
function _notify_stage(string $channel, array $data): int {
|
function enqueue_email(array $data): int {
|
||||||
$id = ++$GLOBALS['_notify_seq'];
|
return _enqueue_message('email', $data);
|
||||||
$GLOBALS['_notify_staged'][$id] = ['channel' => $channel] + $data;
|
|
||||||
return $id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Relay a staged message to id.andmore.pt and return true on success. The local
|
function enqueue_sms(array $data): int {
|
||||||
// `to_user_id` is intentionally NOT forwarded — it's a fotografia id, not a
|
return _enqueue_message('sms', $data);
|
||||||
// canonical id.andmore.pt user id (the central queue FK would reject it). The
|
}
|
||||||
// recipient address + this app's key are enough; the central log records origin.
|
|
||||||
|
function enqueue_whatsapp(array $data): int {
|
||||||
|
return _enqueue_message('whatsapp', $data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _enqueue_message(string $channel, array $data): int {
|
||||||
|
global $pdo;
|
||||||
|
$stmt = $pdo->prepare("
|
||||||
|
INSERT INTO message_queue
|
||||||
|
(channel, to_user_id, to_address, to_name, reply_to, subject, body, alt_body,
|
||||||
|
context_type, context_id, scheduled_for, max_attempts, created_by)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
");
|
||||||
|
$stmt->execute([
|
||||||
|
$channel,
|
||||||
|
$data['to_user_id'] ?? null,
|
||||||
|
$data['to_address'],
|
||||||
|
$data['to_name'] ?? null,
|
||||||
|
// Sem isto, responder ao aviso de contacto respondia ao remetente da
|
||||||
|
// casa e nao a quem escreveu -- o flush_message() ja o passava ao
|
||||||
|
// mailer, era o INSERT que nao o guardava.
|
||||||
|
$data['reply_to'] ?? null,
|
||||||
|
$data['subject'] ?? null,
|
||||||
|
$data['body'],
|
||||||
|
$data['alt_body'] ?? null,
|
||||||
|
$data['context_type'] ?? null,
|
||||||
|
$data['context_id'] ?? null,
|
||||||
|
$data['scheduled_for'] ?? null,
|
||||||
|
$data['max_attempts'] ?? 3,
|
||||||
|
$data['created_by'] ?? ($_SESSION['user']['id'] ?? null),
|
||||||
|
]);
|
||||||
|
return (int) $pdo->lastInsertId();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Flush a single message ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Atomically claims a pending/failed row, sends it, updates status.
|
||||||
|
// Returns true on send success, false otherwise.
|
||||||
function flush_message(int $id): bool {
|
function flush_message(int $id): bool {
|
||||||
$data = $GLOBALS['_notify_staged'][$id] ?? null;
|
global $pdo;
|
||||||
if (!$data) return false;
|
|
||||||
unset($GLOBALS['_notify_staged'][$id]);
|
|
||||||
|
|
||||||
$channel = $data['channel'] ?? 'email';
|
// Atomic claim — only one worker proceeds. Guards against the cron run and
|
||||||
$payload = [
|
// an inline flush racing for the same row.
|
||||||
'channel' => $channel,
|
$claim = $pdo->prepare("
|
||||||
'to' => $data['to_address'] ?? '',
|
UPDATE message_queue
|
||||||
'to_name' => $data['to_name'] ?? null,
|
SET status = 'sending', attempts = attempts + 1
|
||||||
'body' => $data['body'] ?? '',
|
WHERE id = ?
|
||||||
];
|
AND status IN ('pending', 'failed')
|
||||||
if ($channel === 'email') {
|
");
|
||||||
// Preserve the historical subject prefix that the old SMTP path applied.
|
$claim->execute([$id]);
|
||||||
$prefix = defined('EMAIL_SUBJECT_PREFIX') ? EMAIL_SUBJECT_PREFIX : '';
|
if ($claim->rowCount() === 0) return false;
|
||||||
$payload['subject'] = $prefix . ($data['subject'] ?? '');
|
|
||||||
$payload['alt_body'] = $data['alt_body'] ?? null;
|
$row = db_get_message($pdo, $id);
|
||||||
|
if (!$row) return false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
match ($row['channel']) {
|
||||||
|
'email' => _flush_email($row),
|
||||||
|
'sms' => _flush_twilio($row, 'sms'),
|
||||||
|
'whatsapp' => _flush_twilio($row, 'whatsapp'),
|
||||||
|
default => throw new RuntimeException("Unknown channel: {$row['channel']}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
$pdo->prepare("UPDATE message_queue SET status='sent', sent_at=NOW(), last_error=NULL, next_attempt_at=NULL WHERE id=?")->execute([$id]);
|
||||||
|
return true;
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// `attempts` was already incremented by the claim, so it reflects this
|
||||||
|
// attempt. Once it reaches max_attempts the row parks in 'failed' and
|
||||||
|
// only a manual retry (Monitor page) revives it.
|
||||||
|
$maxed = ((int) $row['attempts']) >= ((int) $row['max_attempts']);
|
||||||
|
$newStatus = $maxed ? 'failed' : 'pending';
|
||||||
|
// Exponential backoff: 2^attempts minutes (2, 4, 8, ...)
|
||||||
|
$nextAt = $maxed ? null : date('Y-m-d H:i:s', time() + (60 * (2 ** (int) $row['attempts'])));
|
||||||
|
$pdo->prepare("UPDATE message_queue SET status=?, last_error=?, next_attempt_at=? WHERE id=?")
|
||||||
|
->execute([$newStatus, mb_substr($e->getMessage(), 0, 2000), $nextAt, $id]);
|
||||||
|
error_log("flush_message($id) failed: {$e->getMessage()}");
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
if (!empty($data['context_type'])) {
|
|
||||||
$payload['context'] = ['type' => $data['context_type'], 'id' => $data['context_id'] ?? null];
|
|
||||||
}
|
|
||||||
if (!empty($data['scheduled_for'])) {
|
|
||||||
$payload['scheduled_for'] = $data['scheduled_for'];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$r = notify_remote_send($payload);
|
// ─── Driver: email (PHPMailer / SMTP) ────────────────────────────────────────
|
||||||
return !empty($r['ok']) && (($r['status'] ?? '') !== 'failed');
|
|
||||||
|
function _flush_email(array $row): void {
|
||||||
|
// Dev-mode debug print: skip SMTP entirely, write the email to a log file
|
||||||
|
// and a short summary to PHP's error_log. Kept here rather than in the
|
||||||
|
// shared transport because it writes this app's own log format.
|
||||||
|
if (APP_ENV !== 'prod' && EMAIL_DEV_PRINT) {
|
||||||
|
_dev_print_message($row, 'EMAIL');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// No local queue to drain anymore. Kept as a harmless no-op so any stray caller
|
// Transport is shared with the rest of the fleet (fotografia, hub). It applies
|
||||||
// (or scheduled task that wasn't updated) doesn't fatal.
|
// the EMAIL_DEV_REDIRECT safety net itself, including the [DEV] subject
|
||||||
|
// prefix and the banner naming the original recipient, so that logic no
|
||||||
|
// longer lives here.
|
||||||
|
require_once __DIR__ . '/../shared/platform-tools/functions_mail.php';
|
||||||
|
require_once __DIR__ . '/../shared/platform-tools/functions_settings.php';
|
||||||
|
|
||||||
|
// Settings come from system_settings first, .env second -- the fleet-wide
|
||||||
|
// standard. This install stores them there via setting_or_env(); this
|
||||||
|
// just reads them through the shared accessor instead of the local
|
||||||
|
// constants, so all three platforms resolve SMTP identically.
|
||||||
|
$r = platform_mail_send([
|
||||||
|
'to' => $row['to_address'],
|
||||||
|
'to_name' => $row['to_name'] ?? '',
|
||||||
|
// A fila não deve depender de uma constante que não é dela. O
|
||||||
|
// EMAIL_SUBJECT_PREFIX é definido no functions.php, e o index.php não o
|
||||||
|
// inclui de propósito -- o resultado era «Undefined constant» apanhado
|
||||||
|
// pelo flush_message() e gravado em last_error, com a página a dizer só
|
||||||
|
// "Ocorreu um erro" e nada no log do Apache.
|
||||||
|
'subject' => (defined('EMAIL_SUBJECT_PREFIX') ? EMAIL_SUBJECT_PREFIX : '') . ($row['subject'] ?? ''),
|
||||||
|
'body' => $row['body'],
|
||||||
|
'alt_body' => $row['alt_body'] ?: strip_tags($row['body']),
|
||||||
|
'reply_to' => $row['reply_to'] ?? '',
|
||||||
|
// O 4º argumento liga o tecto de envio (functions_mail_rate): 20/minuto e
|
||||||
|
// 200/hora, partilhados com o resto da quinta. Sem o $pdo o tecto não se
|
||||||
|
// aplica -- o módulo estava aqui e não estava a ser usado.
|
||||||
|
], dirname(__DIR__), platform_smtp_config($GLOBALS['pdo']), $GLOBALS['pdo'] ?? null);
|
||||||
|
|
||||||
|
// flush_message() treats a thrown exception as "retry later" and records
|
||||||
|
// last_error, so a failure must throw rather than return quietly.
|
||||||
|
if (empty($r['ok'])) {
|
||||||
|
throw new RuntimeException($r['error'] ?? 'Envio de email falhou.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Driver: SMS + WhatsApp (Twilio Messages API) ────────────────────────────
|
||||||
|
|
||||||
|
// Both channels hit the same endpoint; only the sender differs (WhatsApp needs
|
||||||
|
// the `whatsapp:` prefix on both From and To). Throws on any non-2xx so
|
||||||
|
// flush_message() records the reason and schedules a retry.
|
||||||
|
function _flush_twilio(array $row, string $channel): void {
|
||||||
|
if (APP_ENV !== 'prod' && SMS_DEV_PRINT) {
|
||||||
|
_dev_print_message($row, strtoupper($channel));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (TWILIO_SID === '' || TWILIO_TOKEN === '') {
|
||||||
|
throw new RuntimeException('Twilio não configurado (TWILIO_SID / TWILIO_TOKEN em falta no .env)');
|
||||||
|
}
|
||||||
|
|
||||||
|
$from = $channel === 'whatsapp' ? TWILIO_WHATSAPP_FROM : TWILIO_SMS_FROM;
|
||||||
|
if ($from === '') {
|
||||||
|
$var = $channel === 'whatsapp' ? 'TWILIO_WHATSAPP_FROM' : 'TWILIO_SMS_FROM';
|
||||||
|
throw new RuntimeException("Remetente não configurado ({$var} em falta no .env)");
|
||||||
|
}
|
||||||
|
|
||||||
|
$to = sms_normalize_number($row['to_address']);
|
||||||
|
if ($to === null) {
|
||||||
|
throw new RuntimeException("Número de telefone inválido: {$row['to_address']}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($channel === 'whatsapp') {
|
||||||
|
$from = 'whatsapp:' . $from;
|
||||||
|
$to = 'whatsapp:' . $to;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SMS/WhatsApp are plain text. Bodies built from the HTML email templates
|
||||||
|
// would arrive as raw markup, so strip tags defensively.
|
||||||
|
$body = trim($row['body']);
|
||||||
|
if ($body !== strip_tags($body)) {
|
||||||
|
$body = trim(html_entity_decode(strip_tags($body), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
|
||||||
|
}
|
||||||
|
if ($body === '') {
|
||||||
|
throw new RuntimeException('Mensagem vazia');
|
||||||
|
}
|
||||||
|
|
||||||
|
$url = 'https://api.twilio.com/2010-04-01/Accounts/' . rawurlencode(TWILIO_SID) . '/Messages.json';
|
||||||
|
$ch = curl_init($url);
|
||||||
|
curl_setopt_array($ch, [
|
||||||
|
CURLOPT_POST => true,
|
||||||
|
CURLOPT_RETURNTRANSFER => true,
|
||||||
|
CURLOPT_TIMEOUT => 20,
|
||||||
|
CURLOPT_USERPWD => TWILIO_SID . ':' . TWILIO_TOKEN,
|
||||||
|
CURLOPT_POSTFIELDS => http_build_query([
|
||||||
|
'From' => $from,
|
||||||
|
'To' => $to,
|
||||||
|
'Body' => $body,
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
$resp = curl_exec($ch);
|
||||||
|
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||||
|
$err = curl_error($ch);
|
||||||
|
curl_close($ch);
|
||||||
|
|
||||||
|
if ($resp === false) {
|
||||||
|
throw new RuntimeException("Erro de ligação ao Twilio: {$err}");
|
||||||
|
}
|
||||||
|
if ($code < 200 || $code >= 300) {
|
||||||
|
// Twilio returns {"code":21211,"message":"Invalid 'To' Phone Number"}.
|
||||||
|
// Surfacing that message is what makes the Monitor page actionable.
|
||||||
|
$data = json_decode((string) $resp, true);
|
||||||
|
$detail = is_array($data)
|
||||||
|
? trim(($data['message'] ?? '') . (isset($data['code']) ? " (Twilio {$data['code']})" : ''))
|
||||||
|
: substr((string) $resp, 0, 300);
|
||||||
|
throw new RuntimeException("Twilio HTTP {$code}: " . ($detail !== '' ? $detail : 'sem detalhe'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Coerces a stored phone into E.164. Accepts "+351915435034", "351915435034",
|
||||||
|
// "915435034" and anything with spaces/dashes. Returns null when it can't.
|
||||||
|
function sms_normalize_number(string $raw): ?string {
|
||||||
|
$raw = trim($raw);
|
||||||
|
$hasPlus = str_starts_with($raw, '+');
|
||||||
|
$digits = preg_replace('/\D+/', '', $raw) ?? '';
|
||||||
|
if ($digits === '') return null;
|
||||||
|
|
||||||
|
if ($hasPlus) {
|
||||||
|
return strlen($digits) >= 8 ? '+' . $digits : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$cc = preg_replace('/\D+/', '', SMS_DEFAULT_COUNTRY_CODE) ?? '';
|
||||||
|
// Already carries the country code (e.g. 351915435034) — just add the plus.
|
||||||
|
if ($cc !== '' && str_starts_with($digits, $cc) && strlen($digits) > strlen($cc)) {
|
||||||
|
return '+' . $digits;
|
||||||
|
}
|
||||||
|
// National number — prefix the default country code.
|
||||||
|
if ($cc !== '' && strlen($digits) >= 9) {
|
||||||
|
return '+' . $cc . $digits;
|
||||||
|
}
|
||||||
|
return strlen($digits) >= 11 ? '+' . $digits : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inverse of sms_normalize_number(): the human-readable form used for the
|
||||||
|
// printed contact on the public site. A national number under the default
|
||||||
|
// country code drops the prefix and is grouped in threes ("+351928363069" ->
|
||||||
|
// "928 363 069"); anything else keeps the international form, which is the
|
||||||
|
// only unambiguous way to write it.
|
||||||
|
function sms_format_display(string $e164): string {
|
||||||
|
$cc = preg_replace('/\D+/', '', SMS_DEFAULT_COUNTRY_CODE) ?? '';
|
||||||
|
$digits = preg_replace('/\D+/', '', $e164) ?? '';
|
||||||
|
if ($cc !== '' && str_starts_with($digits, $cc)) {
|
||||||
|
$national = substr($digits, strlen($cc));
|
||||||
|
if (strlen($national) === 9) {
|
||||||
|
return trim(chunk_split($national, 3, ' '));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $e164;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writes the full message to logs/message_dev.log and a summary line to PHP's
|
||||||
|
// error_log. Only called under APP_ENV != prod + EMAIL_DEV_PRINT / SMS_DEV_PRINT.
|
||||||
|
function _dev_print_message(array $row, string $label): void {
|
||||||
|
$logDir = __DIR__ . '/../logs';
|
||||||
|
$logFile = $logDir . '/message_dev.log';
|
||||||
|
if (!is_dir($logDir)) @mkdir($logDir, 0775, true);
|
||||||
|
|
||||||
|
$sep = str_repeat('─', 70) . "\n";
|
||||||
|
$entry = $sep
|
||||||
|
. sprintf("[%s] %s (DEV PRINT — não enviado)\n", date('Y-m-d H:i:s'), $label)
|
||||||
|
. sprintf("To: %s%s\n", $row['to_address'], $row['to_name'] ? " <{$row['to_name']}>" : '')
|
||||||
|
. sprintf("Subject: %s\n", EMAIL_SUBJECT_PREFIX . ($row['subject'] ?? ''))
|
||||||
|
. sprintf("Context: %s#%s\n", $row['context_type'] ?? '?', $row['context_id'] ?? '?')
|
||||||
|
. $sep
|
||||||
|
. ($row['body'] ?? '') . "\n\n";
|
||||||
|
@file_put_contents($logFile, $entry, FILE_APPEND);
|
||||||
|
|
||||||
|
error_log(sprintf(
|
||||||
|
'[%s-dev] %s → %s (registado em logs/message_dev.log)',
|
||||||
|
strtolower($label),
|
||||||
|
$row['subject'] ?? '(sem assunto)',
|
||||||
|
$row['to_address']
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Drain the queue ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Picks up to $limit due rows and processes them in turn. Returns counts.
|
||||||
|
// Called by cron.php every 5 minutes; also safe to call inline after a bulk
|
||||||
|
// enqueue.
|
||||||
function process_queue(int $limit = 20): array {
|
function process_queue(int $limit = 20): array {
|
||||||
return ['sent' => 0, 'failed' => 0, 'total' => 0];
|
global $pdo;
|
||||||
|
$limit = max(1, $limit);
|
||||||
|
$rows = $pdo->query("
|
||||||
|
SELECT id FROM message_queue
|
||||||
|
WHERE status = 'pending'
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
AND (scheduled_for IS NULL OR scheduled_for <= NOW())
|
||||||
|
AND (next_attempt_at IS NULL OR next_attempt_at <= NOW())
|
||||||
|
ORDER BY scheduled_for ASC, id ASC
|
||||||
|
LIMIT $limit
|
||||||
|
")->fetchAll();
|
||||||
|
|
||||||
|
$sent = 0; $failed = 0;
|
||||||
|
foreach ($rows as $r) {
|
||||||
|
if (flush_message((int) $r['id'])) $sent++; else $failed++;
|
||||||
|
}
|
||||||
|
return ['sent' => $sent, 'failed' => $failed, 'total' => count($rows)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rows stuck in 'sending' mean a worker died mid-send (fatal, timeout, deploy).
|
||||||
|
// Nothing would ever pick them up again, so the cron releases them back to
|
||||||
|
// 'pending' once they're older than $minutes.
|
||||||
|
function requeue_stuck_messages(PDO $pdo, int $minutes = 15): int {
|
||||||
|
$minutes = max(1, $minutes);
|
||||||
|
return (int) $pdo->exec("
|
||||||
|
UPDATE message_queue
|
||||||
|
SET status = 'pending',
|
||||||
|
last_error = CONCAT('Retomado após bloqueio em \"sending\" (', COALESCE(last_error, ''), ')')
|
||||||
|
WHERE status = 'sending'
|
||||||
|
AND updated_at < NOW() - INTERVAL $minutes MINUTE
|
||||||
|
");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── CRUD helpers (used by the Monitor admin page) ───────────────────────────
|
||||||
|
|
||||||
|
function db_get_message(PDO $pdo, int $id): array|false {
|
||||||
|
$stmt = $pdo->prepare("SELECT * FROM message_queue WHERE id = ?");
|
||||||
|
$stmt->execute([$id]);
|
||||||
|
return $stmt->fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch messages with rich filters.
|
||||||
|
*
|
||||||
|
* $filters keys:
|
||||||
|
* - statuses array<string> one or more valid statuses (OR)
|
||||||
|
* - channel string 'email' | 'sms' | 'whatsapp'
|
||||||
|
* - search string LIKE on to_address / to_name / subject
|
||||||
|
* - days int|null limit to created_at within N days
|
||||||
|
* - include_deleted bool default false (exclude soft-deleted)
|
||||||
|
* - only_deleted bool default false (only soft-deleted)
|
||||||
|
* - limit int default 200
|
||||||
|
*/
|
||||||
|
function db_get_messages(PDO $pdo, array $filters = []): array {
|
||||||
|
$statuses = $filters['statuses'] ?? [];
|
||||||
|
$channel = $filters['channel'] ?? null;
|
||||||
|
$search = trim((string) ($filters['search'] ?? ''));
|
||||||
|
$days = isset($filters['days']) ? (int) $filters['days'] : null;
|
||||||
|
$include_deleted = !empty($filters['include_deleted']);
|
||||||
|
$only_deleted = !empty($filters['only_deleted']);
|
||||||
|
$limit = max(1, (int) ($filters['limit'] ?? 200));
|
||||||
|
|
||||||
|
$where = [];
|
||||||
|
$args = [];
|
||||||
|
|
||||||
|
$statuses = array_values(array_intersect($statuses, MESSAGE_QUEUE_VALID_STATUSES));
|
||||||
|
if ($statuses) {
|
||||||
|
$where[] = 'q.status IN (' . implode(',', array_fill(0, count($statuses), '?')) . ')';
|
||||||
|
foreach ($statuses as $s) $args[] = $s;
|
||||||
|
}
|
||||||
|
if ($channel && in_array($channel, MESSAGE_QUEUE_VALID_CHANNELS, true)) {
|
||||||
|
$where[] = 'q.channel = ?';
|
||||||
|
$args[] = $channel;
|
||||||
|
}
|
||||||
|
if ($search !== '') {
|
||||||
|
$where[] = '(q.to_address LIKE ? OR q.to_name LIKE ? OR q.subject LIKE ?)';
|
||||||
|
$like = '%' . $search . '%';
|
||||||
|
$args[] = $like; $args[] = $like; $args[] = $like;
|
||||||
|
}
|
||||||
|
if ($days !== null && $days > 0) {
|
||||||
|
$where[] = "q.created_at >= NOW() - INTERVAL $days DAY";
|
||||||
|
}
|
||||||
|
if ($only_deleted) {
|
||||||
|
$where[] = 'q.deleted_at IS NOT NULL';
|
||||||
|
} elseif (!$include_deleted) {
|
||||||
|
$where[] = 'q.deleted_at IS NULL';
|
||||||
|
}
|
||||||
|
|
||||||
|
$sql = "
|
||||||
|
SELECT q.*, u.name AS user_name
|
||||||
|
FROM message_queue q
|
||||||
|
LEFT JOIN users u ON q.to_user_id = u.id
|
||||||
|
";
|
||||||
|
if ($where) $sql .= ' WHERE ' . implode(' AND ', $where);
|
||||||
|
$sql .= " ORDER BY q.created_at DESC LIMIT $limit";
|
||||||
|
$stmt = $pdo->prepare($sql);
|
||||||
|
$stmt->execute($args);
|
||||||
|
return $stmt->fetchAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Status counts (excluding soft-deleted by default).
|
||||||
|
* Optional $days limits the window. Adds a virtual 'deleted' key with the
|
||||||
|
* count of soft-deleted rows.
|
||||||
|
*/
|
||||||
|
function db_count_messages_by_status(PDO $pdo, ?int $days = null): array {
|
||||||
|
$where = ['deleted_at IS NULL'];
|
||||||
|
if ($days !== null && $days > 0) {
|
||||||
|
$where[] = "created_at >= NOW() - INTERVAL $days DAY";
|
||||||
|
}
|
||||||
|
$whereSql = 'WHERE ' . implode(' AND ', $where);
|
||||||
|
$counts = $pdo->query("
|
||||||
|
SELECT status, COUNT(*) AS n FROM message_queue $whereSql GROUP BY status
|
||||||
|
")->fetchAll(PDO::FETCH_KEY_PAIR);
|
||||||
|
|
||||||
|
foreach (MESSAGE_QUEUE_VALID_STATUSES as $s) $counts[$s] = (int) ($counts[$s] ?? 0);
|
||||||
|
$counts['deleted'] = (int) $pdo->query("SELECT COUNT(*) FROM message_queue WHERE deleted_at IS NOT NULL")->fetchColumn();
|
||||||
|
return $counts;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Number of rows waiting for the next cron pass. Drives the navbar badge.
|
||||||
|
function db_count_pending_messages(PDO $pdo): int {
|
||||||
|
return (int) $pdo->query("
|
||||||
|
SELECT COUNT(*) FROM message_queue
|
||||||
|
WHERE status IN ('pending','failed') AND deleted_at IS NULL
|
||||||
|
")->fetchColumn();
|
||||||
|
}
|
||||||
|
|
||||||
|
function db_retry_message(PDO $pdo, int $id): void {
|
||||||
|
// Resetting `attempts` is what makes a retry meaningful — otherwise a row
|
||||||
|
// that already burned its 3 attempts would fail straight back to 'failed'
|
||||||
|
// on the first error without any backoff.
|
||||||
|
$pdo->prepare("
|
||||||
|
UPDATE message_queue
|
||||||
|
SET status='pending', attempts=0, next_attempt_at=NULL, last_error=NULL, deleted_at=NULL
|
||||||
|
WHERE id=? AND status IN ('failed','cancelled')
|
||||||
|
")->execute([$id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function db_cancel_message(PDO $pdo, int $id): void {
|
||||||
|
$pdo->prepare("
|
||||||
|
UPDATE message_queue
|
||||||
|
SET status='cancelled'
|
||||||
|
WHERE id=? AND status IN ('pending','failed')
|
||||||
|
")->execute([$id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function db_soft_delete_message(PDO $pdo, int $id): void {
|
||||||
|
$pdo->prepare("
|
||||||
|
UPDATE message_queue
|
||||||
|
SET deleted_at = NOW()
|
||||||
|
WHERE id = ? AND deleted_at IS NULL AND status <> 'sending'
|
||||||
|
")->execute([$id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function db_restore_message(PDO $pdo, int $id): void {
|
||||||
|
$pdo->prepare("
|
||||||
|
UPDATE message_queue
|
||||||
|
SET deleted_at = NULL
|
||||||
|
WHERE id = ?
|
||||||
|
")->execute([$id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bulk soft-delete sent messages older than N days. Returns affected rows. */
|
||||||
|
function db_soft_delete_sent_older_than(PDO $pdo, int $days): int {
|
||||||
|
$days = max(1, (int) $days);
|
||||||
|
return (int) $pdo->exec("
|
||||||
|
UPDATE message_queue
|
||||||
|
SET deleted_at = NOW()
|
||||||
|
WHERE deleted_at IS NULL
|
||||||
|
AND status = 'sent'
|
||||||
|
AND sent_at < NOW() - INTERVAL $days DAY
|
||||||
|
");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hard-delete rows soft-deleted more than N days ago. Called by cron.php. */
|
||||||
|
function db_purge_deleted_messages(PDO $pdo, int $days): int {
|
||||||
|
$days = max(1, (int) $days);
|
||||||
|
return (int) $pdo->exec("
|
||||||
|
DELETE FROM message_queue
|
||||||
|
WHERE deleted_at IS NOT NULL
|
||||||
|
AND deleted_at < NOW() - INTERVAL $days DAY
|
||||||
|
");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Display helpers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function message_status_label(string $status): string {
|
||||||
|
return match ($status) {
|
||||||
|
'pending' => 'Pendente',
|
||||||
|
'sending' => 'A enviar',
|
||||||
|
'sent' => 'Enviado',
|
||||||
|
'failed' => 'Falhou',
|
||||||
|
'cancelled' => 'Cancelado',
|
||||||
|
default => ucfirst($status),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function message_status_badge(string $status): string {
|
||||||
|
$colour = match ($status) {
|
||||||
|
'pending' => 'secondary',
|
||||||
|
'sending' => 'info',
|
||||||
|
'sent' => 'success',
|
||||||
|
'failed' => 'danger',
|
||||||
|
'cancelled' => 'dark',
|
||||||
|
default => 'secondary',
|
||||||
|
};
|
||||||
|
return '<span class="badge text-bg-' . $colour . '">' . htmlspecialchars(message_status_label($status)) . '</span>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function message_channel_label(string $channel): string {
|
||||||
|
return match ($channel) {
|
||||||
|
'email' => 'Email',
|
||||||
|
'sms' => 'SMS',
|
||||||
|
'whatsapp' => 'WhatsApp',
|
||||||
|
default => ucfirst($channel),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function message_channel_icon(string $channel): string {
|
||||||
|
return match ($channel) {
|
||||||
|
'email' => 'bi-envelope',
|
||||||
|
'sms' => 'bi-chat-left-text',
|
||||||
|
'whatsapp' => 'bi-whatsapp',
|
||||||
|
default => 'bi-send',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function message_context_label(?string $type): string {
|
||||||
|
return match ($type) {
|
||||||
|
'gallery_delivery' => 'Entrega de galeria',
|
||||||
|
'session_scheduled' => 'Sessão agendada',
|
||||||
|
'session_reminder' => 'Lembrete de sessão',
|
||||||
|
'session_status' => 'Notificação de sessão',
|
||||||
|
'print_job_status' => 'Notificação de encomenda',
|
||||||
|
'password_reset' => 'Reposição de palavra-passe',
|
||||||
|
'newsletter' => 'Newsletter',
|
||||||
|
'broadcast' => 'Campanha (template)',
|
||||||
|
'quote_pack' => 'Pack de orçamento',
|
||||||
|
'quote_document' => 'Orçamento',
|
||||||
|
'voucher' => 'Vale oferta',
|
||||||
|
'contract_request' => 'Pedido de assinatura',
|
||||||
|
null, '' => '—',
|
||||||
|
default => $type,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
// ─── Secrets stored in system_settings ───────────────────────────────────────
|
||||||
|
//
|
||||||
|
// SMTP and Twilio credentials are configurable from the backoffice, which means
|
||||||
|
// they live in the database. That is a real tradeoff: the nightly job in
|
||||||
|
// cron.php keeps 30 database backups, so a plaintext password would sit in
|
||||||
|
// every one of them, and anyone who can read a dump would have the mail account.
|
||||||
|
//
|
||||||
|
// So secret-valued settings are encrypted at rest with AES-256-GCM. The key
|
||||||
|
// never goes in the database — it comes from .env, which is not in git and not
|
||||||
|
// in the DB dump. A dump on its own is therefore useless for recovering them.
|
||||||
|
//
|
||||||
|
// The cipher itself is no longer implemented here. It was one of two copies —
|
||||||
|
// hub2 had the same AES-256-GCM with a different key derivation, so a value
|
||||||
|
// written by one site would not open on the other. There is now a single
|
||||||
|
// implementation in shared/platform-tools; this file re-exports the short names
|
||||||
|
// (secret_encrypt, secret_decrypt, secret_is_encrypted, secret_mask,
|
||||||
|
// secrets_available, SECRET_PREFIX) that the sysadmin pages already call.
|
||||||
|
|
||||||
|
require_once dirname(__DIR__) . '/shared/platform-tools/compat_secrets.php';
|
||||||
|
|
||||||
|
// ─── Read helpers (site-specific, not crypto) ────────────────────────────────
|
||||||
|
//
|
||||||
|
// NOTE: these give .env precedence over the database, which is the opposite of
|
||||||
|
// platform_settings_get(). Deliberate here — an install can pin credentials in
|
||||||
|
// the environment and ignore the backoffice entirely — but it is a difference
|
||||||
|
// worth remembering when comparing behaviour with the other sites.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a secret-valued setting, decrypted.
|
||||||
|
*
|
||||||
|
* `.env` still wins when set, so an install can keep pinning credentials in the
|
||||||
|
* environment and ignore the DB entirely — that is the safer configuration and
|
||||||
|
* remains supported.
|
||||||
|
*/
|
||||||
|
function setting_secret(string $key, string $envKey = '', string $default = ''): string {
|
||||||
|
if ($envKey !== '') {
|
||||||
|
$fromEnv = (string) env($envKey, '');
|
||||||
|
if ($fromEnv !== '') return $fromEnv;
|
||||||
|
}
|
||||||
|
$stored = (string) setting($key, '');
|
||||||
|
return $stored !== '' ? secret_decrypt($stored) : $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a non-secret setting that may also be pinned in .env.
|
||||||
|
* Same precedence as setting_secret(), without the crypto.
|
||||||
|
*/
|
||||||
|
function setting_or_env(string $key, string $envKey, string $default = ''): string {
|
||||||
|
$fromEnv = (string) env($envKey, '');
|
||||||
|
if ($fromEnv !== '') return $fromEnv;
|
||||||
|
$stored = (string) setting($key, '');
|
||||||
|
return $stored !== '' ? $stored : $default;
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
<?php
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Scheduled maintenance runner. Designed to be fired every 5 minutes.
|
||||||
|
//
|
||||||
|
// Shell cron (preferred — no token, no web exposure):
|
||||||
|
// */5 * * * * /usr/bin/php /path/to/fitme3070.pt/cron.php >/dev/null 2>&1
|
||||||
|
//
|
||||||
|
// No shell? Hit it over HTTP with the shared secret from .env:
|
||||||
|
// */5 * * * * curl -fsS "https://fitme3070.pt/cron.php?token=<CRON_TOKEN>"
|
||||||
|
//
|
||||||
|
// What it does, in order:
|
||||||
|
// 1. Releases rows stuck in 'sending' (a worker died mid-send).
|
||||||
|
// 2. Drains the message queue (email via SMTP, SMS/WhatsApp via Twilio).
|
||||||
|
// 3. Soft-deletes messages sent more than 90 days ago, then hard-deletes
|
||||||
|
// rows that have been soft-deleted for another 90.
|
||||||
|
//
|
||||||
|
// Every run is serialised with a lock file, so a slow SMTP server cannot cause
|
||||||
|
// two runs to drain the same rows. flush_message() claims each row atomically
|
||||||
|
// as well, so an inline send racing the cron is also safe — the lock is about
|
||||||
|
// not piling up runs, not about correctness.
|
||||||
|
//
|
||||||
|
// Deliberately NOT a copy of fotografia's cron: that one also queues session
|
||||||
|
// reminders, emails a download digest and compresses session photos. fitme3070
|
||||||
|
// has none of those modules, so the steps would be dead code.
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
$cli = (PHP_SAPI === 'cli');
|
||||||
|
|
||||||
|
require __DIR__ . '/config/db.php';
|
||||||
|
require __DIR__ . '/config/functions.php';
|
||||||
|
|
||||||
|
// ─── Access control (HTTP only) ──────────────────────────────────────────────
|
||||||
|
// Over the web the token is the only thing standing between the internet and a
|
||||||
|
// job that sends mail. Missing or wrong token = 404, not 403: an attacker
|
||||||
|
// probing for cron endpoints learns nothing from a 404.
|
||||||
|
if (!$cli) {
|
||||||
|
$expected = (string) env('CRON_TOKEN', '');
|
||||||
|
$supplied = (string) ($_GET['token'] ?? '');
|
||||||
|
if ($expected === '' || $expected === 'replace_me'
|
||||||
|
|| !hash_equals($expected, $supplied)) {
|
||||||
|
http_response_code(404);
|
||||||
|
exit("Not Found\n");
|
||||||
|
}
|
||||||
|
header('Content-Type: text/plain; charset=utf-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Single-run lock ─────────────────────────────────────────────────────────
|
||||||
|
$lockPath = __DIR__ . '/logs/cron.lock';
|
||||||
|
@mkdir(dirname($lockPath), 0775, true);
|
||||||
|
$lock = @fopen($lockPath, 'c');
|
||||||
|
if ($lock === false) {
|
||||||
|
echo "cron: não foi possível abrir o ficheiro de lock\n";
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
if (!flock($lock, LOCK_EX | LOCK_NB)) {
|
||||||
|
echo "cron: já existe uma execução a decorrer — saltada.\n";
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
$started = microtime(true);
|
||||||
|
$log = [];
|
||||||
|
function cron_log(string $line): void {
|
||||||
|
global $log;
|
||||||
|
$log[] = $line;
|
||||||
|
echo $line . "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
cron_log('── cron ' . date('Y-m-d H:i:s') . ' ──');
|
||||||
|
|
||||||
|
// ─── 1. Release rows stuck in 'sending' ──────────────────────────────────────
|
||||||
|
try {
|
||||||
|
$released = requeue_stuck_messages($pdo, 15);
|
||||||
|
if ($released > 0) cron_log("mensagens libertadas de 'sending': {$released}");
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
cron_log('ERRO ao libertar mensagens presas: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 2. Drain the queue ──────────────────────────────────────────────────────
|
||||||
|
try {
|
||||||
|
$r = process_queue(50);
|
||||||
|
if ($r['total'] > 0) {
|
||||||
|
cron_log("fila: {$r['total']} processada(s), {$r['sent']} enviada(s), {$r['failed']} falhada(s)");
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
cron_log('ERRO ao drenar a fila: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 3. Retention ────────────────────────────────────────────────────────────
|
||||||
|
// Once a day is plenty. Gated on the first 5-minute slot of 04:00 — the hour
|
||||||
|
// alone would still fire this twelve times. Bodies are longtext, so this is
|
||||||
|
// what stops the table growing without bound.
|
||||||
|
if ((int) date('G') === 4 && (int) date('i') < 5) {
|
||||||
|
try {
|
||||||
|
$soft = db_soft_delete_sent_older_than($pdo, 90);
|
||||||
|
$hard = db_purge_deleted_messages($pdo, 90);
|
||||||
|
if ($soft || $hard) cron_log("retenção: {$soft} arquivada(s), {$hard} eliminada(s)");
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
cron_log('ERRO na retenção: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cron_log(sprintf('── fim (%.2fs) ──', microtime(true) - $started));
|
||||||
|
|
||||||
|
flock($lock, LOCK_UN);
|
||||||
|
fclose($lock);
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
-- Local outbound message queue.
|
||||||
|
--
|
||||||
|
-- Added when fitme3070 stopped relaying mail through the hub's /notify endpoint
|
||||||
|
-- and went back to sending its own, PHPMailer over SMTP. Mirrors the
|
||||||
|
-- fotografia.andmore.pt table so the shared queue code ports unchanged.
|
||||||
|
--
|
||||||
|
-- Safe to re-run.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `message_queue` (
|
||||||
|
`id` INT(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
`channel` ENUM('email','sms','whatsapp') NOT NULL DEFAULT 'email',
|
||||||
|
`status` ENUM('pending','sending','sent','failed','cancelled') NOT NULL DEFAULT 'pending',
|
||||||
|
`to_user_id` INT(11) DEFAULT NULL,
|
||||||
|
`to_address` VARCHAR(255) NOT NULL,
|
||||||
|
`to_name` VARCHAR(150) DEFAULT NULL,
|
||||||
|
`reply_to` VARCHAR(190) DEFAULT NULL,
|
||||||
|
`subject` VARCHAR(255) DEFAULT NULL,
|
||||||
|
`body` LONGTEXT NOT NULL,
|
||||||
|
`alt_body` TEXT DEFAULT NULL,
|
||||||
|
`context_type` VARCHAR(50) DEFAULT NULL,
|
||||||
|
`context_id` INT(11) DEFAULT NULL,
|
||||||
|
`scheduled_for` DATETIME DEFAULT NULL,
|
||||||
|
`attempts` INT(11) NOT NULL DEFAULT 0,
|
||||||
|
`max_attempts` INT(11) NOT NULL DEFAULT 3,
|
||||||
|
`next_attempt_at` DATETIME DEFAULT NULL,
|
||||||
|
`last_error` TEXT DEFAULT NULL,
|
||||||
|
`created_by` INT(11) DEFAULT NULL,
|
||||||
|
`sent_at` DATETIME DEFAULT NULL,
|
||||||
|
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
`deleted_at` DATETIME DEFAULT NULL,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
-- The drainer's hot query: pending/failed rows whose turn has come.
|
||||||
|
KEY `idx_mq_drain` (`status`, `next_attempt_at`, `scheduled_for`),
|
||||||
|
KEY `idx_mq_created` (`created_at`),
|
||||||
|
KEY `idx_mq_context` (`context_type`, `context_id`),
|
||||||
|
KEY `idx_mq_deleted` (`deleted_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- No foreign key on to_user_id / created_by: messages outlive the accounts they
|
||||||
|
-- were sent to, and the delivery history is worth more than the referential
|
||||||
|
-- tidiness. The Monitor page tolerates a missing user.
|
||||||
@@ -154,6 +154,14 @@ $app_name = defined('APP_NAME') ? APP_NAME : 'FitMe 3070';
|
|||||||
<a class="nav-link<?= ($_SERVER['SCRIPT_NAME'] ?? '') === '/views/sysadmin/backups.php' ? ' active' : '' ?>"
|
<a class="nav-link<?= ($_SERVER['SCRIPT_NAME'] ?? '') === '/views/sysadmin/backups.php' ? ' active' : '' ?>"
|
||||||
href="<?= base_url('views/sysadmin/backups.php') ?>"><i class="bi bi-database-fill-gear"></i>Backups</a>
|
href="<?= base_url('views/sysadmin/backups.php') ?>"><i class="bi bi-database-fill-gear"></i>Backups</a>
|
||||||
</li>
|
</li>
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link<?= ($_SERVER['SCRIPT_NAME'] ?? '') === '/views/sysadmin/messages.php' ? ' active' : '' ?>"
|
||||||
|
href="<?= base_url('views/sysadmin/messages.php') ?>"><i class="bi bi-envelope-paper"></i>Mensagens</a>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link<?= ($_SERVER['SCRIPT_NAME'] ?? '') === '/views/sysadmin/comms.php' ? ' active' : '' ?>"
|
||||||
|
href="<?= base_url('views/sysadmin/comms.php') ?>"><i class="bi bi-send"></i>Comunicações</a>
|
||||||
|
</li>
|
||||||
<li class="nav-item">
|
<li class="nav-item">
|
||||||
<a class="nav-link<?= ($_SERVER['SCRIPT_NAME'] ?? '') === '/views/sysadmin/platform_update.php' ? ' active' : '' ?>"
|
<a class="nav-link<?= ($_SERVER['SCRIPT_NAME'] ?? '') === '/views/sysadmin/platform_update.php' ? ' active' : '' ?>"
|
||||||
href="<?= base_url('views/sysadmin/platform_update.php') ?>"><i class="bi bi-arrow-repeat"></i>Actualizações</a>
|
href="<?= base_url('views/sysadmin/platform_update.php') ?>"><i class="bi bi-arrow-repeat"></i>Actualizações</a>
|
||||||
|
|||||||
+1
-1
Submodule shared/platform-tools updated: 603ff84759...ea3616abae.
Vendored
+502
@@ -0,0 +1,502 @@
|
|||||||
|
GNU LESSER GENERAL PUBLIC LICENSE
|
||||||
|
Version 2.1, February 1999
|
||||||
|
|
||||||
|
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||||
|
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
[This is the first released version of the Lesser GPL. It also counts
|
||||||
|
as the successor of the GNU Library Public License, version 2, hence
|
||||||
|
the version number 2.1.]
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The licenses for most software are designed to take away your
|
||||||
|
freedom to share and change it. By contrast, the GNU General Public
|
||||||
|
Licenses are intended to guarantee your freedom to share and change
|
||||||
|
free software--to make sure the software is free for all its users.
|
||||||
|
|
||||||
|
This license, the Lesser General Public License, applies to some
|
||||||
|
specially designated software packages--typically libraries--of the
|
||||||
|
Free Software Foundation and other authors who decide to use it. You
|
||||||
|
can use it too, but we suggest you first think carefully about whether
|
||||||
|
this license or the ordinary General Public License is the better
|
||||||
|
strategy to use in any particular case, based on the explanations below.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom of use,
|
||||||
|
not price. Our General Public Licenses are designed to make sure that
|
||||||
|
you have the freedom to distribute copies of free software (and charge
|
||||||
|
for this service if you wish); that you receive source code or can get
|
||||||
|
it if you want it; that you can change the software and use pieces of
|
||||||
|
it in new free programs; and that you are informed that you can do
|
||||||
|
these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to make restrictions that forbid
|
||||||
|
distributors to deny you these rights or to ask you to surrender these
|
||||||
|
rights. These restrictions translate to certain responsibilities for
|
||||||
|
you if you distribute copies of the library or if you modify it.
|
||||||
|
|
||||||
|
For example, if you distribute copies of the library, whether gratis
|
||||||
|
or for a fee, you must give the recipients all the rights that we gave
|
||||||
|
you. You must make sure that they, too, receive or can get the source
|
||||||
|
code. If you link other code with the library, you must provide
|
||||||
|
complete object files to the recipients, so that they can relink them
|
||||||
|
with the library after making changes to the library and recompiling
|
||||||
|
it. And you must show them these terms so they know their rights.
|
||||||
|
|
||||||
|
We protect your rights with a two-step method: (1) we copyright the
|
||||||
|
library, and (2) we offer you this license, which gives you legal
|
||||||
|
permission to copy, distribute and/or modify the library.
|
||||||
|
|
||||||
|
To protect each distributor, we want to make it very clear that
|
||||||
|
there is no warranty for the free library. Also, if the library is
|
||||||
|
modified by someone else and passed on, the recipients should know
|
||||||
|
that what they have is not the original version, so that the original
|
||||||
|
author's reputation will not be affected by problems that might be
|
||||||
|
introduced by others.
|
||||||
|
|
||||||
|
Finally, software patents pose a constant threat to the existence of
|
||||||
|
any free program. We wish to make sure that a company cannot
|
||||||
|
effectively restrict the users of a free program by obtaining a
|
||||||
|
restrictive license from a patent holder. Therefore, we insist that
|
||||||
|
any patent license obtained for a version of the library must be
|
||||||
|
consistent with the full freedom of use specified in this license.
|
||||||
|
|
||||||
|
Most GNU software, including some libraries, is covered by the
|
||||||
|
ordinary GNU General Public License. This license, the GNU Lesser
|
||||||
|
General Public License, applies to certain designated libraries, and
|
||||||
|
is quite different from the ordinary General Public License. We use
|
||||||
|
this license for certain libraries in order to permit linking those
|
||||||
|
libraries into non-free programs.
|
||||||
|
|
||||||
|
When a program is linked with a library, whether statically or using
|
||||||
|
a shared library, the combination of the two is legally speaking a
|
||||||
|
combined work, a derivative of the original library. The ordinary
|
||||||
|
General Public License therefore permits such linking only if the
|
||||||
|
entire combination fits its criteria of freedom. The Lesser General
|
||||||
|
Public License permits more lax criteria for linking other code with
|
||||||
|
the library.
|
||||||
|
|
||||||
|
We call this license the "Lesser" General Public License because it
|
||||||
|
does Less to protect the user's freedom than the ordinary General
|
||||||
|
Public License. It also provides other free software developers Less
|
||||||
|
of an advantage over competing non-free programs. These disadvantages
|
||||||
|
are the reason we use the ordinary General Public License for many
|
||||||
|
libraries. However, the Lesser license provides advantages in certain
|
||||||
|
special circumstances.
|
||||||
|
|
||||||
|
For example, on rare occasions, there may be a special need to
|
||||||
|
encourage the widest possible use of a certain library, so that it becomes
|
||||||
|
a de-facto standard. To achieve this, non-free programs must be
|
||||||
|
allowed to use the library. A more frequent case is that a free
|
||||||
|
library does the same job as widely used non-free libraries. In this
|
||||||
|
case, there is little to gain by limiting the free library to free
|
||||||
|
software only, so we use the Lesser General Public License.
|
||||||
|
|
||||||
|
In other cases, permission to use a particular library in non-free
|
||||||
|
programs enables a greater number of people to use a large body of
|
||||||
|
free software. For example, permission to use the GNU C Library in
|
||||||
|
non-free programs enables many more people to use the whole GNU
|
||||||
|
operating system, as well as its variant, the GNU/Linux operating
|
||||||
|
system.
|
||||||
|
|
||||||
|
Although the Lesser General Public License is Less protective of the
|
||||||
|
users' freedom, it does ensure that the user of a program that is
|
||||||
|
linked with the Library has the freedom and the wherewithal to run
|
||||||
|
that program using a modified version of the Library.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow. Pay close attention to the difference between a
|
||||||
|
"work based on the library" and a "work that uses the library". The
|
||||||
|
former contains code derived from the library, whereas the latter must
|
||||||
|
be combined with the library in order to run.
|
||||||
|
|
||||||
|
GNU LESSER GENERAL PUBLIC LICENSE
|
||||||
|
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||||
|
|
||||||
|
0. This License Agreement applies to any software library or other
|
||||||
|
program which contains a notice placed by the copyright holder or
|
||||||
|
other authorized party saying it may be distributed under the terms of
|
||||||
|
this Lesser General Public License (also called "this License").
|
||||||
|
Each licensee is addressed as "you".
|
||||||
|
|
||||||
|
A "library" means a collection of software functions and/or data
|
||||||
|
prepared so as to be conveniently linked with application programs
|
||||||
|
(which use some of those functions and data) to form executables.
|
||||||
|
|
||||||
|
The "Library", below, refers to any such software library or work
|
||||||
|
which has been distributed under these terms. A "work based on the
|
||||||
|
Library" means either the Library or any derivative work under
|
||||||
|
copyright law: that is to say, a work containing the Library or a
|
||||||
|
portion of it, either verbatim or with modifications and/or translated
|
||||||
|
straightforwardly into another language. (Hereinafter, translation is
|
||||||
|
included without limitation in the term "modification".)
|
||||||
|
|
||||||
|
"Source code" for a work means the preferred form of the work for
|
||||||
|
making modifications to it. For a library, complete source code means
|
||||||
|
all the source code for all modules it contains, plus any associated
|
||||||
|
interface definition files, plus the scripts used to control compilation
|
||||||
|
and installation of the library.
|
||||||
|
|
||||||
|
Activities other than copying, distribution and modification are not
|
||||||
|
covered by this License; they are outside its scope. The act of
|
||||||
|
running a program using the Library is not restricted, and output from
|
||||||
|
such a program is covered only if its contents constitute a work based
|
||||||
|
on the Library (independent of the use of the Library in a tool for
|
||||||
|
writing it). Whether that is true depends on what the Library does
|
||||||
|
and what the program that uses the Library does.
|
||||||
|
|
||||||
|
1. You may copy and distribute verbatim copies of the Library's
|
||||||
|
complete source code as you receive it, in any medium, provided that
|
||||||
|
you conspicuously and appropriately publish on each copy an
|
||||||
|
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||||
|
all the notices that refer to this License and to the absence of any
|
||||||
|
warranty; and distribute a copy of this License along with the
|
||||||
|
Library.
|
||||||
|
|
||||||
|
You may charge a fee for the physical act of transferring a copy,
|
||||||
|
and you may at your option offer warranty protection in exchange for a
|
||||||
|
fee.
|
||||||
|
|
||||||
|
2. You may modify your copy or copies of the Library or any portion
|
||||||
|
of it, thus forming a work based on the Library, and copy and
|
||||||
|
distribute such modifications or work under the terms of Section 1
|
||||||
|
above, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The modified work must itself be a software library.
|
||||||
|
|
||||||
|
b) You must cause the files modified to carry prominent notices
|
||||||
|
stating that you changed the files and the date of any change.
|
||||||
|
|
||||||
|
c) You must cause the whole of the work to be licensed at no
|
||||||
|
charge to all third parties under the terms of this License.
|
||||||
|
|
||||||
|
d) If a facility in the modified Library refers to a function or a
|
||||||
|
table of data to be supplied by an application program that uses
|
||||||
|
the facility, other than as an argument passed when the facility
|
||||||
|
is invoked, then you must make a good faith effort to ensure that,
|
||||||
|
in the event an application does not supply such function or
|
||||||
|
table, the facility still operates, and performs whatever part of
|
||||||
|
its purpose remains meaningful.
|
||||||
|
|
||||||
|
(For example, a function in a library to compute square roots has
|
||||||
|
a purpose that is entirely well-defined independent of the
|
||||||
|
application. Therefore, Subsection 2d requires that any
|
||||||
|
application-supplied function or table used by this function must
|
||||||
|
be optional: if the application does not supply it, the square
|
||||||
|
root function must still compute square roots.)
|
||||||
|
|
||||||
|
These requirements apply to the modified work as a whole. If
|
||||||
|
identifiable sections of that work are not derived from the Library,
|
||||||
|
and can be reasonably considered independent and separate works in
|
||||||
|
themselves, then this License, and its terms, do not apply to those
|
||||||
|
sections when you distribute them as separate works. But when you
|
||||||
|
distribute the same sections as part of a whole which is a work based
|
||||||
|
on the Library, the distribution of the whole must be on the terms of
|
||||||
|
this License, whose permissions for other licensees extend to the
|
||||||
|
entire whole, and thus to each and every part regardless of who wrote
|
||||||
|
it.
|
||||||
|
|
||||||
|
Thus, it is not the intent of this section to claim rights or contest
|
||||||
|
your rights to work written entirely by you; rather, the intent is to
|
||||||
|
exercise the right to control the distribution of derivative or
|
||||||
|
collective works based on the Library.
|
||||||
|
|
||||||
|
In addition, mere aggregation of another work not based on the Library
|
||||||
|
with the Library (or with a work based on the Library) on a volume of
|
||||||
|
a storage or distribution medium does not bring the other work under
|
||||||
|
the scope of this License.
|
||||||
|
|
||||||
|
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||||
|
License instead of this License to a given copy of the Library. To do
|
||||||
|
this, you must alter all the notices that refer to this License, so
|
||||||
|
that they refer to the ordinary GNU General Public License, version 2,
|
||||||
|
instead of to this License. (If a newer version than version 2 of the
|
||||||
|
ordinary GNU General Public License has appeared, then you can specify
|
||||||
|
that version instead if you wish.) Do not make any other change in
|
||||||
|
these notices.
|
||||||
|
|
||||||
|
Once this change is made in a given copy, it is irreversible for
|
||||||
|
that copy, so the ordinary GNU General Public License applies to all
|
||||||
|
subsequent copies and derivative works made from that copy.
|
||||||
|
|
||||||
|
This option is useful when you wish to copy part of the code of
|
||||||
|
the Library into a program that is not a library.
|
||||||
|
|
||||||
|
4. You may copy and distribute the Library (or a portion or
|
||||||
|
derivative of it, under Section 2) in object code or executable form
|
||||||
|
under the terms of Sections 1 and 2 above provided that you accompany
|
||||||
|
it with the complete corresponding machine-readable source code, which
|
||||||
|
must be distributed under the terms of Sections 1 and 2 above on a
|
||||||
|
medium customarily used for software interchange.
|
||||||
|
|
||||||
|
If distribution of object code is made by offering access to copy
|
||||||
|
from a designated place, then offering equivalent access to copy the
|
||||||
|
source code from the same place satisfies the requirement to
|
||||||
|
distribute the source code, even though third parties are not
|
||||||
|
compelled to copy the source along with the object code.
|
||||||
|
|
||||||
|
5. A program that contains no derivative of any portion of the
|
||||||
|
Library, but is designed to work with the Library by being compiled or
|
||||||
|
linked with it, is called a "work that uses the Library". Such a
|
||||||
|
work, in isolation, is not a derivative work of the Library, and
|
||||||
|
therefore falls outside the scope of this License.
|
||||||
|
|
||||||
|
However, linking a "work that uses the Library" with the Library
|
||||||
|
creates an executable that is a derivative of the Library (because it
|
||||||
|
contains portions of the Library), rather than a "work that uses the
|
||||||
|
library". The executable is therefore covered by this License.
|
||||||
|
Section 6 states terms for distribution of such executables.
|
||||||
|
|
||||||
|
When a "work that uses the Library" uses material from a header file
|
||||||
|
that is part of the Library, the object code for the work may be a
|
||||||
|
derivative work of the Library even though the source code is not.
|
||||||
|
Whether this is true is especially significant if the work can be
|
||||||
|
linked without the Library, or if the work is itself a library. The
|
||||||
|
threshold for this to be true is not precisely defined by law.
|
||||||
|
|
||||||
|
If such an object file uses only numerical parameters, data
|
||||||
|
structure layouts and accessors, and small macros and small inline
|
||||||
|
functions (ten lines or less in length), then the use of the object
|
||||||
|
file is unrestricted, regardless of whether it is legally a derivative
|
||||||
|
work. (Executables containing this object code plus portions of the
|
||||||
|
Library will still fall under Section 6.)
|
||||||
|
|
||||||
|
Otherwise, if the work is a derivative of the Library, you may
|
||||||
|
distribute the object code for the work under the terms of Section 6.
|
||||||
|
Any executables containing that work also fall under Section 6,
|
||||||
|
whether or not they are linked directly with the Library itself.
|
||||||
|
|
||||||
|
6. As an exception to the Sections above, you may also combine or
|
||||||
|
link a "work that uses the Library" with the Library to produce a
|
||||||
|
work containing portions of the Library, and distribute that work
|
||||||
|
under terms of your choice, provided that the terms permit
|
||||||
|
modification of the work for the customer's own use and reverse
|
||||||
|
engineering for debugging such modifications.
|
||||||
|
|
||||||
|
You must give prominent notice with each copy of the work that the
|
||||||
|
Library is used in it and that the Library and its use are covered by
|
||||||
|
this License. You must supply a copy of this License. If the work
|
||||||
|
during execution displays copyright notices, you must include the
|
||||||
|
copyright notice for the Library among them, as well as a reference
|
||||||
|
directing the user to the copy of this License. Also, you must do one
|
||||||
|
of these things:
|
||||||
|
|
||||||
|
a) Accompany the work with the complete corresponding
|
||||||
|
machine-readable source code for the Library including whatever
|
||||||
|
changes were used in the work (which must be distributed under
|
||||||
|
Sections 1 and 2 above); and, if the work is an executable linked
|
||||||
|
with the Library, with the complete machine-readable "work that
|
||||||
|
uses the Library", as object code and/or source code, so that the
|
||||||
|
user can modify the Library and then relink to produce a modified
|
||||||
|
executable containing the modified Library. (It is understood
|
||||||
|
that the user who changes the contents of definitions files in the
|
||||||
|
Library will not necessarily be able to recompile the application
|
||||||
|
to use the modified definitions.)
|
||||||
|
|
||||||
|
b) Use a suitable shared library mechanism for linking with the
|
||||||
|
Library. A suitable mechanism is one that (1) uses at run time a
|
||||||
|
copy of the library already present on the user's computer system,
|
||||||
|
rather than copying library functions into the executable, and (2)
|
||||||
|
will operate properly with a modified version of the library, if
|
||||||
|
the user installs one, as long as the modified version is
|
||||||
|
interface-compatible with the version that the work was made with.
|
||||||
|
|
||||||
|
c) Accompany the work with a written offer, valid for at
|
||||||
|
least three years, to give the same user the materials
|
||||||
|
specified in Subsection 6a, above, for a charge no more
|
||||||
|
than the cost of performing this distribution.
|
||||||
|
|
||||||
|
d) If distribution of the work is made by offering access to copy
|
||||||
|
from a designated place, offer equivalent access to copy the above
|
||||||
|
specified materials from the same place.
|
||||||
|
|
||||||
|
e) Verify that the user has already received a copy of these
|
||||||
|
materials or that you have already sent this user a copy.
|
||||||
|
|
||||||
|
For an executable, the required form of the "work that uses the
|
||||||
|
Library" must include any data and utility programs needed for
|
||||||
|
reproducing the executable from it. However, as a special exception,
|
||||||
|
the materials to be distributed need not include anything that is
|
||||||
|
normally distributed (in either source or binary form) with the major
|
||||||
|
components (compiler, kernel, and so on) of the operating system on
|
||||||
|
which the executable runs, unless that component itself accompanies
|
||||||
|
the executable.
|
||||||
|
|
||||||
|
It may happen that this requirement contradicts the license
|
||||||
|
restrictions of other proprietary libraries that do not normally
|
||||||
|
accompany the operating system. Such a contradiction means you cannot
|
||||||
|
use both them and the Library together in an executable that you
|
||||||
|
distribute.
|
||||||
|
|
||||||
|
7. You may place library facilities that are a work based on the
|
||||||
|
Library side-by-side in a single library together with other library
|
||||||
|
facilities not covered by this License, and distribute such a combined
|
||||||
|
library, provided that the separate distribution of the work based on
|
||||||
|
the Library and of the other library facilities is otherwise
|
||||||
|
permitted, and provided that you do these two things:
|
||||||
|
|
||||||
|
a) Accompany the combined library with a copy of the same work
|
||||||
|
based on the Library, uncombined with any other library
|
||||||
|
facilities. This must be distributed under the terms of the
|
||||||
|
Sections above.
|
||||||
|
|
||||||
|
b) Give prominent notice with the combined library of the fact
|
||||||
|
that part of it is a work based on the Library, and explaining
|
||||||
|
where to find the accompanying uncombined form of the same work.
|
||||||
|
|
||||||
|
8. You may not copy, modify, sublicense, link with, or distribute
|
||||||
|
the Library except as expressly provided under this License. Any
|
||||||
|
attempt otherwise to copy, modify, sublicense, link with, or
|
||||||
|
distribute the Library is void, and will automatically terminate your
|
||||||
|
rights under this License. However, parties who have received copies,
|
||||||
|
or rights, from you under this License will not have their licenses
|
||||||
|
terminated so long as such parties remain in full compliance.
|
||||||
|
|
||||||
|
9. You are not required to accept this License, since you have not
|
||||||
|
signed it. However, nothing else grants you permission to modify or
|
||||||
|
distribute the Library or its derivative works. These actions are
|
||||||
|
prohibited by law if you do not accept this License. Therefore, by
|
||||||
|
modifying or distributing the Library (or any work based on the
|
||||||
|
Library), you indicate your acceptance of this License to do so, and
|
||||||
|
all its terms and conditions for copying, distributing or modifying
|
||||||
|
the Library or works based on it.
|
||||||
|
|
||||||
|
10. Each time you redistribute the Library (or any work based on the
|
||||||
|
Library), the recipient automatically receives a license from the
|
||||||
|
original licensor to copy, distribute, link with or modify the Library
|
||||||
|
subject to these terms and conditions. You may not impose any further
|
||||||
|
restrictions on the recipients' exercise of the rights granted herein.
|
||||||
|
You are not responsible for enforcing compliance by third parties with
|
||||||
|
this License.
|
||||||
|
|
||||||
|
11. If, as a consequence of a court judgment or allegation of patent
|
||||||
|
infringement or for any other reason (not limited to patent issues),
|
||||||
|
conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot
|
||||||
|
distribute so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you
|
||||||
|
may not distribute the Library at all. For example, if a patent
|
||||||
|
license would not permit royalty-free redistribution of the Library by
|
||||||
|
all those who receive copies directly or indirectly through you, then
|
||||||
|
the only way you could satisfy both it and this License would be to
|
||||||
|
refrain entirely from distribution of the Library.
|
||||||
|
|
||||||
|
If any portion of this section is held invalid or unenforceable under any
|
||||||
|
particular circumstance, the balance of the section is intended to apply,
|
||||||
|
and the section as a whole is intended to apply in other circumstances.
|
||||||
|
|
||||||
|
It is not the purpose of this section to induce you to infringe any
|
||||||
|
patents or other property right claims or to contest validity of any
|
||||||
|
such claims; this section has the sole purpose of protecting the
|
||||||
|
integrity of the free software distribution system which is
|
||||||
|
implemented by public license practices. Many people have made
|
||||||
|
generous contributions to the wide range of software distributed
|
||||||
|
through that system in reliance on consistent application of that
|
||||||
|
system; it is up to the author/donor to decide if he or she is willing
|
||||||
|
to distribute software through any other system and a licensee cannot
|
||||||
|
impose that choice.
|
||||||
|
|
||||||
|
This section is intended to make thoroughly clear what is believed to
|
||||||
|
be a consequence of the rest of this License.
|
||||||
|
|
||||||
|
12. If the distribution and/or use of the Library is restricted in
|
||||||
|
certain countries either by patents or by copyrighted interfaces, the
|
||||||
|
original copyright holder who places the Library under this License may add
|
||||||
|
an explicit geographical distribution limitation excluding those countries,
|
||||||
|
so that distribution is permitted only in or among countries not thus
|
||||||
|
excluded. In such case, this License incorporates the limitation as if
|
||||||
|
written in the body of this License.
|
||||||
|
|
||||||
|
13. The Free Software Foundation may publish revised and/or new
|
||||||
|
versions of the Lesser General Public License from time to time.
|
||||||
|
Such new versions will be similar in spirit to the present version,
|
||||||
|
but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Library
|
||||||
|
specifies a version number of this License which applies to it and
|
||||||
|
"any later version", you have the option of following the terms and
|
||||||
|
conditions either of that version or of any later version published by
|
||||||
|
the Free Software Foundation. If the Library does not specify a
|
||||||
|
license version number, you may choose any version ever published by
|
||||||
|
the Free Software Foundation.
|
||||||
|
|
||||||
|
14. If you wish to incorporate parts of the Library into other free
|
||||||
|
programs whose distribution conditions are incompatible with these,
|
||||||
|
write to the author to ask for permission. For software which is
|
||||||
|
copyrighted by the Free Software Foundation, write to the Free
|
||||||
|
Software Foundation; we sometimes make exceptions for this. Our
|
||||||
|
decision will be guided by the two goals of preserving the free status
|
||||||
|
of all derivatives of our free software and of promoting the sharing
|
||||||
|
and reuse of software generally.
|
||||||
|
|
||||||
|
NO WARRANTY
|
||||||
|
|
||||||
|
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||||
|
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||||
|
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||||
|
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||||
|
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||||
|
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||||
|
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||||
|
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||||
|
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||||
|
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||||
|
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||||
|
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||||
|
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||||
|
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||||
|
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||||
|
DAMAGES.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Libraries
|
||||||
|
|
||||||
|
If you develop a new library, and you want it to be of the greatest
|
||||||
|
possible use to the public, we recommend making it free software that
|
||||||
|
everyone can redistribute and change. You can do so by permitting
|
||||||
|
redistribution under these terms (or, alternatively, under the terms of the
|
||||||
|
ordinary General Public License).
|
||||||
|
|
||||||
|
To apply these terms, attach the following notices to the library. It is
|
||||||
|
safest to attach them to the start of each source file to most effectively
|
||||||
|
convey the exclusion of warranty; and each file should have at least the
|
||||||
|
"copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the library's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This library is free software; you can redistribute it and/or
|
||||||
|
modify it under the terms of the GNU Lesser General Public
|
||||||
|
License as published by the Free Software Foundation; either
|
||||||
|
version 2.1 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This library is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||||
|
Lesser General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Lesser General Public
|
||||||
|
License along with this library; if not, write to the Free Software
|
||||||
|
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or your
|
||||||
|
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||||
|
necessary. Here is a sample; alter the names:
|
||||||
|
|
||||||
|
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||||
|
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||||
|
|
||||||
|
<signature of Ty Coon>, 1 April 1990
|
||||||
|
Ty Coon, President of Vice
|
||||||
|
|
||||||
|
That's all there is to it!
|
||||||
Vendored
+40
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PHPMailer Exception class.
|
||||||
|
* PHP Version 5.5.
|
||||||
|
*
|
||||||
|
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
|
||||||
|
*
|
||||||
|
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
|
||||||
|
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
|
||||||
|
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
|
||||||
|
* @author Brent R. Matzelle (original founder)
|
||||||
|
* @copyright 2012 - 2020 Marcus Bointon
|
||||||
|
* @copyright 2010 - 2012 Jim Jagielski
|
||||||
|
* @copyright 2004 - 2009 Andy Prevost
|
||||||
|
* @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License
|
||||||
|
* @note This program is distributed in the hope that it will be useful - WITHOUT
|
||||||
|
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace PHPMailer\PHPMailer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PHPMailer exception handler.
|
||||||
|
*
|
||||||
|
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
|
||||||
|
*/
|
||||||
|
class Exception extends \Exception
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Prettify error message output.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function errorMessage()
|
||||||
|
{
|
||||||
|
return '<strong>' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "</strong><br />\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+5586
File diff suppressed because it is too large.
Load diff
Vendored
+1617
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,198 @@
|
|||||||
|
<?php
|
||||||
|
// Comunicações — delivery credentials plus the diagnostics a sysadmin needs
|
||||||
|
// when mail stops working.
|
||||||
|
//
|
||||||
|
// Config and tests live on one page deliberately: the loop is "change a
|
||||||
|
// setting, test it, read the real error", and splitting that across two screens
|
||||||
|
// makes it slower to diagnose.
|
||||||
|
//
|
||||||
|
// Sysadmin-only: it handles SMTP and Twilio credentials.
|
||||||
|
|
||||||
|
require __DIR__ . '/../../config/db.php';
|
||||||
|
require __DIR__ . '/../../config/functions.php';
|
||||||
|
$user = require_sysadmin();
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../../shared/platform-tools/functions_mail.php';
|
||||||
|
require_once __DIR__ . '/../../shared/platform-tools/functions_settings.php';
|
||||||
|
|
||||||
|
$repo_root = dirname(__DIR__, 2);
|
||||||
|
$saved = false;
|
||||||
|
$errors = [];
|
||||||
|
$test = null;
|
||||||
|
|
||||||
|
// Secret fields are write-only in the UI and encrypted at rest. Which keys count
|
||||||
|
// as secret is decided by platform_settings_is_secret() — anything ending in
|
||||||
|
// _password/_secret/_token/_api_key — rather than a list maintained here, so a
|
||||||
|
// field added later can't accidentally be stored in the clear.
|
||||||
|
$fields = [
|
||||||
|
'smtp_host' => ['label' => 'Servidor SMTP', 'type' => 'text', 'hint' => 'Vazio = usa a função mail() do PHP.'],
|
||||||
|
'smtp_port' => ['label' => 'Porta', 'type' => 'number', 'hint' => '587 para TLS, 465 para SSL.'],
|
||||||
|
'smtp_secure' => ['label' => 'Encriptação', 'type' => 'select', 'options' => ['tls' => 'TLS (StartTLS)', 'ssl' => 'SSL', '' => 'Nenhuma']],
|
||||||
|
'smtp_username' => ['label' => 'Utilizador', 'type' => 'text', 'hint' => 'Normalmente o endereço de email completo.'],
|
||||||
|
'smtp_password' => ['label' => 'Palavra-passe', 'type' => 'password'],
|
||||||
|
'email_from' => ['label' => 'Remetente', 'type' => 'text', 'hint' => 'Endereço que aparece no From.'],
|
||||||
|
'email_from_name' => ['label' => 'Nome do remetente', 'type' => 'text'],
|
||||||
|
'twilio_sid' => ['label' => 'Account SID', 'type' => 'text', 'hint' => 'Começa por AC…'],
|
||||||
|
'twilio_token' => ['label' => 'Auth Token', 'type' => 'password'],
|
||||||
|
'twilio_sms_from' => ['label' => 'Remetente SMS', 'type' => 'text', 'hint' => 'E.164 (+351…) ou alfanumérico.'],
|
||||||
|
'twilio_whatsapp_from' => ['label' => 'Remetente WhatsApp', 'type' => 'text', 'hint' => 'Número E.164, sem o prefixo whatsapp:.'],
|
||||||
|
'sms_default_country_code' => ['label' => 'Indicativo por defeito', 'type' => 'text', 'hint' => 'Aplicado a números guardados sem +.'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$groups = [
|
||||||
|
'SMTP' => ['smtp_host', 'smtp_port', 'smtp_secure', 'smtp_username', 'smtp_password', 'email_from', 'email_from_name'],
|
||||||
|
'Twilio (SMS / WhatsApp)' => ['twilio_sid', 'twilio_token', 'twilio_sms_from', 'twilio_whatsapp_from', 'sms_default_country_code'],
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||||
|
csrf_check();
|
||||||
|
$action = $_POST['_action'] ?? 'save';
|
||||||
|
$uid = (int) $user['id'];
|
||||||
|
|
||||||
|
if ($action === 'save') {
|
||||||
|
foreach ($fields as $key => $meta) {
|
||||||
|
$raw = trim((string) ($_POST[$key] ?? ''));
|
||||||
|
|
||||||
|
if (platform_settings_is_secret($key)) {
|
||||||
|
// Blank means "leave the stored one alone" — the field is never
|
||||||
|
// pre-filled with the real value, so blank cannot mean "clear".
|
||||||
|
// Clearing is an explicit checkbox.
|
||||||
|
if (!empty($_POST[$key . '_clear'])) {
|
||||||
|
db_update_setting($pdo, $key, '', $uid);
|
||||||
|
} elseif ($raw !== '') {
|
||||||
|
db_update_setting($pdo, $key, secret_encrypt($raw), $uid);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
db_update_setting($pdo, $key, $raw, $uid);
|
||||||
|
}
|
||||||
|
// db_update_setting() drops fitme3070's file cache; platform_settings_get()
|
||||||
|
// keeps its own per-request cache, which must go too or the diagnostics
|
||||||
|
// below would render the values from before this save.
|
||||||
|
platform_settings_cache_clear();
|
||||||
|
$saved = true;
|
||||||
|
} elseif ($action === 'test') {
|
||||||
|
$test = platform_mail_test($repo_root, platform_smtp_config($pdo));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$current = settings_all();
|
||||||
|
[$diagClass, $diagTitle, $diagText] = platform_mail_diagnosis($repo_root, null, $pdo);
|
||||||
|
$rows = platform_mail_config_rows(null, $pdo);
|
||||||
|
|
||||||
|
$page_title = 'Comunicações';
|
||||||
|
include __DIR__ . '/../../includes/header.php';
|
||||||
|
?>
|
||||||
|
<div class="container" style="max-width:860px;">
|
||||||
|
<h1 class="h3 mb-1">Comunicações</h1>
|
||||||
|
<p class="text-muted mb-4">Credenciais de envio e diagnóstico. As palavras-passe são guardadas cifradas.</p>
|
||||||
|
|
||||||
|
<?php if ($saved): ?><div class="alert alert-success">Definições guardadas.</div><?php endif; ?>
|
||||||
|
<?php foreach ($errors as $e): ?><div class="alert alert-danger"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
|
||||||
|
|
||||||
|
<?php if (!platform_settings_secret_available()): ?>
|
||||||
|
<div class="alert alert-warning">
|
||||||
|
<strong>Cifra indisponível.</strong> Defina <code>APP_SECRET_KEY</code> no <code>.env</code>
|
||||||
|
(ou um <code>BACKUP_TOKEN</code> que não seja <code>replace_me</code>) — sem chave, as palavras-passe
|
||||||
|
ficam guardadas em texto simples e acabam nos backups da base de dados.
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<!-- ─── Estado ─────────────────────────────────────────────────────── -->
|
||||||
|
<div class="card shadow-sm mb-3"><div class="card-body">
|
||||||
|
<div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
|
||||||
|
<div>
|
||||||
|
<h2 class="h6 mb-1">Estado</h2>
|
||||||
|
<span class="badge text-bg-<?= htmlspecialchars($diagClass) ?>"><?= htmlspecialchars($diagTitle) ?></span>
|
||||||
|
<p class="text-muted small mb-0 mt-2"><?= htmlspecialchars($diagText) ?></p>
|
||||||
|
</div>
|
||||||
|
<form method="POST" class="ms-auto">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="_action" value="test">
|
||||||
|
<button class="btn btn-outline-primary"><i class="bi bi-plug me-1"></i>Testar ligação SMTP</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<?php if ($test !== null): ?>
|
||||||
|
<hr>
|
||||||
|
<div class="alert alert-<?= !empty($test['ok']) ? 'success' : 'danger' ?> py-2 small mb-2">
|
||||||
|
<?= !empty($test['ok']) ? 'Ligação estabelecida.' : htmlspecialchars((string) ($test['error'] ?? 'Falhou.')) ?>
|
||||||
|
</div>
|
||||||
|
<?php if (!empty($test['log'])): ?>
|
||||||
|
<details>
|
||||||
|
<summary class="small text-muted">Registo da ligação</summary>
|
||||||
|
<pre class="small bg-light p-2 mt-2 mb-0" style="max-height:260px;overflow:auto;white-space:pre-wrap;"><?= htmlspecialchars((string) $test['log']) ?></pre>
|
||||||
|
</details>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<hr>
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-sm mb-0">
|
||||||
|
<tbody>
|
||||||
|
<?php foreach ($rows as [$label, $value, $ok]): ?>
|
||||||
|
<tr>
|
||||||
|
<th class="text-muted fw-normal" style="width:40%;"><?= htmlspecialchars($label) ?></th>
|
||||||
|
<td>
|
||||||
|
<?= htmlspecialchars((string) $value) ?>
|
||||||
|
<?php if (!$ok): ?><i class="bi bi-exclamation-triangle-fill text-warning ms-1"></i><?php endif; ?>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="text-muted small mb-0 mt-2">
|
||||||
|
Valores pinados no <code>.env</code> têm precedência sobre estes campos — se editar aqui e nada mudar,
|
||||||
|
é porque a chave está definida no <code>.env</code>.
|
||||||
|
</p>
|
||||||
|
</div></div>
|
||||||
|
|
||||||
|
<!-- ─── Definições ─────────────────────────────────────────────────── -->
|
||||||
|
<form method="POST">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="_action" value="save">
|
||||||
|
<?php foreach ($groups as $groupLabel => $keys): ?>
|
||||||
|
<div class="card shadow-sm mb-3"><div class="card-body">
|
||||||
|
<h2 class="h6 mb-3"><?= htmlspecialchars($groupLabel) ?></h2>
|
||||||
|
<?php foreach ($keys as $key):
|
||||||
|
$meta = $fields[$key];
|
||||||
|
$isSecret = platform_settings_is_secret($key);
|
||||||
|
$stored = (string) ($current[$key] ?? '');
|
||||||
|
?>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="f-<?= htmlspecialchars($key) ?>"><?= htmlspecialchars($meta['label']) ?></label>
|
||||||
|
<?php if ($meta['type'] === 'select'): ?>
|
||||||
|
<select class="form-select" id="f-<?= htmlspecialchars($key) ?>" name="<?= htmlspecialchars($key) ?>">
|
||||||
|
<?php foreach ($meta['options'] as $val => $lbl): ?>
|
||||||
|
<option value="<?= htmlspecialchars((string) $val) ?>" <?= $stored === (string) $val ? 'selected' : '' ?>><?= htmlspecialchars($lbl) ?></option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
<?php elseif ($isSecret): ?>
|
||||||
|
<input type="password" class="form-control" id="f-<?= htmlspecialchars($key) ?>"
|
||||||
|
name="<?= htmlspecialchars($key) ?>" autocomplete="new-password"
|
||||||
|
placeholder="<?= $stored !== '' ? '•••••••• (guardada — deixe vazio para manter)' : 'não definida' ?>">
|
||||||
|
<?php if ($stored !== ''): ?>
|
||||||
|
<div class="form-check small mt-1">
|
||||||
|
<input class="form-check-input" type="checkbox" value="1"
|
||||||
|
id="c-<?= htmlspecialchars($key) ?>" name="<?= htmlspecialchars($key) ?>_clear">
|
||||||
|
<label class="form-check-label text-muted" for="c-<?= htmlspecialchars($key) ?>">Apagar a guardada</label>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php else: ?>
|
||||||
|
<input type="<?= htmlspecialchars($meta['type']) ?>" class="form-control"
|
||||||
|
id="f-<?= htmlspecialchars($key) ?>" name="<?= htmlspecialchars($key) ?>"
|
||||||
|
value="<?= htmlspecialchars($stored) ?>">
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php if (!empty($meta['hint'])): ?>
|
||||||
|
<div class="form-text"><?= htmlspecialchars($meta['hint']) ?></div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</div></div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<button class="btn btn-primary">Guardar</button>
|
||||||
|
<a class="btn btn-link" href="<?= base_url('views/sysadmin/messages.php') ?>">Ver fila de mensagens →</a>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<?php include __DIR__ . '/../../includes/footer.php'; ?>
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
<?php
|
||||||
|
// Monitor da fila de mensagens — o que saiu, o que falhou e porquê.
|
||||||
|
//
|
||||||
|
// The queue is only useful if someone can see into it: a message that failed
|
||||||
|
// three times and parked in 'failed' is invisible everywhere else in the app,
|
||||||
|
// and last_error is the only place the real SMTP rejection is written down.
|
||||||
|
//
|
||||||
|
// Sysadmin-only: message bodies contain personal data.
|
||||||
|
|
||||||
|
require __DIR__ . '/../../config/db.php';
|
||||||
|
require __DIR__ . '/../../config/functions.php';
|
||||||
|
$user = require_sysadmin();
|
||||||
|
|
||||||
|
$notice = '';
|
||||||
|
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||||
|
csrf_check();
|
||||||
|
$id = (int) ($_POST['id'] ?? 0);
|
||||||
|
$action = $_POST['_action'] ?? '';
|
||||||
|
|
||||||
|
if ($id > 0) {
|
||||||
|
switch ($action) {
|
||||||
|
case 'retry':
|
||||||
|
// Back to 'pending' with the attempt counter cleared, then sent
|
||||||
|
// inline so the operator sees the outcome now rather than
|
||||||
|
// waiting for the next cron tick.
|
||||||
|
db_retry_message($pdo, $id);
|
||||||
|
$notice = flush_message($id)
|
||||||
|
? "Mensagem #{$id} enviada."
|
||||||
|
: "Mensagem #{$id} voltou a falhar — veja o erro na linha.";
|
||||||
|
break;
|
||||||
|
case 'cancel':
|
||||||
|
db_cancel_message($pdo, $id);
|
||||||
|
$notice = "Mensagem #{$id} cancelada.";
|
||||||
|
break;
|
||||||
|
case 'delete':
|
||||||
|
db_soft_delete_message($pdo, $id);
|
||||||
|
$notice = "Mensagem #{$id} arquivada.";
|
||||||
|
break;
|
||||||
|
case 'restore':
|
||||||
|
db_restore_message($pdo, $id);
|
||||||
|
$notice = "Mensagem #{$id} restaurada.";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$status = (string) ($_GET['status'] ?? '');
|
||||||
|
$channel = (string) ($_GET['channel'] ?? '');
|
||||||
|
$search = trim((string) ($_GET['q'] ?? ''));
|
||||||
|
$trash = !empty($_GET['trash']);
|
||||||
|
$detail = (int) ($_GET['id'] ?? 0);
|
||||||
|
|
||||||
|
$counts = db_count_messages_by_status($pdo, 30);
|
||||||
|
// db_get_messages() takes a `statuses` ARRAY and `only_deleted`, not the
|
||||||
|
// singular/`trash` names the query string uses.
|
||||||
|
$messages = db_get_messages($pdo, [
|
||||||
|
'statuses' => $status !== '' ? [$status] : [],
|
||||||
|
'channel' => $channel ?: null,
|
||||||
|
'search' => $search ?: null,
|
||||||
|
'only_deleted' => $trash,
|
||||||
|
'limit' => 200,
|
||||||
|
]);
|
||||||
|
$row = $detail > 0 ? db_get_message($pdo, $detail) : false;
|
||||||
|
|
||||||
|
$page_title = 'Mensagens';
|
||||||
|
include __DIR__ . '/../../includes/header.php';
|
||||||
|
?>
|
||||||
|
<div class="container">
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
||||||
|
<h1 class="h3 mb-0">Mensagens</h1>
|
||||||
|
<a class="btn btn-sm btn-outline-secondary" href="<?= base_url('views/sysadmin/comms.php') ?>">
|
||||||
|
<i class="bi bi-sliders me-1"></i>Configuração SMTP
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<?php if ($notice): ?><div class="alert alert-info"><?= htmlspecialchars($notice) ?></div><?php endif; ?>
|
||||||
|
|
||||||
|
<!-- ─── Contadores (últimos 30 dias) ───────────────────────────────── -->
|
||||||
|
<div class="row g-2 mb-3">
|
||||||
|
<?php foreach (['pending' => 'Em espera', 'sending' => 'A enviar', 'sent' => 'Enviadas', 'failed' => 'Falhadas', 'cancelled' => 'Canceladas'] as $k => $lbl): ?>
|
||||||
|
<div class="col-6 col-md">
|
||||||
|
<a class="text-decoration-none" href="<?= base_url('views/sysadmin/messages.php?status=' . $k) ?>">
|
||||||
|
<div class="card shadow-sm h-100"><div class="card-body py-2 px-3">
|
||||||
|
<div class="text-muted small"><?= htmlspecialchars($lbl) ?></div>
|
||||||
|
<div class="fs-4"><?= (int) ($counts[$k] ?? 0) ?></div>
|
||||||
|
</div></div>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ─── Filtros ────────────────────────────────────────────────────── -->
|
||||||
|
<form class="card shadow-sm mb-3" method="GET"><div class="card-body py-2">
|
||||||
|
<div class="row g-2 align-items-end">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label small mb-1" for="f-status">Estado</label>
|
||||||
|
<select class="form-select form-select-sm" id="f-status" name="status">
|
||||||
|
<option value="">Todos</option>
|
||||||
|
<?php foreach (MESSAGE_QUEUE_VALID_STATUSES as $s): ?>
|
||||||
|
<option value="<?= $s ?>" <?= $status === $s ? 'selected' : '' ?>><?= htmlspecialchars(message_status_label($s)) ?></option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label small mb-1" for="f-channel">Canal</label>
|
||||||
|
<select class="form-select form-select-sm" id="f-channel" name="channel">
|
||||||
|
<option value="">Todos</option>
|
||||||
|
<?php foreach (MESSAGE_QUEUE_VALID_CHANNELS as $c): ?>
|
||||||
|
<option value="<?= $c ?>" <?= $channel === $c ? 'selected' : '' ?>><?= htmlspecialchars(message_channel_label($c)) ?></option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-4">
|
||||||
|
<label class="form-label small mb-1" for="f-q">Pesquisar</label>
|
||||||
|
<input class="form-control form-control-sm" id="f-q" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="destinatário ou assunto">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2 d-grid">
|
||||||
|
<button class="btn btn-sm btn-primary">Filtrar</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-check small mt-2">
|
||||||
|
<input class="form-check-input" type="checkbox" value="1" id="f-trash" name="trash" <?= $trash ? 'checked' : '' ?>>
|
||||||
|
<label class="form-check-label text-muted" for="f-trash">Mostrar arquivadas</label>
|
||||||
|
</div>
|
||||||
|
</div></form>
|
||||||
|
|
||||||
|
<!-- ─── Detalhe ────────────────────────────────────────────────────── -->
|
||||||
|
<?php if ($row): ?>
|
||||||
|
<div class="card shadow-sm mb-3"><div class="card-body">
|
||||||
|
<div class="d-flex justify-content-between align-items-start">
|
||||||
|
<h2 class="h6 mb-2">#<?= (int) $row['id'] ?> · <?= htmlspecialchars($row['subject'] ?? '(sem assunto)') ?></h2>
|
||||||
|
<a class="btn-close" href="<?= base_url('views/sysadmin/messages.php') ?>" aria-label="Fechar"></a>
|
||||||
|
</div>
|
||||||
|
<dl class="row small mb-2">
|
||||||
|
<dt class="col-sm-3 fw-normal text-muted">Para</dt>
|
||||||
|
<dd class="col-sm-9"><?= htmlspecialchars($row['to_address']) ?><?= $row['to_name'] ? ' (' . htmlspecialchars($row['to_name']) . ')' : '' ?></dd>
|
||||||
|
<dt class="col-sm-3 fw-normal text-muted">Estado</dt>
|
||||||
|
<dd class="col-sm-9"><?= message_status_badge($row['status']) ?> · <?= (int) $row['attempts'] ?>/<?= (int) $row['max_attempts'] ?> tentativas</dd>
|
||||||
|
<dt class="col-sm-3 fw-normal text-muted">Contexto</dt>
|
||||||
|
<dd class="col-sm-9"><?= htmlspecialchars(message_context_label($row['context_type'])) ?></dd>
|
||||||
|
<?php if (!empty($row['last_error'])): ?>
|
||||||
|
<dt class="col-sm-3 fw-normal text-muted">Último erro</dt>
|
||||||
|
<dd class="col-sm-9"><code class="text-danger"><?= htmlspecialchars($row['last_error']) ?></code></dd>
|
||||||
|
<?php endif; ?>
|
||||||
|
</dl>
|
||||||
|
<details>
|
||||||
|
<summary class="small text-muted">Corpo da mensagem</summary>
|
||||||
|
<pre class="small bg-light p-2 mt-2 mb-0" style="max-height:340px;overflow:auto;white-space:pre-wrap;"><?= htmlspecialchars($row['body']) ?></pre>
|
||||||
|
</details>
|
||||||
|
</div></div>
|
||||||
|
<?php endif; ?>
|
||||||
|
|
||||||
|
<!-- ─── Lista ──────────────────────────────────────────────────────── -->
|
||||||
|
<div class="card shadow-sm"><div class="card-body">
|
||||||
|
<?php if (!$messages): ?>
|
||||||
|
<p class="text-muted text-center py-4 mb-0">Sem mensagens.</p>
|
||||||
|
<?php else: ?>
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-hover align-middle small">
|
||||||
|
<thead><tr>
|
||||||
|
<th>#</th><th>Canal</th><th>Para</th><th>Assunto</th>
|
||||||
|
<th>Estado</th><th>Criada</th><th class="text-end">Ações</th>
|
||||||
|
</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<?php foreach ($messages as $m): ?>
|
||||||
|
<tr>
|
||||||
|
<td><a href="<?= base_url('views/sysadmin/messages.php?id=' . (int) $m['id']) ?>">#<?= (int) $m['id'] ?></a></td>
|
||||||
|
<td><i class="bi <?= htmlspecialchars(message_channel_icon($m['channel'])) ?>" title="<?= htmlspecialchars(message_channel_label($m['channel'])) ?>"></i></td>
|
||||||
|
<td><?= htmlspecialchars($m['to_address']) ?></td>
|
||||||
|
<td class="text-truncate" style="max-width:260px;"><?= htmlspecialchars($m['subject'] ?? '—') ?></td>
|
||||||
|
<td>
|
||||||
|
<?= message_status_badge($m['status']) ?>
|
||||||
|
<?php if (!empty($m['last_error'])): ?>
|
||||||
|
<i class="bi bi-exclamation-circle text-danger ms-1" title="<?= htmlspecialchars(mb_substr($m['last_error'], 0, 200)) ?>"></i>
|
||||||
|
<?php endif; ?>
|
||||||
|
</td>
|
||||||
|
<td class="text-muted"><?= htmlspecialchars(format_date_pt($m['created_at'])) ?></td>
|
||||||
|
<td class="text-end text-nowrap">
|
||||||
|
<?php if (!$trash): ?>
|
||||||
|
<?php if (in_array($m['status'], ['failed', 'cancelled', 'pending'], true)): ?>
|
||||||
|
<form method="POST" class="d-inline">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="id" value="<?= (int) $m['id'] ?>">
|
||||||
|
<input type="hidden" name="_action" value="retry">
|
||||||
|
<button class="btn btn-sm btn-outline-primary" title="Reenviar agora"><i class="bi bi-arrow-repeat"></i></button>
|
||||||
|
</form>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php if (in_array($m['status'], ['pending', 'failed'], true)): ?>
|
||||||
|
<form method="POST" class="d-inline">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="id" value="<?= (int) $m['id'] ?>">
|
||||||
|
<input type="hidden" name="_action" value="cancel">
|
||||||
|
<button class="btn btn-sm btn-outline-secondary" title="Cancelar"><i class="bi bi-slash-circle"></i></button>
|
||||||
|
</form>
|
||||||
|
<?php endif; ?>
|
||||||
|
<form method="POST" class="d-inline">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="id" value="<?= (int) $m['id'] ?>">
|
||||||
|
<input type="hidden" name="_action" value="delete">
|
||||||
|
<button class="btn btn-sm btn-outline-danger" title="Arquivar"><i class="bi bi-archive"></i></button>
|
||||||
|
</form>
|
||||||
|
<?php else: ?>
|
||||||
|
<form method="POST" class="d-inline">
|
||||||
|
<?= csrf_field() ?>
|
||||||
|
<input type="hidden" name="id" value="<?= (int) $m['id'] ?>">
|
||||||
|
<input type="hidden" name="_action" value="restore">
|
||||||
|
<button class="btn btn-sm btn-outline-secondary" title="Restaurar"><i class="bi bi-arrow-counterclockwise"></i></button>
|
||||||
|
</form>
|
||||||
|
<?php endif; ?>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="text-muted small mb-0">
|
||||||
|
Mostradas até 200. A fila é drenada pelo <code>cron.php</code>; as falhas voltam a ser tentadas
|
||||||
|
com espera exponencial até <code>max_attempts</code>.
|
||||||
|
</p>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div></div>
|
||||||
|
</div>
|
||||||
|
<?php include __DIR__ . '/../../includes/footer.php'; ?>
|
||||||
Reference in new issue
Block a user