Add admin health page and printable 24h export

- add a protected health.php page for config, XMLTV and M3U diagnostics
- add shared admin/config helpers for authenticated internal tools
- add a styled 24h export page designed for PDF/print output
- add browser-side PNG export for the daily schedule
- update README with the new admin tools
This commit is contained in:
Johnnybegood90 committed 2026-03-15 01:44:22 +01:00
1 parent c46ca14f4c
commit a81e33ccb8
6 files changed
+708 -2

No files matched your search

+12 -2
View File
@@ -43,6 +43,8 @@ This demo runs with sample XMLTV feeds to showcase the interface.
- ⭐ **Favorites** — pin channels to the top of the grid, persisted in localStorage - ⭐ **Favorites** — pin channels to the top of the grid, persisted in localStorage
- 🌍 **i18n** — auto-detects browser language, supports EN / FR / ES (add your own in `locales/`) - 🌍 **i18n** — auto-detects browser language, supports EN / FR / ES (add your own in `locales/`)
- ⚙️ **Re-editable setup** — protected by an admin key, no SSH required to update config - ⚙️ **Re-editable setup** — protected by an admin key, no SSH required to update config
- 🩺 **Admin health page** — check config, XMLTV, M3U, response times, and metadata coverage
- 🖨️ **24h printable export** — generate a polished daily schedule for PDF/print and PNG export
- 🔔 **Update notifications** — a badge appears in the topbar when a new release is available on GitHub - 🔔 **Update notifications** — a badge appears in the topbar when a new release is available on GitHub
- 🔄 **Auto-reload** EPG every 30 minutes - 🔄 **Auto-reload** EPG every 30 minutes
- 0️⃣ **Zero build tooling** — vanilla PHP/JS/CSS, with bundled local assets - 0️⃣ **Zero build tooling** — vanilla PHP/JS/CSS, with bundled local assets
@@ -225,6 +227,13 @@ GridTV detects the missing config and automatically redirects you to the setup p
Once submitted, `config.json` is created on the server. **The setup page becomes inaccessible until you re-enter your admin key.** Once submitted, `config.json` is created on the server. **The setup page becomes inaccessible until you re-enter your admin key.**
Admin tools are available here once unlocked with the same key:
```text
http://guide.your-domain.com/health.php
http://guide.your-domain.com/export.php
```
--- ---
<details> <details>
@@ -280,9 +289,10 @@ nano /var/www/gridtv/config.json
gridtv/ gridtv/
├── index.php # Entry point ├── index.php # Entry point
├── setup.php # Setup + re-configuration (admin key protected) ├── setup.php # Setup + re-configuration (admin key protected)
├── health.php # Admin diagnostics page
├── export.php # 24h printable export (PDF/image friendly)
├── proxy.php # HTTP→HTTPS stream proxy ├── proxy.php # HTTP→HTTPS stream proxy
├── version.json # Current version (used for update check) ├── version.json # Current version (used for update check)
├── config.example.json # Config template
├── Dockerfile ├── Dockerfile
├── docker-compose.yml ├── docker-compose.yml
├── .gitignore # config.json excluded ├── .gitignore # config.json excluded
@@ -485,9 +495,9 @@ GNU Affero General Public License v3.0 (AGPLv3)
- **i18n** — EN / FR / ES with browser auto-detection, extensible via locales/ - **i18n** — EN / FR / ES with browser auto-detection, extensible via locales/
- **Favorites** — pin channels to the top of the grid (localStorage) - **Favorites** — pin channels to the top of the grid (localStorage)
- **Setup re-editable** — protected by an admin key, auto-generated on first setup - **Setup re-editable** — protected by an admin key, auto-generated on first setup
- **Admin health page** — diagnostics for config, XMLTV, M3U, timing, and metadata coverage
- **Update notifications** — topbar badge links to latest GitHub release - **Update notifications** — topbar badge links to latest GitHub release
### 🔜 Coming soon ### 🔜 Coming soon
- **Dark/Light auto mode** — follow system preference when using the default theme - **Dark/Light auto mode** — follow system preference when using the default theme
- **Grid export** — export today's schedule as PDF or image
</details> </details>
+20
View File
@@ -0,0 +1,20 @@
/*!
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
!function(A,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(A="undefined"!=typeof globalThis?globalThis:A||self).html2canvas=e()}(this,function(){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var r=function(A,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(A,e){A.__proto__=e}||function(A,e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(A[t]=e[t])})(A,e)};function A(A,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function t(){this.constructor=A}r(A,e),A.prototype=null===e?Object.create(e):(t.prototype=e.prototype,new t)}var h=function(){return(h=Object.assign||function(A){for(var e,t=1,r=arguments.length;t<r;t++)for(var B in e=arguments[t])Object.prototype.hasOwnProperty.call(e,B)&&(A[B]=e[B]);return A}).apply(this,arguments)};function a(A,s,o,i){return new(o=o||Promise)(function(t,e){function r(A){try{n(i.next(A))}catch(A){e(A)}}function B(A){try{n(i.throw(A))}catch(A){e(A)}}function n(A){var e;A.done?t(A.value):((e=A.value)instanceof o?e:new o(function(A){A(e)})).then(r,B)}n((i=i.apply(A,s||[])).next())})}function H(t,r){var B,n,s,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},A={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(A[Symbol.iterator]=function(){return this}),A;function e(e){return function(A){return function(e){if(B)throw new TypeError("Generator is already executing.");for(;o;)try{if(B=1,n&&(s=2&e[0]?n.return:e[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,e[1])).done)return s;switch(n=0,(e=s?[2&e[0],s.value]:e)[0]){case 0:case 1:s=e;break;case 4:return o.label++,{value:e[1],done:!1};case 5:o.label++,n=e[1],e=[0];continue;case 7:e=o.ops.pop(),o.trys.pop();continue;default:if(!(s=0<(s=o.trys).length&&s[s.length-1])&&(6===e[0]||2===e[0])){o=0;continue}if(3===e[0]&&(!s||e[1]>s[0]&&e[1]<s[3])){o.label=e[1];break}if(6===e[0]&&o.label<s[1]){o.label=s[1],s=e;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(e);break}s[2]&&o.ops.pop(),o.trys.pop();continue}e=r.call(t,o)}catch(A){e=[6,A],n=0}finally{B=s=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([e,A])}}}function t(A,e,t){if(t||2===arguments.length)for(var r,B=0,n=e.length;B<n;B++)!r&&B in e||((r=r||Array.prototype.slice.call(e,0,B))[B]=e[B]);return A.concat(r||e)}var d=(B.prototype.add=function(A,e,t,r){return new B(this.left+A,this.top+e,this.width+t,this.height+r)},B.fromClientRect=function(A,e){return new B(e.left+A.windowBounds.left,e.top+A.windowBounds.top,e.width,e.height)},B.fromDOMRectList=function(A,e){e=Array.from(e).find(function(A){return 0!==A.width});return e?new B(e.left+A.windowBounds.left,e.top+A.windowBounds.top,e.width,e.height):B.EMPTY},B.EMPTY=new B(0,0,0,0),B);function B(A,e,t,r){this.left=A,this.top=e,this.width=t,this.height=r}for(var f=function(A,e){return d.fromClientRect(A,e.getBoundingClientRect())},Q=function(A){for(var e=[],t=0,r=A.length;t<r;){var B,n=A.charCodeAt(t++);55296<=n&&n<=56319&&t<r?56320==(64512&(B=A.charCodeAt(t++)))?e.push(((1023&n)<<10)+(1023&B)+65536):(e.push(n),t--):e.push(n)}return e},g=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];if(String.fromCodePoint)return String.fromCodePoint.apply(String,A);var t=A.length;if(!t)return"";for(var r=[],B=-1,n="";++B<t;){var s=A[B];s<=65535?r.push(s):(s-=65536,r.push(55296+(s>>10),s%1024+56320)),(B+1===t||16384<r.length)&&(n+=String.fromCharCode.apply(String,r),r.length=0)}return n},e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="undefined"==typeof Uint8Array?[]:new Uint8Array(256),s=0;s<e.length;s++)n[e.charCodeAt(s)]=s;for(var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i=0;i<o.length;i++)c[o.charCodeAt(i)]=i;function w(A,e,t){return A.slice?A.slice(e,t):new Uint16Array(Array.prototype.slice.call(A,e,t))}var U=(l.prototype.get=function(A){var e;if(0<=A){if(A<55296||56319<A&&A<=65535)return e=this.index[A>>5],this.data[e=(e<<2)+(31&A)];if(A<=65535)return e=this.index[2048+(A-55296>>5)],this.data[e=(e<<2)+(31&A)];if(A<this.highStart)return e=this.index[e=2080+(A>>11)],e=this.index[e+=A>>5&63],this.data[e=(e<<2)+(31&A)];if(A<=1114111)return this.data[this.highValueIndex]}return this.errorValue},l);function l(A,e,t,r,B,n){this.initialValue=A,this.errorValue=e,this.highStart=t,this.highValueIndex=r,this.index=B,this.data=n}for(var C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u="undefined"==typeof Uint8Array?[]:new Uint8Array(256),F=0;F<C.length;F++)u[C.charCodeAt(F)]=F;function p(A,e,t,r){var B=r[t];if(Array.isArray(A)?-1!==A.indexOf(B):A===B)for(var n=t;n<=r.length;){if((o=r[++n])===e)return 1;if(o!==D)break}if(B===D)for(n=t;0<n;){var s=r[--n];if(Array.isArray(A)?-1!==A.indexOf(s):A===s)for(var o,i=t;i<=r.length;){if((o=r[++i])===e)return 1;if(o!==D)break}if(s!==D)break}}function E(A,e){for(var t=A;0<=t;){var r=e[t];if(r!==D)return r;t--}return 0}function I(t,A){var e=(B=function(A,r){void 0===r&&(r="strict");var B=[],n=[],sLine truncated
+246
View File
@@ -0,0 +1,246 @@
<?php
require_once __DIR__ . '/src/lib/admin.php';
$config = gridtv_load_config();
gridtv_require_admin($config, 'Export');
[$locale, $L] = gridtv_load_locale($config);
function export_parse_xmltv_programmes(string $xml, string $target_day): array {
libxml_use_internal_errors(true);
$dom = new DOMDocument();
if (!$dom->loadXML($xml, LIBXML_NOERROR | LIBXML_NOWARNING)) {
return ['channels' => [], 'programmes' => [], 'error' => 'Invalid XMLTV response'];
}
$xp = new DOMXPath($dom);
$channels = [];
foreach ($xp->query('/tv/channel') as $channel) {
$id = $channel->getAttribute('id');
$name = trim($xp->evaluate('string(display-name[1])', $channel));
$icon = trim($xp->evaluate('string(icon/@src)', $channel));
$channels[$id] = ['id' => $id, 'name' => $name ?: $id, 'icon' => $icon];
}
$start_day = new DateTimeImmutable($target_day . ' 00:00:00');
$end_day = $start_day->modify('+1 day');
$rows = [];
foreach ($xp->query('/tv/programme') as $programme) {
$channel_id = $programme->getAttribute('channel');
$start = DateTimeImmutable::createFromFormat('YmdHis O', $programme->getAttribute('start'));
$stop = DateTimeImmutable::createFromFormat('YmdHis O', $programme->getAttribute('stop'));
if (!$start || !$stop) continue;
if ($stop <= $start_day || $start >= $end_day) continue;
$title = trim($xp->evaluate('string(title)', $programme));
$subtitle = trim($xp->evaluate('string(sub-title)', $programme));
$desc = trim($xp->evaluate('string(desc)', $programme));
$rating = trim($xp->evaluate('string(rating/value)', $programme));
$cats = [];
foreach ($xp->query('category', $programme) as $cat) {
$value = trim($cat->textContent);
if ($value !== '') $cats[strtolower($value)] = $value;
}
$rows[$channel_id][] = [
'start' => $start,
'stop' => $stop,
'title' => $title,
'subtitle' => $subtitle,
'desc' => $desc,
'rating' => $rating,
'categories' => array_values($cats),
];
}
uasort($channels, static function ($a, $b) {
preg_match('/^\d+/', $a['name'], $ma);
preg_match('/^\d+/', $b['name'], $mb);
$na = isset($ma[0]) ? (int) $ma[0] : 9999;
$nb = isset($mb[0]) ? (int) $mb[0] : 9999;
return $na <=> $nb ?: strcmp($a['name'], $b['name']);
});
foreach ($rows as &$programmes) {
usort($programmes, static fn($a, $b) => $a['start'] <=> $b['start']);
}
return ['channels' => $channels, 'programmes' => $rows, 'error' => ''];
}
$sources = array_values($config['epg_sources'] ?? []);
$source_index = max(0, min((int) ($_GET['source'] ?? 0), max(count($sources) - 1, 0)));
$source = $sources[$source_index] ?? null;
$target_day = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) ($_GET['day'] ?? '')) ? (string) $_GET['day'] : (new DateTimeImmutable('today'))->format('Y-m-d');
$fetch = $source ? gridtv_fetch_url((string) $source['epg_url'], 25) : ['ok' => false, 'error' => 'No source configured', 'body' => ''];
$parsed = $fetch['ok'] ? export_parse_xmltv_programmes($fetch['body'], $target_day) : ['channels' => [], 'programmes' => [], 'error' => $fetch['error'] ?: 'Unable to fetch XMLTV'];
$print_channels = [];
foreach ($parsed['channels'] as $channel_id => $channel) {
if (!empty($parsed['programmes'][$channel_id])) {
$print_channels[$channel_id] = $channel;
}
}
$day_label = (new DateTimeImmutable($target_day))->format('l d F Y');
?><!DOCTYPE html>
<html lang="<?= htmlspecialchars($locale) ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GridTV — Export 24h</title>
<link rel="stylesheet" href="/assets/fonts/fonts.css">
<script src="/assets/vendor/html2canvas.min.js"></script>
<style>
:root{--paper:#f4ecda;--ink:#22201b;--ink-soft:#675f52;--accent:#aa4231;--accent-2:#264653;--line:#d3c5ab;--stamp:#d8b24a}
*{box-sizing:border-box}body{margin:0;font-family:'Barlow Condensed',sans-serif;background:linear-gradient(180deg,#1f2125 0,#121317 100%);color:#f7f4ee}
.page{max-width:1380px;margin:0 auto;padding:26px 18px 40px}
.toolbar{display:flex;justify-content:space-between;gap:16px;align-items:flex-start;flex-wrap:wrap;margin-bottom:18px}
.heading{max-width:760px}.heading h1{margin:0 0 6px;font-size:34px;letter-spacing:.06em;text-transform:uppercase}.heading p{margin:0;color:#bcb7ad;font-size:14px;line-height:1.5}
.controls{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
.controls a,.controls button,.controls select,.controls input{height:42px;border:none}
.controls a,.controls button{display:inline-flex;align-items:center;justify-content:center;padding:0 14px;background:#ebd58a;color:#1f1d18;text-decoration:none;font-size:13px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;cursor:pointer}
.controls .ghost{background:#262a31;color:#f7f4ee;border:1px solid #3c4450}
.controls select,.controls input{padding:0 12px;background:#262a31;color:#fff;border:1px solid #3c4450;font-family:'Share Tech Mono',monospace}
.sheet-wrap{overflow:auto;padding:8px 0}
.sheet{width:1120px;margin:0 auto;background:var(--paper);color:var(--ink);padding:30px 34px 36px;box-shadow:0 26px 70px rgba(0,0,0,.45);border:10px solid #f8f2e7;position:relative}
.sheet::before{content:'';position:absolute;inset:14px;border:1px solid rgba(38,70,83,.18);pointer-events:none}
.sheet-head{display:flex;justify-content:space-between;gap:20px;align-items:flex-end;border-bottom:3px solid var(--accent);padding-bottom:16px;margin-bottom:18px}
.sheet-title{font-family:'IM Fell English',serif;font-size:44px;line-height:1.05;letter-spacing:.01em}
.sheet-sub{font-family:'Share Tech Mono',monospace;font-size:12px;letter-spacing:.16em;text-transform:uppercase;color:var(--accent-2)}
.sheet-meta{text-align:right}.sheet-meta .group{font-size:22px;font-weight:700}.sheet-meta .date{font-size:14px;color:var(--ink-soft)}
.legend{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px}
.legend span{padding:6px 10px;border:1px solid var(--line);font-family:'Share Tech Mono',monospace;font-size:11px;letter-spacing:.08em;text-transform:uppercase}
.table{display:grid;gap:12px}
.row{display:grid;grid-template-columns:170px 1fr;gap:14px;align-items:stretch}
.channel{border-top:2px solid var(--accent-2);padding-top:8px}
.channel-top{display:flex;gap:10px;align-items:center}
.channel img{width:42px;height:42px;object-fit:contain;background:#fff;border:1px solid var(--line);padding:4px}
.channel-name{font-size:22px;font-weight:700;line-height:1.05}
.timeline{display:grid;grid-template-columns:repeat(24,minmax(0,1fr));border-top:2px solid var(--accent-2);position:relative;min-height:112px}
.hour{border-left:1px dashed var(--line);padding:8px 7px 10px 10px}
.hour:first-child{border-left:none}
.hour-label{font-family:'Share Tech Mono',monospace;font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--ink-soft);margin-bottom:8px}
.item{display:block;padding:8px 8px 9px;background:rgba(170,66,49,.08);border-left:3px solid var(--accent);margin-bottom:7px}
.item.tight{padding:6px 7px}
.item-title{font-size:14px;font-weight:700;line-height:1.1}
.item-meta{font-family:'Share Tech Mono',monospace;font-size:10px;letter-spacing:.03em;color:var(--ink-soft);margin-top:4px}
.item-sub{font-size:11px;color:var(--ink-soft);margin-top:3px;line-height:1.2}
.empty{color:var(--ink-soft);font-style:italic;font-size:12px;padding-top:24px}
.note{margin-top:16px;font-size:12px;color:var(--ink-soft);text-align:right}
@media print{body{background:#fff}.page{padding:0}.toolbar{display:none}.sheet{box-shadow:none;border:none;width:auto;margin:0}.sheet-wrap{overflow:visible}}
@media (max-width:1200px){.sheet{transform-origin:top center}}
</style>
</head>
<body>
<div class="page">
<div class="toolbar">
<div class="heading">
<h1>Export 24h</h1>
<p>Version “programme télé” pensée pour être imprimée proprement en PDF, ou exportée en image pour l’envoyer facilement à quelqu’un.</p>
</div>
<div class="controls">
<form method="GET" style="display:flex;gap:10px;flex-wrap:wrap">
<select name="source">
<?php foreach ($sources as $i => $src): ?>
<option value="<?= $i ?>"<?= $i === $source_index ? ' selected' : '' ?>><?= htmlspecialchars($src['name']) ?></option>
<?php endforeach; ?>
</select>
<input type="date" name="day" value="<?= htmlspecialchars($target_day) ?>">
<button type="submit" class="ghost">Refresh</button>
</form>
<button type="button" onclick="window.print()">PDF / Print</button>
<button type="button" class="ghost" onclick="downloadImage()">Image</button>
<a href="/health.php" class="ghost">Health</a>
<a href="/index.php" class="ghost">Guide</a>
</div>
</div>
<div class="sheet-wrap">
<div class="sheet" id="exportSheet">
<div class="sheet-head">
<div>
<div class="sheet-sub">TV Guide · 24 hours · Printable edition</div>
<div class="sheet-title">Le programme télé de la journée</div>
</div>
<div class="sheet-meta">
<div class="group"><?= htmlspecialchars($config['group_name'] ?? 'GridTV') ?></div>
<div class="date"><?= htmlspecialchars($day_label) ?> · <?= htmlspecialchars($source['name'] ?? 'Source') ?></div>
</div>
</div>
<div class="legend">
<span>24h view</span>
<span><?= count($print_channels) ?> channel(s)</span>
<span>Generated from XMLTV</span>
</div>
<?php if (!$fetch['ok'] || $parsed['error']): ?>
<div class="empty">Impossible de générer la feuille: <?= htmlspecialchars($parsed['error'] ?: ($fetch['error'] ?? 'Unknown error')) ?></div>
<?php elseif (!$print_channels): ?>
<div class="empty">Aucun programme trouvé pour cette journée.</div>
<?php else: ?>
<div class="table">
<?php foreach ($print_channels as $channel_id => $channel): ?>
<div class="row">
<div class="channel">
<div class="channel-top">
<?php if ($channel['icon']): ?><img src="<?= htmlspecialchars($channel['icon']) ?>" alt=""><?php endif; ?>
<div class="channel-name"><?= htmlspecialchars($channel['name']) ?></div>
</div>
</div>
<div class="timeline">
<?php
for ($hour = 0; $hour < 24; $hour++):
$hour_start = new DateTimeImmutable($target_day . sprintf(' %02d:00:00', $hour));
$hour_end = $hour_start->modify('+1 hour');
$items = [];
foreach ($parsed['programmes'][$channel_id] as $programme) {
if ($programme['stop'] <= $hour_start || $programme['start'] >= $hour_end) continue;
$items[] = $programme;
}
?>
<div class="hour">
<div class="hour-label"><?= sprintf('%02dh', $hour) ?></div>
<?php if (!$items): ?>
<div class="empty">—</div>
<?php else: ?>
<?php foreach ($items as $programme): ?>
<?php
$meta = $programme['start']->format('H:i') . ' - ' . $programme['stop']->format('H:i');
if ($programme['rating']) $meta .= ' · ' . $programme['rating'];
$cats = $programme['categories'] ? implode(' · ', $programme['categories']) : '';
?>
<div class="item<?= strlen($programme['title']) > 28 ? ' tight' : '' ?>">
<div class="item-title"><?= htmlspecialchars($programme['title']) ?></div>
<?php if ($programme['subtitle']): ?><div class="item-sub"><?= htmlspecialchars($programme['subtitle']) ?></div><?php endif; ?>
<div class="item-meta"><?= htmlspecialchars($meta) ?></div>
<?php if ($cats): ?><div class="item-sub"><?= htmlspecialchars($cats) ?></div><?php endif; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<?php endfor; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="note">Astuce: “PDF / Print” donne un export A4/PDF propre. “Image” fabrique un PNG de la feuille affichée.</div>
<?php endif; ?>
</div>
</div>
</div>
<script>
async function downloadImage() {
const sheet = document.getElementById('exportSheet');
if (!sheet || typeof html2canvas !== 'function') return;
const canvas = await html2canvas(sheet, {backgroundColor: '#f4ecda', scale: 2, useCORS: true});
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = 'gridtv-24h-<?= htmlspecialchars($target_day) ?>.png';
link.click();
}
</script>
</body>
</html>
+274
View File
@@ -0,0 +1,274 @@
<?php
require_once __DIR__ . '/src/lib/admin.php';
$config = gridtv_load_config();
gridtv_require_admin($config, 'Health');
[$locale, $L] = gridtv_load_locale($config);
function health_status_class(bool $ok): string {
return $ok ? 'ok' : 'ko';
}
function health_status_label(bool $ok): string {
return $ok ? 'OK' : 'Issue';
}
function health_parse_xmltv(string $xml): array {
if ($xml === '') {
return ['ok' => false, 'error' => 'Empty response'];
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$loaded = $dom->loadXML($xml, LIBXML_NOERROR | LIBXML_NOWARNING);
$errors = array_map(static fn($e) => trim($e->message), libxml_get_errors());
libxml_clear_errors();
if (!$loaded) {
return ['ok' => false, 'error' => $errors[0] ?? 'Invalid XML'];
}
$xp = new DOMXPath($dom);
$programmes = $xp->query('/tv/programme');
$channels = $xp->query('/tv/channel');
$categories = $xp->query('/tv/programme/category');
$subtitles = $xp->query('/tv/programme/sub-title');
$ratings = $xp->query('/tv/programme/rating');
$dates = $xp->query('/tv/programme/date');
$first = null;
$last = null;
foreach ($programmes as $programme) {
$start = $programme->getAttribute('start');
$stop = $programme->getAttribute('stop');
if ($start !== '' && ($first === null || strcmp($start, $first) < 0)) $first = $start;
if ($stop !== '' && ($last === null || strcmp($stop, $last) > 0)) $last = $stop;
}
return [
'ok' => true,
'channels' => $channels->length,
'programmes' => $programmes->length,
'categories' => $categories->length,
'subtitles' => $subtitles->length,
'ratings' => $ratings->length,
'dates' => $dates->length,
'first_start' => $first,
'last_stop' => $last,
];
}
function health_parse_m3u(string $body): array {
$lines = preg_split('/\r\n|\r|\n/', $body);
$streams = 0;
$extinf = 0;
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') continue;
if (stripos($line, '#EXTINF') === 0) {
$extinf++;
continue;
}
if ($line[0] !== '#') $streams++;
}
return ['streams' => $streams, 'extinf' => $extinf];
}
function health_format_xmltv_stamp(?string $stamp): string {
if (!$stamp) return '—';
$dt = DateTime::createFromFormat('YmdHis O', $stamp);
if (!$dt) return $stamp;
return $dt->format('d/m/Y H:i');
}
$config_path = gridtv_config_path();
$config_exists = file_exists($config_path);
$config_writable = $config_exists ? is_writable($config_path) : is_writable(dirname($config_path));
$sources = array_values($config['epg_sources'] ?? []);
$checks = [
[
'label' => 'Config file',
'ok' => $config_exists,
'detail' => $config_exists ? basename($config_path) . ' found' : 'Missing config.json',
],
[
'label' => 'Config writable',
'ok' => $config_writable,
'detail' => $config_writable ? 'Writable by PHP' : 'Not writable by PHP',
],
[
'label' => 'PHP version',
'ok' => version_compare(PHP_VERSION, '8.0.0', '>='),
'detail' => 'PHP ' . PHP_VERSION,
],
[
'label' => 'php-curl',
'ok' => extension_loaded('curl'),
'detail' => extension_loaded('curl') ? 'Extension loaded' : 'Missing php-curl',
],
[
'label' => 'Configured sources',
'ok' => count($sources) > 0,
'detail' => count($sources) . ' source(s) in config',
],
];
$source_reports = [];
foreach ($sources as $index => $source) {
$epg_url = trim((string) ($source['epg_url'] ?? ''));
$m3u_url = trim((string) ($source['m3u_url'] ?? ''));
$epg_fetch = $epg_url !== '' ? gridtv_fetch_url($epg_url, 25) : ['ok' => false, 'status' => 0, 'error' => 'Missing URL', 'body' => '', 'content_type' => '', 'final_url' => '', 'time_total' => 0.0];
$epg_stats = $epg_fetch['ok'] ? health_parse_xmltv($epg_fetch['body']) : ['ok' => false, 'error' => $epg_fetch['error'] ?: 'HTTP ' . $epg_fetch['status']];
$m3u_fetch = null;
$m3u_stats = null;
if ($m3u_url !== '') {
$m3u_fetch = gridtv_fetch_url($m3u_url, 20);
$m3u_stats = $m3u_fetch['ok'] ? health_parse_m3u($m3u_fetch['body']) : null;
}
$source_reports[] = [
'name' => $source['name'] ?: 'Source ' . ($index + 1),
'epg_url' => $epg_url,
'm3u_url' => $m3u_url,
'epg_fetch' => $epg_fetch,
'epg_stats' => $epg_stats,
'm3u_fetch' => $m3u_fetch,
'm3u_stats' => $m3u_stats,
];
}
?><!DOCTYPE html>
<html lang="<?= htmlspecialchars($locale) ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GridTV — Health</title>
<link rel="stylesheet" href="/assets/fonts/fonts.css">
<style>
:root{--bg:#0b0d10;--surface:#13161b;--surface2:#1a1f27;--border:#2a3240;--accent:#e8c842;--accent2:#5ec0ff;--text:#eaf0f6;--muted:#8f9aac;--ok:#4fd18b;--warn:#ff6767}
*{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at top left,#1b2330 0,#0b0d10 48%);color:var(--text);font-family:'Barlow Condensed',sans-serif}
.page{max-width:1200px;margin:0 auto;padding:32px 20px 56px}
.hero{display:flex;justify-content:space-between;gap:18px;align-items:flex-end;margin-bottom:24px}
.logo{font-family:'Share Tech Mono',monospace;font-size:26px;letter-spacing:.12em;color:var(--accent);text-transform:uppercase}
.subtitle{color:var(--muted);font-size:14px;max-width:700px;line-height:1.5}
.actions{display:flex;gap:10px;flex-wrap:wrap}
.btn{display:inline-flex;align-items:center;gap:8px;padding:11px 14px;border:1px solid var(--border);background:var(--surface);color:var(--text);text-decoration:none;font-size:13px;letter-spacing:.08em;text-transform:uppercase}
.btn-primary{background:var(--accent);color:#000;border-color:var(--accent)}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px;margin-bottom:22px}
.card,.source{background:rgba(19,22,27,.95);border:1px solid var(--border)}
.card{padding:16px}
.eyebrow{font-family:'Share Tech Mono',monospace;font-size:11px;color:var(--accent2);letter-spacing:.12em;text-transform:uppercase;margin-bottom:10px}
.value{font-size:28px;font-weight:700}
.small{font-size:13px;color:var(--muted)}
.checks{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin-bottom:24px}
.check{padding:14px;background:var(--surface);border:1px solid var(--border)}
.status{display:inline-flex;align-items:center;gap:8px;font-family:'Share Tech Mono',monospace;font-size:11px;letter-spacing:.1em;text-transform:uppercase}
.status::before{content:'';width:10px;height:10px;border-radius:50%}
.status.ok{color:var(--ok)}.status.ok::before{background:var(--ok)}
.status.ko{color:var(--warn)}.status.ko::before{background:var(--warn)}
.source-list{display:grid;gap:18px}
.source{padding:20px}
.source-head{display:flex;justify-content:space-between;gap:14px;align-items:flex-start;margin-bottom:16px}
.source-title{font-size:24px;font-weight:700}
.pill{display:inline-block;padding:6px 10px;font-family:'Share Tech Mono',monospace;font-size:11px;letter-spacing:.1em;text-transform:uppercase;background:var(--surface2);border:1px solid var(--border);color:var(--accent2)}
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:14px}
.panel{padding:16px;background:var(--surface2);border:1px solid var(--border)}
.panel h3{margin:0 0 10px;font-size:16px;letter-spacing:.06em;text-transform:uppercase}
.kv{display:grid;grid-template-columns:160px 1fr;gap:8px;font-size:14px;line-height:1.45}
.kv div:nth-child(odd){color:var(--muted)}
.mono{font-family:'Share Tech Mono',monospace;font-size:12px;word-break:break-all}
@media (max-width:700px){.hero{flex-direction:column;align-items:flex-start}.kv{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="page">
<div class="hero">
<div>
<div class="logo">GridTV / Health</div>
<div class="subtitle">Page de diagnostic admin. Elle vérifie l’état de l’instance, les flux XMLTV/M3U configurés et les signaux qui aident à comprendre vite ce qui coince.</div>
</div>
<div class="actions">
<a class="btn btn-primary" href="/export.php">Export 24h</a>
<a class="btn" href="/setup.php">Setup</a>
<a class="btn" href="/index.php">Guide</a>
</div>
</div>
<div class="grid">
<div class="card"><div class="eyebrow">Group</div><div class="value"><?= htmlspecialchars($config['group_name'] ?? 'GridTV') ?></div><div class="small">Configured TV group name</div></div>
<div class="card"><div class="eyebrow">Sources</div><div class="value"><?= count($sources) ?></div><div class="small">Configured XMLTV sources</div></div>
<div class="card"><div class="eyebrow">Locale</div><div class="value"><?= strtoupper(htmlspecialchars($locale)) ?></div><div class="small">Detected UI locale</div></div>
<div class="card"><div class="eyebrow">Config Size</div><div class="value"><?= $config_exists ? htmlspecialchars(gridtv_format_bytes(filesize($config_path))) : '0 B' ?></div><div class="small"><?= htmlspecialchars($config_path) ?></div></div>
</div>
<div class="checks">
<?php foreach ($checks as $check): ?>
<div class="check">
<div class="status <?= health_status_class($check['ok']) ?>"><?= health_status_label($check['ok']) ?></div>
<div style="font-size:18px;font-weight:700;margin:8px 0 6px"><?= htmlspecialchars($check['label']) ?></div>
<div class="small"><?= htmlspecialchars($check['detail']) ?></div>
</div>
<?php endforeach; ?>
</div>
<div class="source-list">
<?php foreach ($source_reports as $report): ?>
<section class="source">
<div class="source-head">
<div>
<div class="source-title"><?= htmlspecialchars($report['name']) ?></div>
<div class="small">EPG host: <?= htmlspecialchars(gridtv_extract_host($report['epg_url'])) ?: '—' ?><?= $report['m3u_url'] ? ' · M3U host: ' . htmlspecialchars(gridtv_extract_host($report['m3u_url'])) : '' ?></div>
</div>
<span class="pill"><?= htmlspecialchars($report['epg_fetch']['ok'] && $report['epg_stats']['ok'] ? 'Healthy XMLTV' : 'Check source') ?></span>
</div>
<div class="split">
<div class="panel">
<h3>XMLTV</h3>
<div class="kv">
<div>Status</div><div><span class="status <?= health_status_class($report['epg_fetch']['ok'] && $report['epg_stats']['ok']) ?>"><?= health_status_label($report['epg_fetch']['ok'] && $report['epg_stats']['ok']) ?></span></div>
<div>URL</div><div class="mono"><?= htmlspecialchars($report['epg_url']) ?></div>
<div>HTTP</div><div><?= htmlspecialchars((string) $report['epg_fetch']['status']) ?><?= $report['epg_fetch']['error'] ? ' · ' . htmlspecialchars($report['epg_fetch']['error']) : '' ?></div>
<div>Response time</div><div><?= htmlspecialchars(number_format($report['epg_fetch']['time_total'], 2)) ?> s</div>
<?php if ($report['epg_fetch']['ok'] && $report['epg_stats']['ok']): ?>
<div>Channels</div><div><?= htmlspecialchars((string) $report['epg_stats']['channels']) ?></div>
<div>Programmes</div><div><?= htmlspecialchars((string) $report['epg_stats']['programmes']) ?></div>
<div>Sub-titles</div><div><?= htmlspecialchars((string) $report['epg_stats']['subtitles']) ?></div>
<div>Ratings</div><div><?= htmlspecialchars((string) $report['epg_stats']['ratings']) ?></div>
<div>Categories</div><div><?= htmlspecialchars((string) $report['epg_stats']['categories']) ?></div>
<div>Date tags</div><div><?= htmlspecialchars((string) $report['epg_stats']['dates']) ?></div>
<div>Window</div><div><?= htmlspecialchars(health_format_xmltv_stamp($report['epg_stats']['first_start'])) ?> → <?= htmlspecialchars(health_format_xmltv_stamp($report['epg_stats']['last_stop'])) ?></div>
<div>Content-Type</div><div><?= htmlspecialchars($report['epg_fetch']['content_type'] ?: '—') ?></div>
<?php else: ?>
<div>Parse</div><div><?= htmlspecialchars($report['epg_stats']['error'] ?? 'Unable to read XMLTV') ?></div>
<?php endif; ?>
</div>
</div>
<div class="panel">
<h3>M3U</h3>
<?php if (!$report['m3u_url']): ?>
<div class="small">No M3U URL configured for this source.</div>
<?php else: ?>
<div class="kv">
<div>Status</div><div><span class="status <?= health_status_class((bool) ($report['m3u_fetch']['ok'] ?? false)) ?>"><?= health_status_label((bool) ($report['m3u_fetch']['ok'] ?? false)) ?></span></div>
<div>URL</div><div class="mono"><?= htmlspecialchars($report['m3u_url']) ?></div>
<div>HTTP</div><div><?= htmlspecialchars((string) ($report['m3u_fetch']['status'] ?? 0)) ?><?= !empty($report['m3u_fetch']['error']) ? ' · ' . htmlspecialchars($report['m3u_fetch']['error']) : '' ?></div>
<div>Response time</div><div><?= htmlspecialchars(number_format((float) ($report['m3u_fetch']['time_total'] ?? 0), 2)) ?> s</div>
<?php if (!empty($report['m3u_fetch']['ok']) && $report['m3u_stats']): ?>
<div>Streams</div><div><?= htmlspecialchars((string) $report['m3u_stats']['streams']) ?></div>
<div>#EXTINF</div><div><?= htmlspecialchars((string) $report['m3u_stats']['extinf']) ?></div>
<div>Content-Type</div><div><?= htmlspecialchars($report['m3u_fetch']['content_type'] ?: '—') ?></div>
<?php else: ?>
<div>Parse</div><div>Unable to load playlist.</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
</section>
<?php endforeach; ?>
</div>
</div>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
<?php
require_once __DIR__ . '/common.php';
function gridtv_require_admin(array $config, string $page_title = 'Admin'): array {
session_start();
$admin_key = (string) ($config['admin_key'] ?? '');
$session_key = $_SESSION['gridtv_admin_unlocked'] ?? '';
$error = '';
if ($admin_key !== '' && hash_equals($admin_key, (string) $session_key)) {
return ['unlocked' => true, 'error' => ''];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_key_input'])) {
$submitted = trim((string) ($_POST['admin_key_input'] ?? ''));
if ($admin_key !== '' && hash_equals($admin_key, $submitted)) {
$_SESSION['gridtv_admin_unlocked'] = $admin_key;
header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
exit;
}
$error = 'Invalid admin key.';
}
http_response_code(401);
echo '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>GridTV — ' . htmlspecialchars($page_title) . '</title><link rel="stylesheet" href="/assets/fonts/fonts.css"><style>:root{--bg:#0a0b0d;--surface:#111318;--surface2:#181b22;--border:#232733;--border-bright:#2e3444;--accent:#e8c842;--text:#c8cdd8;--text-dim:#5a6070;--text-bright:#eef0f5;--error:#ff4444;}*{box-sizing:border-box}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:var(--bg);color:var(--text);font-family:"Barlow Condensed",sans-serif;padding:24px}.card{width:100%;max-width:460px;background:var(--surface);border:1px solid var(--border-bright);padding:34px}.logo{font-family:"Share Tech Mono",monospace;font-size:22px;color:var(--accent);letter-spacing:.1em;text-transform:uppercase;margin-bottom:8px}.sub{font-size:13px;color:var(--text-dim);line-height:1.5;margin-bottom:24px}.error{background:rgba(255,68,68,.08);border-left:3px solid var(--error);padding:12px 14px;color:var(--error);font-size:13px;margin-bottom:18px}label{display:block;font-family:"Share Tech Mono",monospace;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:var(--text-dim);margin-bottom:8px}input{width:100%;background:var(--surface2);border:1px solid var(--border-bright);color:var(--text-bright);font-family:"Share Tech Mono",monospace;font-size:13px;padding:11px 12px;margin-bottom:16px}button{width:100%;background:var(--accent);color:#000;border:none;font-family:"Barlow Condensed",sans-serif;font-size:14px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;padding:12px;cursor:pointer}.links{margin-top:16px;font-size:12px;color:var(--text-dim)}.links a{color:var(--accent);text-decoration:none}</style></head><body><div class="card"><div class="logo">GridTV</div><div class="sub">Enter your admin key to access the ' . htmlspecialchars($page_title) . ' page.</div>' . ($error ? '<div class="error">' . htmlspecialchars($error) . '</div>' : '') . '<form method="POST"><label for="admin_key_input">Admin key</label><input id="admin_key_input" type="password" name="admin_key_input" autocomplete="off" autofocus><button type="submit">Unlock</button></form><div class="links"><a href="/setup.php">Open setup</a></div></div></body></html>';
exit;
}
+127
View File
@@ -0,0 +1,127 @@
<?php
function gridtv_config_path(): string {
return dirname(__DIR__, 2) . '/config.json';
}
function gridtv_load_config(): array {
$config_path = gridtv_config_path();
if (!file_exists($config_path)) {
header('Location: /setup.php');
exit;
}
$config = json_decode(file_get_contents($config_path), true);
if (!is_array($config)) {
http_response_code(500);
die('<h2>GridTV — Configuration error</h2><p><code>config.json</code> is invalid or corrupted.<br>Please delete it and re-run <a href="/setup.php">setup</a>, or fix it manually via SSH.</p>');
}
if (isset($config['epg_url']) && !isset($config['epg_sources'])) {
$config['epg_sources'] = [[
'name' => 'Main',
'epg_url' => $config['epg_url'],
'm3u_url' => $config['m3u_url'] ?? '',
]];
$config['allow_personal_epg'] = false;
unset($config['epg_url'], $config['m3u_url']);
file_put_contents($config_path, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
return $config;
}
function gridtv_load_locale(array $config = []): array {
$locale_files = glob(dirname(__DIR__, 2) . '/locales/*.json') ?: [];
$supported_locales = array_map(fn($f) => basename($f, '.json'), $locale_files);
$locale = 'en';
$accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? 'en';
foreach (explode(',', $accept) as $lang) {
$code = strtolower(substr(trim($lang), 0, 2));
if (in_array($code, $supported_locales, true)) {
$locale = $code;
break;
}
}
$locale_path = dirname(__DIR__, 2) . "/locales/{$locale}.json";
$strings = is_file($locale_path) ? json_decode(file_get_contents($locale_path), true) : null;
if (!is_array($strings)) {
$fallback_path = dirname(__DIR__, 2) . '/locales/en.json';
$strings = is_file($fallback_path) ? (json_decode(file_get_contents($fallback_path), true) ?? []) : [];
$locale = 'en';
}
return [$locale, $strings];
}
function gridtv_fetch_url(string $url, int $timeout = 20, bool $head_only = false): array {
if (!function_exists('curl_init')) {
return [
'ok' => false,
'status' => 0,
'error' => 'php-curl extension is not installed.',
'body' => '',
'headers' => [],
'content_type' => '',
'final_url' => $url,
'time_total' => 0.0,
];
}
$headers = [];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'] ?? 'GridTV/health',
CURLOPT_HEADERFUNCTION => static function ($ch, $line) use (&$headers) {
$trimmed = trim($line);
if ($trimmed !== '' && strpos($trimmed, ':') !== false) {
[$name, $value] = explode(':', $trimmed, 2);
$headers[strtolower(trim($name))] = trim($value);
}
return strlen($line);
},
CURLOPT_HTTPHEADER => ['Accept: */*'],
CURLOPT_NOBODY => $head_only,
]);
$body = curl_exec($ch);
$error = curl_error($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$final_url = (string) curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$time_total = (float) curl_getinfo($ch, CURLINFO_TOTAL_TIME);
curl_close($ch);
return [
'ok' => $error === '' && $status >= 200 && $status < 400,
'status' => $status,
'error' => $error,
'body' => is_string($body) ? $body : '',
'headers' => $headers,
'content_type' => $content_type,
'final_url' => $final_url ?: $url,
'time_total' => $time_total,
];
}
function gridtv_format_bytes(int $bytes): string {
$units = ['B', 'KB', 'MB', 'GB'];
$size = (float) $bytes;
$unit = 0;
while ($size >= 1024 && $unit < count($units) - 1) {
$size /= 1024;
$unit++;
}
return number_format($size, $size >= 10 || $unit === 0 ? 0 : 1) . ' ' . $units[$unit];
}
function gridtv_extract_host(string $url): string {
return strtolower(parse_url($url, PHP_URL_HOST) ?? '');
}