feat: contactos editáveis, equipa com título/aptidões, mensalidades e reviews Google
- Contactos: nova página no backoffice (fitme3070_info) e 964 201 137 como telefone principal; o telefone secundário só aparece quando existe. - Equipa: título, aptidões/funções e formações; o cartão mostra foto, nome e título e abre um cartão horizontal de detalhe (hover no desktop, toque no telemóvel) sem mexer na grelha. - Mensalidades: cartões editáveis com um destaque, modal de inscrição que guarda o pedido (RGPD + estado + campos reservados para o CRM) e avisa o ginásio por e-mail; lista de pedidos com estados, notas e CSV. - Reviews Google via Places API (New), filtradas por classificação mínima e em cache configurável; página de configuração com pesquisa do Place ID. - Assets com ?v=<mtime>: site/assets é servido com cache imutável de 1 ano. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8a494d59a5
commit
f95c9ebc52
27 files changed
+2063
-16
No files matched your search
+10
-2
@@ -9,11 +9,19 @@ if (!defined('SITE_INCLUDES')) {
|
||||
}
|
||||
|
||||
// <script src> / <link rel=stylesheet> tag builders (CI4 html helper).
|
||||
// site/assets is served with a one-year immutable Cache-Control, so local files
|
||||
// carry their mtime as ?v= — an edited style.css/main.js gets a new URL instead
|
||||
// of staying stuck in returning visitors' caches.
|
||||
function _asset_versioned(string $path): string {
|
||||
$file = dirname(__DIR__) . '/' . ltrim($path, '/');
|
||||
if (strpos($path, '?') !== false || preg_match('~^https?://~', $path) || !is_file($file)) return base_url($path);
|
||||
return base_url($path) . '?v=' . filemtime($file);
|
||||
}
|
||||
function script_tag(string $src): string {
|
||||
return '<script src="' . htmlspecialchars(base_url($src), ENT_QUOTES) . '"></script>' . "\n";
|
||||
return '<script src="' . htmlspecialchars(_asset_versioned($src), ENT_QUOTES) . '"></script>' . "\n";
|
||||
}
|
||||
function link_tag(string $href, string $rel = 'stylesheet'): string {
|
||||
return '<link rel="' . $rel . '" href="' . htmlspecialchars(base_url($href), ENT_QUOTES) . '">' . "\n";
|
||||
return '<link rel="' . $rel . '" href="' . htmlspecialchars(_asset_versioned($href), ENT_QUOTES) . '">' . "\n";
|
||||
}
|
||||
function site_url(string $path = ''): string { return base_url($path); }
|
||||
|
||||
|
||||
@@ -31,6 +31,9 @@ require_once __DIR__ . '/functions_galerias.php'; // galleries + images CRU
|
||||
require_once __DIR__ . '/functions_work_hours.php'; // work hours CRUD
|
||||
require_once __DIR__ . '/functions_horario.php'; // class schedule CRUD
|
||||
require_once __DIR__ . '/functions_events.php'; // time-limited events + landing pages + leads
|
||||
require_once __DIR__ . '/functions_info.php'; // contactos (fitme3070_info) editor
|
||||
require_once __DIR__ . '/functions_memberships.php'; // mensalidades + pedidos de inscrição
|
||||
require_once __DIR__ . '/functions_reviews.php'; // reviews Google (Places API) + cache
|
||||
|
||||
// ─── DB-backed settings → legacy constants ───────────────────────────────────
|
||||
// Resolved once from the settings cache so call sites read plain constants.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
// ─── Contactos (fitme3070_info, linha id=1) ───────────────────────────────────
|
||||
// Single-row table read by site_info() (functions_site.php) — contact section,
|
||||
// footer, mobile "Ligar" bar, WhatsApp button and the SEO JSON-LD all take their
|
||||
// values from here, so one save updates every place.
|
||||
// Used by views/admin/info/edit.php.
|
||||
|
||||
// field => [label, max length, input type]. Order is the form order.
|
||||
function info_fields(): array {
|
||||
return [
|
||||
'name' => ['Nome do ginásio', 200, 'text'],
|
||||
'adress' => ['Morada', 200, 'text'],
|
||||
'phone' => ['Telefone principal', 25, 'tel'],
|
||||
'telephone' => ['Telefone secundário', 25, 'tel'],
|
||||
'whatsapp' => ['WhatsApp (só dígitos, ex.: 351964201137)', 13, 'text'],
|
||||
'email' => ['E-mail', 100, 'email'],
|
||||
'website' => ['Website', 100, 'text'],
|
||||
'instagram' => ['Instagram (URL)', 200, 'url'],
|
||||
'facebook' => ['Facebook (URL)', 200, 'url'],
|
||||
'messenger' => ['Messenger (URL)', 200, 'url'],
|
||||
'google_maps_link' => ['Google Maps — link', 255, 'url'],
|
||||
'google_maps' => ['Google Maps — código embed (iframe)', 0, 'textarea'],
|
||||
];
|
||||
}
|
||||
|
||||
function info_from_post(array $post, array &$errors): array {
|
||||
$data = [];
|
||||
foreach (info_fields() as $key => [$label, $max, $type]) {
|
||||
$v = trim((string) ($post[$key] ?? ''));
|
||||
if ($key === 'whatsapp') $v = preg_replace('/\D+/', '', $v);
|
||||
if ($max > 0 && mb_strlen($v) > $max) $errors[] = "«{$label}» tem mais de {$max} caracteres.";
|
||||
if ($v !== '' && $type === 'email' && !filter_var($v, FILTER_VALIDATE_EMAIL)) $errors[] = 'O e-mail não é válido.';
|
||||
if ($v !== '' && $type === 'url' && !preg_match('~^https?://~i', $v)) $errors[] = "«{$label}» tem de começar por https://";
|
||||
$data[$key] = $v;
|
||||
}
|
||||
// Only a Google Maps iframe survives; anything else is dropped here rather
|
||||
// than stored and filtered on every page view.
|
||||
$data['google_maps'] = clean_map_embed($data['google_maps']);
|
||||
if ($data['name'] === '') $errors[] = 'O nome é obrigatório.';
|
||||
if ($data['phone'] === '') $errors[] = 'O telefone principal é obrigatório.';
|
||||
return $data;
|
||||
}
|
||||
|
||||
function db_info_save(PDO $pdo, array $data): bool {
|
||||
$cols = array_keys(info_fields());
|
||||
$exists = (bool) $pdo->query("SELECT COUNT(*) FROM fitme3070_info WHERE id = 1")->fetchColumn();
|
||||
$vals = array_map(fn($c) => $data[$c] ?? '', $cols);
|
||||
if ($exists) {
|
||||
$sets = implode(', ', array_map(fn($c) => "`$c` = ?", $cols));
|
||||
$stmt = $pdo->prepare("UPDATE fitme3070_info SET $sets, updated_at = NOW() WHERE id = 1");
|
||||
} else {
|
||||
$names = implode(', ', array_map(fn($c) => "`$c`", $cols));
|
||||
$marks = implode(', ', array_fill(0, count($cols), '?'));
|
||||
$stmt = $pdo->prepare("INSERT INTO fitme3070_info (id, $names, updated_at) VALUES (1, $marks, NOW())");
|
||||
}
|
||||
$stmt->execute($vals);
|
||||
return $stmt->rowCount() > 0;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
// ─── Mensalidades (cartões de preço) + pedidos de inscrição ───────────────────
|
||||
// Soft-delete via deleted_at. Only one card may be featured at a time — enforced
|
||||
// here, on save, rather than in the schema.
|
||||
// Used by views/admin/memberships/*.php, site/index.php and site/inscricao.php.
|
||||
|
||||
function memberships_defaults(): array {
|
||||
return [
|
||||
'name' => '', 'subtitle' => '', 'price' => '', 'is_addon' => 0,
|
||||
'price_suffix' => '/mês', 'features' => '', 'is_featured' => 0,
|
||||
'featured_label' => 'Mais popular', 'cta_label' => 'Inscrever',
|
||||
'item_order' => 0, 'is_active' => 1,
|
||||
];
|
||||
}
|
||||
|
||||
function db_memberships_list(PDO $pdo, bool $include_deleted = false): array {
|
||||
$sql = "SELECT * FROM memberships";
|
||||
if (!$include_deleted) $sql .= " WHERE deleted_at IS NULL";
|
||||
$sql .= " ORDER BY deleted_at IS NOT NULL, item_order, name";
|
||||
return $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
// Public list: active, not deleted. Defensive — the table may not exist yet on
|
||||
// an install that hasn't run the migration.
|
||||
function site_memberships(PDO $pdo): array {
|
||||
try {
|
||||
return $pdo->query(
|
||||
"SELECT * FROM memberships WHERE deleted_at IS NULL AND is_active = 1 ORDER BY item_order, name"
|
||||
)->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (Throwable $e) { return []; }
|
||||
}
|
||||
|
||||
function db_memberships_get(PDO $pdo, int $id): ?array {
|
||||
$stmt = $pdo->prepare("SELECT * FROM memberships WHERE id = ? LIMIT 1");
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
|
||||
}
|
||||
|
||||
// Normalise raw POST into the row shape; appends messages to $errors.
|
||||
function memberships_from_post(array $post, array &$errors): array {
|
||||
$price = str_replace([' ', '€'], '', trim((string) ($post['price'] ?? '')));
|
||||
$price = str_replace(',', '.', $price);
|
||||
$data = [
|
||||
'name' => mb_substr(trim((string) ($post['name'] ?? '')), 0, 100),
|
||||
'subtitle' => mb_substr(trim((string) ($post['subtitle'] ?? '')), 0, 255),
|
||||
'price' => $price,
|
||||
'is_addon' => !empty($post['is_addon']) ? 1 : 0,
|
||||
'price_suffix' => mb_substr(trim((string) ($post['price_suffix'] ?? '')), 0, 60),
|
||||
'features' => trim((string) ($post['features'] ?? '')),
|
||||
'is_featured' => !empty($post['is_featured']) ? 1 : 0,
|
||||
'featured_label' => mb_substr(trim((string) ($post['featured_label'] ?? '')), 0, 40),
|
||||
'cta_label' => mb_substr(trim((string) ($post['cta_label'] ?? '')), 0, 40),
|
||||
'item_order' => (int) ($post['item_order'] ?? 0),
|
||||
'is_active' => !empty($post['is_active']) ? 1 : 0,
|
||||
];
|
||||
if ($data['name'] === '') $errors[] = 'O nome é obrigatório.';
|
||||
if ($price !== '' && (!is_numeric($price) || (float) $price < 0)) $errors[] = 'Preço inválido — usa um número, ex.: 34,90.';
|
||||
if ($data['featured_label'] === '') $data['featured_label'] = 'Mais popular';
|
||||
if ($data['cta_label'] === '') $data['cta_label'] = 'Inscrever';
|
||||
return $data;
|
||||
}
|
||||
|
||||
function _memberships_params(array $d): array {
|
||||
return [
|
||||
$d['name'], $d['subtitle'],
|
||||
$d['price'] === '' || $d['price'] === null ? null : number_format((float) $d['price'], 2, '.', ''),
|
||||
$d['is_addon'], $d['price_suffix'], $d['features'] !== '' ? $d['features'] : null,
|
||||
$d['is_featured'], $d['featured_label'], $d['cta_label'], $d['item_order'], $d['is_active'],
|
||||
];
|
||||
}
|
||||
|
||||
function _memberships_clear_featured(PDO $pdo, int $except): void {
|
||||
$pdo->prepare("UPDATE memberships SET is_featured = 0 WHERE id <> ? AND is_featured = 1")->execute([$except]);
|
||||
}
|
||||
|
||||
function db_memberships_create(PDO $pdo, array $d): int {
|
||||
$pdo->beginTransaction();
|
||||
$stmt = $pdo->prepare("
|
||||
INSERT INTO memberships (name, subtitle, price, is_addon, price_suffix, features,
|
||||
is_featured, featured_label, cta_label, item_order, is_active,
|
||||
created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?, NOW(), NOW())
|
||||
");
|
||||
$stmt->execute(_memberships_params($d));
|
||||
$id = (int) $pdo->lastInsertId();
|
||||
if ($d['is_featured']) _memberships_clear_featured($pdo, $id);
|
||||
$pdo->commit();
|
||||
return $id;
|
||||
}
|
||||
|
||||
function db_memberships_update(PDO $pdo, int $id, array $d): bool {
|
||||
$pdo->beginTransaction();
|
||||
$stmt = $pdo->prepare("
|
||||
UPDATE memberships SET name = ?, subtitle = ?, price = ?, is_addon = ?, price_suffix = ?,
|
||||
features = ?, is_featured = ?, featured_label = ?, cta_label = ?, item_order = ?,
|
||||
is_active = ?, updated_at = NOW()
|
||||
WHERE id = ?
|
||||
");
|
||||
$params = _memberships_params($d);
|
||||
$params[] = $id;
|
||||
$stmt->execute($params);
|
||||
$changed = $stmt->rowCount() > 0;
|
||||
if ($d['is_featured']) _memberships_clear_featured($pdo, $id);
|
||||
$pdo->commit();
|
||||
return $changed;
|
||||
}
|
||||
|
||||
function db_memberships_delete(PDO $pdo, int $id): bool {
|
||||
$stmt = $pdo->prepare("UPDATE memberships SET deleted_at = NOW(), is_featured = 0 WHERE id = ? AND deleted_at IS NULL");
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->rowCount() > 0;
|
||||
}
|
||||
|
||||
function db_memberships_restore(PDO $pdo, int $id): bool {
|
||||
$stmt = $pdo->prepare("UPDATE memberships SET deleted_at = NULL WHERE id = ? AND deleted_at IS NOT NULL");
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->rowCount() > 0;
|
||||
}
|
||||
|
||||
// "34,90 €" / "+10 €" / "Sob consulta" — PT formatting, drops ",00".
|
||||
function membership_price_label(array $m): string {
|
||||
if ($m['price'] === null || $m['price'] === '') return 'Sob consulta';
|
||||
$p = (float) $m['price'];
|
||||
$s = number_format($p, floor($p) == $p ? 0 : 2, ',', ' ');
|
||||
return (!empty($m['is_addon']) ? '+' : '') . $s . ' €';
|
||||
}
|
||||
|
||||
// Non-empty trimmed lines of a textarea — used for features, skills, formações.
|
||||
function text_lines(?string $text): array {
|
||||
$out = [];
|
||||
foreach (preg_split('/\R/', (string) $text) as $line) {
|
||||
$line = trim($line, " \t-•");
|
||||
if ($line !== '') $out[] = $line;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
// ─── Pedidos de inscrição (leads) ─────────────────────────────────────────────
|
||||
|
||||
function membership_lead_statuses(): array {
|
||||
return ['novo' => 'Novo', 'contactado' => 'Contactado', 'inscrito' => 'Inscrito', 'descartado' => 'Descartado'];
|
||||
}
|
||||
|
||||
function db_membership_leads_list(PDO $pdo, string $status = ''): array {
|
||||
$sql = "SELECT * FROM membership_leads";
|
||||
$args = [];
|
||||
if ($status !== '' && isset(membership_lead_statuses()[$status])) { $sql .= " WHERE status = ?"; $args[] = $status; }
|
||||
$sql .= " ORDER BY created_at DESC, id DESC";
|
||||
$stmt = $pdo->prepare($sql);
|
||||
$stmt->execute($args);
|
||||
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
||||
function db_membership_leads_count_new(PDO $pdo): int {
|
||||
try { return (int) $pdo->query("SELECT COUNT(*) FROM membership_leads WHERE status = 'novo'")->fetchColumn(); }
|
||||
catch (Throwable $e) { return 0; }
|
||||
}
|
||||
|
||||
function db_membership_lead_create(PDO $pdo, array $d): int {
|
||||
$stmt = $pdo->prepare("
|
||||
INSERT INTO membership_leads (membership_id, membership_name, name, email, phone, message,
|
||||
consent, consent_text, ip, user_agent, created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?, NOW(), NOW())
|
||||
");
|
||||
$stmt->execute([
|
||||
$d['membership_id'] ?: null,
|
||||
mb_substr((string) ($d['membership_name'] ?? ''), 0, 100),
|
||||
mb_substr(trim((string) ($d['name'] ?? '')), 0, 150),
|
||||
mb_substr(trim((string) ($d['email'] ?? '')), 0, 190),
|
||||
mb_substr(trim((string) ($d['phone'] ?? '')), 0, 40),
|
||||
mb_substr(trim((string) ($d['message'] ?? '')), 0, 1000),
|
||||
!empty($d['consent']) ? 1 : 0,
|
||||
mb_substr((string) ($d['consent_text'] ?? ''), 0, 255),
|
||||
mb_substr((string) ($d['ip'] ?? ''), 0, 45),
|
||||
mb_substr((string) ($d['user_agent'] ?? ''), 0, 255),
|
||||
]);
|
||||
return (int) $pdo->lastInsertId();
|
||||
}
|
||||
|
||||
function db_membership_lead_update(PDO $pdo, int $id, string $status, string $notes): bool {
|
||||
if (!isset(membership_lead_statuses()[$status])) return false;
|
||||
$stmt = $pdo->prepare("UPDATE membership_leads SET status = ?, admin_notes = ?, updated_at = NOW() WHERE id = ?");
|
||||
$stmt->execute([$status, $notes !== '' ? $notes : null, $id]);
|
||||
return $stmt->rowCount() > 0;
|
||||
}
|
||||
|
||||
function db_membership_lead_delete(PDO $pdo, int $id): bool {
|
||||
$stmt = $pdo->prepare("DELETE FROM membership_leads WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->rowCount() > 0;
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
// ─── Reviews Google (Places API — New) ────────────────────────────────────────
|
||||
// The homepage shows the gym's best Google reviews, pulled live from Place
|
||||
// Details. Configured in the backoffice (views/admin/reviews/index.php):
|
||||
//
|
||||
// google_places_api_key — encrypted at rest (.env GOOGLE_PLACES_API_KEY wins)
|
||||
// google_place_id — the gym's Place ID
|
||||
// google_reviews_min_rating — only reviews with at least this many stars (default 4)
|
||||
// google_reviews_max — how many to show (default 3)
|
||||
// google_reviews_cache_hours — how long a fetch is reused (default 24)
|
||||
//
|
||||
// Two limits of the API shape the section:
|
||||
// - Place Details returns at most 5 reviews, chosen by Google ("most
|
||||
// relevant"). There is no "only positive" query: we filter those 5 by
|
||||
// rating, so on a bad week fewer than `max` may qualify.
|
||||
// - Reviews are a billed Enterprise + Atmosphere field. Without the cache every
|
||||
// page view would be one billed call; with it, one call per cache window.
|
||||
//
|
||||
// The cache is a PHP array literal under config/cache/ (like the settings
|
||||
// cache): read via include, served from opcache, never over HTTP. A failed
|
||||
// refresh keeps serving the previous copy so a key/quota problem never blanks
|
||||
// the section — the error is kept for the backoffice page to show.
|
||||
|
||||
const REVIEWS_FIELD_MASK = 'displayName,rating,userRatingCount,googleMapsUri,reviews';
|
||||
|
||||
function reviews_config(): array {
|
||||
return [
|
||||
'api_key' => setting_secret('google_places_api_key', 'GOOGLE_PLACES_API_KEY'),
|
||||
'place_id' => trim((string) setting('google_place_id', '')),
|
||||
'min_rating' => max(1, min(5, (int) setting('google_reviews_min_rating', 4))),
|
||||
'max' => max(1, min(5, (int) setting('google_reviews_max', 3))),
|
||||
'cache_hours' => max(1, (int) setting('google_reviews_cache_hours', 24)),
|
||||
];
|
||||
}
|
||||
|
||||
function reviews_configured(): bool {
|
||||
$c = reviews_config();
|
||||
return $c['api_key'] !== '' && $c['place_id'] !== '';
|
||||
}
|
||||
|
||||
function _reviews_cache_path(): string {
|
||||
return __DIR__ . '/cache/google_reviews.cache.php';
|
||||
}
|
||||
|
||||
function reviews_cache_read(): ?array {
|
||||
$path = _reviews_cache_path();
|
||||
if (!is_file($path)) return null;
|
||||
$data = @include $path;
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
function _reviews_cache_write(array $data): void {
|
||||
$path = _reviews_cache_path();
|
||||
if (!is_dir(dirname($path))) @mkdir(dirname($path), 0775, true);
|
||||
$tmp = $path . '.' . bin2hex(random_bytes(4)) . '.tmp';
|
||||
if (@file_put_contents($tmp, "<?php\nreturn " . var_export($data, true) . ";\n", LOCK_EX) === false) return;
|
||||
@rename($tmp, $path);
|
||||
if (function_exists('opcache_invalidate')) @opcache_invalidate($path, true);
|
||||
}
|
||||
|
||||
function reviews_cache_clear(): void {
|
||||
$path = _reviews_cache_path();
|
||||
if (is_file($path)) @unlink($path);
|
||||
}
|
||||
|
||||
// Low-level GET/POST against places.googleapis.com. Returns [status, decoded|null, error].
|
||||
function _places_request(string $method, string $url, string $apiKey, string $fieldMask, ?array $body = null): array {
|
||||
if (!function_exists('curl_init')) return [0, null, 'cURL indisponível nesta instalação.'];
|
||||
$ch = curl_init($url);
|
||||
$headers = ['X-Goog-Api-Key: ' . $apiKey, 'X-Goog-FieldMask: ' . $fieldMask, 'Accept: application/json'];
|
||||
if ($body !== null) {
|
||||
$headers[] = 'Content-Type: application/json';
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
|
||||
}
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_CUSTOMREQUEST => $method,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_CONNECTTIMEOUT => 3,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
]);
|
||||
$raw = curl_exec($ch);
|
||||
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$cerr = curl_error($ch);
|
||||
curl_close($ch);
|
||||
if ($raw === false) return [0, null, 'Sem ligação à Google: ' . $cerr];
|
||||
$json = json_decode((string) $raw, true);
|
||||
if ($status !== 200) {
|
||||
$msg = is_array($json) ? (string) ($json['error']['message'] ?? '') : '';
|
||||
return [$status, $json, 'Google respondeu ' . $status . ($msg !== '' ? ': ' . $msg : '')];
|
||||
}
|
||||
return [$status, is_array($json) ? $json : null, is_array($json) ? '' : 'Resposta inválida da Google.'];
|
||||
}
|
||||
|
||||
// Fetch Place Details now and rewrite the cache. Returns the cache array.
|
||||
function reviews_refresh(): array {
|
||||
$c = reviews_config();
|
||||
$old = reviews_cache_read() ?? [];
|
||||
if ($c['api_key'] === '' || $c['place_id'] === '') {
|
||||
return $old + ['error' => 'Falta a chave da API ou o Place ID.'];
|
||||
}
|
||||
$url = 'https://places.googleapis.com/v1/places/' . rawurlencode($c['place_id']) . '?languageCode=pt-PT';
|
||||
[$status, $json, $err] = _places_request('GET', $url, $c['api_key'], REVIEWS_FIELD_MASK);
|
||||
|
||||
if ($err !== '') {
|
||||
// Keep serving the previous copy; retry after an hour, not a full window.
|
||||
$data = $old;
|
||||
$data['error'] = $err;
|
||||
$data['error_at'] = time();
|
||||
$data['fetched_at'] = time() - max(0, $c['cache_hours'] * 3600 - 3600);
|
||||
_reviews_cache_write($data);
|
||||
error_log('[reviews] ' . $err);
|
||||
return $data;
|
||||
}
|
||||
|
||||
$reviews = [];
|
||||
foreach ((array) ($json['reviews'] ?? []) as $r) {
|
||||
$reviews[] = [
|
||||
'rating' => (int) ($r['rating'] ?? 0),
|
||||
'text' => (string) ($r['text']['text'] ?? $r['originalText']['text'] ?? ''),
|
||||
'relative' => (string) ($r['relativePublishTimeDescription'] ?? ''),
|
||||
'published' => (string) ($r['publishTime'] ?? ''),
|
||||
'author' => (string) ($r['authorAttribution']['displayName'] ?? ''),
|
||||
'author_uri' => (string) ($r['authorAttribution']['uri'] ?? ''),
|
||||
'author_photo' => (string) ($r['authorAttribution']['photoUri'] ?? ''),
|
||||
'uri' => (string) ($r['googleMapsUri'] ?? ''),
|
||||
];
|
||||
}
|
||||
$data = [
|
||||
'fetched_at' => time(),
|
||||
'name' => (string) ($json['displayName']['text'] ?? ''),
|
||||
'rating' => isset($json['rating']) ? (float) $json['rating'] : null,
|
||||
'total' => (int) ($json['userRatingCount'] ?? 0),
|
||||
'maps_uri' => (string) ($json['googleMapsUri'] ?? ''),
|
||||
'reviews' => $reviews,
|
||||
'error' => '',
|
||||
];
|
||||
_reviews_cache_write($data);
|
||||
return $data;
|
||||
}
|
||||
|
||||
// Cached data, refreshed when older than the cache window. The refresh is
|
||||
// serialised with a non-blocking lock so a burst of visitors at expiry makes
|
||||
// one Google call, not one each — the others just serve the stale copy.
|
||||
function reviews_get(): array {
|
||||
$c = reviews_config();
|
||||
$cache = reviews_cache_read();
|
||||
$fresh = $cache && (time() - (int) ($cache['fetched_at'] ?? 0)) < $c['cache_hours'] * 3600;
|
||||
if ($fresh || !reviews_configured()) return $cache ?? [];
|
||||
|
||||
$lock = @fopen(_reviews_cache_path() . '.lock', 'c');
|
||||
if ($lock && flock($lock, LOCK_EX | LOCK_NB)) {
|
||||
$cache = reviews_refresh();
|
||||
flock($lock, LOCK_UN);
|
||||
}
|
||||
if ($lock) fclose($lock);
|
||||
return $cache ?? [];
|
||||
}
|
||||
|
||||
// What the homepage renders: summary + the best qualifying reviews, or null
|
||||
// when there is nothing worth showing (not configured, no qualifying review).
|
||||
function site_reviews(): ?array {
|
||||
try { $data = reviews_get(); } catch (Throwable $e) { error_log('[reviews] ' . $e->getMessage()); return null; }
|
||||
if (!$data || empty($data['reviews'])) return null;
|
||||
$c = reviews_config();
|
||||
$picked = array_values(array_filter($data['reviews'], fn($r) => $r['rating'] >= $c['min_rating'] && trim($r['text']) !== ''));
|
||||
// Highest rating first; Google's relevance order breaks ties (usort is stable).
|
||||
usort($picked, fn($a, $b) => $b['rating'] <=> $a['rating']);
|
||||
$picked = array_slice($picked, 0, $c['max']);
|
||||
if (!$picked) return null;
|
||||
return [
|
||||
'rating' => $data['rating'],
|
||||
'total' => $data['total'],
|
||||
'maps_uri' => $data['maps_uri'],
|
||||
'write_uri' => 'https://search.google.com/local/writereview?placeid=' . rawurlencode($c['place_id']),
|
||||
'reviews' => $picked,
|
||||
];
|
||||
}
|
||||
|
||||
// Backoffice helper: find the Place ID from a free-text query (Text Search,
|
||||
// IDs + name + address only — the cheapest field set).
|
||||
function reviews_find_place(string $query, string $apiKey): array {
|
||||
[$status, $json, $err] = _places_request(
|
||||
'POST', 'https://places.googleapis.com/v1/places:searchText', $apiKey,
|
||||
'places.id,places.displayName,places.formattedAddress,places.rating,places.userRatingCount',
|
||||
['textQuery' => $query, 'languageCode' => 'pt-PT', 'regionCode' => 'PT']
|
||||
);
|
||||
if ($err !== '') return ['error' => $err, 'places' => []];
|
||||
$out = [];
|
||||
foreach ((array) ($json['places'] ?? []) as $p) {
|
||||
$out[] = [
|
||||
'id' => (string) ($p['id'] ?? ''),
|
||||
'name' => (string) ($p['displayName']['text'] ?? ''),
|
||||
'address' => (string) ($p['formattedAddress'] ?? ''),
|
||||
'rating' => $p['rating'] ?? null,
|
||||
'total' => (int) ($p['userRatingCount'] ?? 0),
|
||||
];
|
||||
}
|
||||
return ['error' => '', 'places' => $out];
|
||||
}
|
||||
@@ -30,6 +30,7 @@ function site_navbar(): array {
|
||||
'Equipa' => '#equipa',
|
||||
'Modalidades' => '#modalidades',
|
||||
'Horário' => '#horario',
|
||||
'Mensalidades' => '#mensalidades',
|
||||
'Contactos' => '#contactos',
|
||||
'CrossFit' => 'home/crossfit', // separate page, navbar styles it specially
|
||||
];
|
||||
|
||||
@@ -18,28 +18,35 @@ function db_team_get(PDO $pdo, int $id): ?array {
|
||||
|
||||
function db_team_create(PDO $pdo, array $data): int {
|
||||
$stmt = $pdo->prepare("
|
||||
INSERT INTO team (name, birthday, `at`, status, description, photo, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
|
||||
INSERT INTO team (name, title, birthday, `at`, status, description, skills, certifications, photo, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
|
||||
");
|
||||
$stmt->execute([
|
||||
$data['name'],
|
||||
$data['title'] ?? '',
|
||||
$data['birthday'] ?: null,
|
||||
$data['at'] ?: null,
|
||||
$data['status'] ?? 'ativo',
|
||||
$data['description'] ?? null,
|
||||
($data['skills'] ?? '') !== '' ? $data['skills'] : null,
|
||||
($data['certifications'] ?? '') !== '' ? $data['certifications'] : null,
|
||||
$data['photo'] ?? null,
|
||||
]);
|
||||
return (int) $pdo->lastInsertId();
|
||||
}
|
||||
|
||||
function db_team_update(PDO $pdo, int $id, array $data, ?string $photo = null): bool {
|
||||
$sets = ["name = ?", "birthday = ?", "`at` = ?", "status = ?", "description = ?", "updated_at = NOW()"];
|
||||
$sets = ["name = ?", "title = ?", "birthday = ?", "`at` = ?", "status = ?", "description = ?",
|
||||
"skills = ?", "certifications = ?", "updated_at = NOW()"];
|
||||
$params = [
|
||||
$data['name'],
|
||||
$data['title'] ?? '',
|
||||
$data['birthday'] ?: null,
|
||||
$data['at'] ?: null,
|
||||
$data['status'] ?? 'ativo',
|
||||
$data['description'] ?? null,
|
||||
($data['skills'] ?? '') !== '' ? $data['skills'] : null,
|
||||
($data['certifications'] ?? '') !== '' ? $data['certifications'] : null,
|
||||
];
|
||||
if ($photo !== null) {
|
||||
$sets[] = "photo = ?";
|
||||
|
||||
Reference in new issue
Block a user