Compare commits

..
11 Commits
Author SHA1 Message Date
Meghdad a803f8c745 feat: add project-level env configuration for collector 2026-07-28 04:22:51 +03:30
Meghdad f0c40c120d feat: switch captcha collector to TCI internet panel 2026-07-28 04:16:15 +03:30
Meghdad 64b481bdb0 feat: add panel-validated CAPTCHA dataset collector
- validate labels through real panel login attempts
  - append confirmed samples safely to the OCR dataset
  - add dependency-free mobile-friendly collector UI
  - support Persian and Arabic digit normalization
  - fix PHP 8.5 captcha image corruption
  - add integration tests and documentation
2026-07-28 03:52:28 +03:30
Meghdad d5e974957e update panel page 2026-07-28 03:50:45 +03:30
Meghdad 49de12a5bb update .gitignore 2026-07-28 02:58:03 +03:30
Meghdad 85b91f2226 rename panel 2026-07-28 02:24:46 +03:30
Meghdad ffca10abf8 add test capcha panel 2026-07-28 02:22:25 +03:30
Meghdad 9bdea89278 feat: optimize mobile OCR verification workflow 2026-07-26 20:03:38 +03:30
Meghdad 91e8e00028 add favicon for web page 2026-07-26 00:18:52 +03:30
Meghdad fa90a91bb7 Merge remote-tracking branch 'origin/main' 2026-07-25 23:57:07 +03:30
Meghdad 57671efc7d init 2026-07-25 23:56:30 +03:30
10 changed files with 2797 additions and 1497 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
# Copy this file to .env and replace the credentials.
PANEL_LOGIN_USERNAME="your-tci-username"
PANEL_LOGIN_PASSWORD="your-tci-password"
# Optional collector settings:
PANEL_BASE_URL="https://internet.tci.ir"
PANEL_REQUEST_TIMEOUT="10"
# Use an absolute path on PHP-FPM deployments. Leave unset for ./dataset.
# OCR_DATASET_DIR="/srv/tci-ocr/dataset"
+3
View File
@@ -1,5 +1,6 @@
.idea/
.venv/
.env
__pycache__/
*.py[cod]
.pytest_cache/
@@ -8,3 +9,5 @@ build/
*.egg-info/
captcha.jpg
dataset/
dataset-*/
screenshots/
+47 -45
View File
@@ -101,65 +101,71 @@ The verifier builds a complete temporary CSV and atomically replaces the origina
when you quit, so the CSV cannot be left half-written. If it is interrupted while
copying or displaying rather than at the prompt, the original CSV remains unchanged.
## 5. Verify labels in a web browser
## 5. Collect panel-validated captchas
The PHP verifier provides the same sequential labeling workflow without Kitty,
Python packages, Composer, or a framework. It requires PHP 8.1 or newer with
PDO SQLite and Fileinfo enabled.
The dependency-free PHP collector downloads a fresh captcha from the customer
panel and validates your transcription with a real login attempt. An image is
added to the dataset only when the panel responds with its successful login
redirect. Rejected, expired, or skipped captchas are discarded.
Start it locally from the repository root:
The collector requires PHP 8.1 or newer with sessions, OpenSSL, and the standard
HTTP stream wrapper enabled. Start it from the repository root:
```bash
php -S 127.0.0.1:8080 -t web
```
Then open `http://127.0.0.1:8080`. On the first visit, click **Initialize
verifier**. The browser incrementally imports `dataset/labels.csv` into
`dataset/verification.sqlite`; progress is resumable if the page or server is
stopped.
Open `http://127.0.0.1:8080`, enter the number, and press Enter. ASCII, Persian,
and Arabic digits are accepted and normalized to ASCII. The next challenge is
loaded without a page refresh so the numeric keyboard stays open on phones.
Each accepted label is immediately committed to SQLite. ASCII, Persian, and
Arabic digits are accepted and normalized to ASCII. Enter saves and advances;
an empty Enter or **Skip for now** leaves the row unverified and advances. Recent
labels can be opened and corrected without moving the main queue.
The page deliberately does not rewrite the large CSV after every answer. The
header shows how many rows have not yet been copied back. Click **Sync
labels.csv** before training, copying the dataset, or using another Python tool.
Sync writes a complete neighboring temporary file and atomically replaces
`labels.csv`; a failed write leaves the existing CSV unchanged.
Do not run `verify_labels.py`, the downloader, or another process that changes
`labels.csv` while the web verifier is active. The page detects an external CSV
change and stops rather than overwriting it. To move the dataset to another
machine, sync first and copy the dataset normally; the destination can rebuild
its SQLite state from the synced CSV.
### Use another dataset directory
The default dataset is the repository's `dataset/` directory. Set
`OCR_DATASET_DIR` to use another location:
By default the collector connects to the TCI customer panel at
`https://internet.tci.ir/panel/` and appends to `dataset/labels.csv`. Create a
project-level `.env` file for your TCI credentials:
```bash
OCR_DATASET_DIR=/data/persian-ocr \
php -S 127.0.0.1:8080 -t web
cp .env.example .env
```
`OCR_STATE_PATH` can optionally place `verification.sqlite` elsewhere. The PHP
process must be able to read the CSV and images and write the SQLite database,
its lock/WAL files, and temporary CSV files. Grant the PHP-FPM user ownership or
a targeted ACL; do not make the directory world-writable.
Edit `.env` and replace `your-tci-username` and `your-tci-password`. Quoted
values may contain spaces, `#`, or `$`. The `.env` file is ignored by Git.
Existing PHP-FPM, Nginx FastCGI, or process environment settings take precedence
over values in `.env`.
The supported settings are:
- `PANEL_BASE_URL` — panel origin; defaults to `https://internet.tci.ir`.
- `PANEL_LOGIN_USERNAME` — login username; defaults to `username`.
- `PANEL_LOGIN_PASSWORD` — plaintext login password; defaults to `password`.
- `PANEL_REQUEST_TIMEOUT` — upstream timeout in seconds; defaults to `10`.
- `OCR_DATASET_DIR` — output dataset; defaults to the repository's `dataset/`.
Validated images use content-addressed paths below `images/panel/`. The collector
appends rows with `batch_id=panel` and `verified=1`, while preserving all existing
CSV rows. Writes are locked, flushed, and exact-image duplicates are idempotent.
If the dataset directory or CSV has been removed, it is recreated automatically.
Legacy `verification.sqlite` files are ignored.
Keep the collector private: it has no user authentication and holds the panel
credentials. The PHP user needs read permission for `.env` and write permission
for the dataset directory. On a typical Debian/Ubuntu PHP-FPM server, protect the
file with:
```bash
sudo chown root:www-data .env
sudo chmod 640 .env
```
Use your PHP-FPM worker group instead of `www-data` when it differs. Keep the
Nginx document root set to the repository's `web/` directory so `.env` and
`dataset/` cannot be downloaded.
### Minimal Nginx configuration
Use `web/` as the public document root so the CSV, SQLite state, images, and
Python source files are not directly downloadable. The page safely streams the
selected image itself.
```nginx
server {
listen 80;
server_name verifier.example.internal;
server_name collector.example.internal;
root /srv/tci-ocr/web;
index index.php;
@@ -179,7 +185,3 @@ server {
}
}
```
Adjust the PHP-FPM socket and paths for the server. The application intentionally
contains no authentication; add Nginx basic authentication to the `server` or
`location /` block, or expose it only on a private network.
+775
View File
@@ -0,0 +1,775 @@
<?php
declare(strict_types=1);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);
const DEFAULT_TRAFFIC_GB = '12.5';
const DEFAULT_PLAN_NAME = 'سرویس طلایی';
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Lax');
ini_set(
'session.cookie_secure',
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? '1' : '0'
);
session_name('CUSTOMER_PORTAL_SESSION');
session_start();
sendSecurityHeaders();
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
if ($method === 'GET' && $path === '/') {
header('Location: /panel', true, 302);
exit;
}
if ($method === 'GET' && $path === '/captcha') {
renderCaptcha();
}
if ($method === 'POST' && ($path === '/login' || $path === '/panel')) {
handleLogin();
}
if ($method === 'POST' && $path === '/logout') {
logout();
}
if ($method === 'GET' && $path === '/panel') {
if (($_SESSION['authenticated'] ?? false) === true) {
renderPanel();
}
renderLogin();
}
if (in_array($path, ['/panel', '/login', '/logout', '/captcha'], true)) {
header('Allow: GET, POST');
renderErrorPage(405, 'روش درخواست پشتیبانی نمی‌شود.');
}
renderErrorPage(404, 'صفحه مورد نظر پیدا نشد.');
function sendSecurityHeaders(): void
{
header_remove('X-Powered-By');
header('Cache-Control: no-store, max-age=0');
header('Pragma: no-cache');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header("Content-Security-Policy: default-src 'self'; img-src 'self'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'");
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
}
function envValue(string $key, string $default = ''): string
{
$value = getenv($key);
return $value === false || $value === '' ? $default : $value;
}
function scalarPostValue(string $key, int $maxLength): ?string
{
if (!array_key_exists($key, $_POST) || !is_string($_POST[$key])) {
return null;
}
$value = $_POST[$key];
return strlen($value) <= $maxLength ? $value : null;
}
function csrfToken(): string
{
if (!isset($_SESSION['csrf_token']) || !is_string($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
function csrfIsValid(?string $token): bool
{
$storedToken = $_SESSION['csrf_token'] ?? null;
return is_string($token)
&& is_string($storedToken)
&& hash_equals($storedToken, $token);
}
function handleLogin(): never
{
$username = scalarPostValue('username', 128);
$password = scalarPostValue('password', 256);
$captcha = scalarPostValue('captcha', 16);
$csrf = scalarPostValue('csrf_token', 64);
if ($username === null || $password === null || $captcha === null || !csrfIsValid($csrf)) {
renderLogin('درخواست ورود معتبر نیست. لطفاً صفحه را تازه‌سازی و دوباره تلاش کنید.', 400, $username ?? '');
}
$captchaHash = $_SESSION['captcha_hash'] ?? null;
$captchaIssuedAt = $_SESSION['captcha_issued_at'] ?? 0;
unset($_SESSION['captcha_hash'], $_SESSION['captcha_issued_at']);
$captchaIsValid = is_string($captchaHash)
&& is_int($captchaIssuedAt)
&& (time() - $captchaIssuedAt) <= 300
&& password_verify(strtoupper(trim($captcha)), $captchaHash);
if (!$captchaIsValid) {
renderLogin('کد امنیتی اشتباه است یا اعتبار آن به پایان رسیده است.', 401, $username);
}
$expectedUsername = envValue('PANEL_USERNAME', 'username');
$expectedPasswordHash = envValue('PANEL_PASSWORD_HASH', password_hash("password", PASSWORD_DEFAULT));
if ($expectedUsername === '' || $expectedPasswordHash === '') {
error_log('Customer portal credentials are not configured.');
renderLogin('سرویس ورود موقتاً در دسترس نیست. لطفاً کمی بعد تلاش کنید.', 503, $username);
}
$usernameIsValid = hash_equals($expectedUsername, trim($username));
$passwordIsValid = password_verify($password, $expectedPasswordHash);
$credentialsAreValid = $usernameIsValid && $passwordIsValid;
if (!$credentialsAreValid) {
renderLogin('نام کاربری یا رمز عبور صحیح نیست.', 401, $username);
}
session_regenerate_id(true);
$_SESSION['authenticated'] = true;
$_SESSION['username'] = trim($username);
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
header('Location: /panel', true, 303);
exit;
}
function logout(): never
{
$csrf = scalarPostValue('csrf_token', 64);
if (!csrfIsValid($csrf)) {
renderErrorPage(403, 'اعتبار درخواست به پایان رسیده است.');
}
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', [
'expires' => time() - 42000,
'path' => $params['path'],
'domain' => $params['domain'],
'secure' => $params['secure'],
'httponly' => $params['httponly'],
'samesite' => 'Lax',
]);
}
session_destroy();
header('Location: /panel', true, 303);
exit;
}
function generateCaptchaCode(): string
{
$alphabet = '123456789';
$code = '';
for ($i = 0; $i < 5; $i++) {
$code .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $code;
}
function renderCaptcha(): never
{
$code = generateCaptchaCode();
$_SESSION['captcha_hash'] = password_hash($code, PASSWORD_DEFAULT);
$_SESSION['captcha_issued_at'] = time();
if (!function_exists('imagecreatetruecolor')) {
header('Content-Type: image/svg+xml; charset=UTF-8');
$escapedCode = htmlspecialchars($code, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="220" height="72" viewBox="0 0 220 72">
<defs><linearGradient id="bg" x1="0" x2="1"><stop stop-color="#f4f7fb"/><stop offset="1" stop-color="#e8eef7"/></linearGradient></defs>
<rect width="220" height="72" rx="10" fill="url(#bg)"/>
<path d="M3 17L217 55M8 63L212 11M28 4L191 68M5 40L215 29" stroke="#9badc4" stroke-width="1.5" opacity=".7"/>
<text x="110" y="48" text-anchor="middle" font-family="monospace" font-size="32"
font-weight="bold" letter-spacing="8" fill="#19324d">{$escapedCode}</text>
</svg>
SVG;
exit;
}
$image = imagecreatetruecolor(220, 72);
$background = imagecolorallocate($image, 241, 245, 250);
$foreground = imagecolorallocate($image, 25, 50, 77);
$noise = imagecolorallocate($image, 139, 160, 185);
imagefilledrectangle($image, 0, 0, 220, 72, $background);
for ($i = 0; $i < 9; $i++) {
imageline(
$image,
random_int(0, 219),
random_int(0, 71),
random_int(0, 219),
random_int(0, 71),
$noise
);
}
$font = 5;
$textWidth = imagefontwidth($font) * strlen($code);
$textHeight = imagefontheight($font);
$textLayer = imagecreatetruecolor($textWidth, $textHeight);
imagefilledrectangle($textLayer, 0, 0, $textWidth, $textHeight, $background);
imagecolortransparent($textLayer, $background);
imagestring($textLayer, $font, 0, 0, $code, $foreground);
$scaledTextLayer = imagescale(
$textLayer,
$textWidth * 3,
$textHeight * 3,
IMG_NEAREST_NEIGHBOUR
);
imagecopy(
$image,
$scaledTextLayer,
(int) ((220 - imagesx($scaledTextLayer)) / 2),
(int) ((72 - imagesy($scaledTextLayer)) / 2),
0,
0,
imagesx($scaledTextLayer),
imagesy($scaledTextLayer)
);
header('Content-Type: image/jpeg');
imagejpeg($image, null, 92);
exit;
}
function renderLogin(string $error = '', int $status = 200, string $username = ''): never
{
http_response_code($status);
$safeUsername = htmlspecialchars($username, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$safeCsrf = htmlspecialchars(csrfToken(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$errorHtml = $error === ''
? ''
: '<div class="alert" role="alert"><span class="alert-icon">!</span><span>'
. htmlspecialchars($error, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
. '</span></div>';
$captchaUrl = '/captcha?nonce=' . rawurlencode(bin2hex(random_bytes(8)));
echo pageStart('ورود به حساب کاربری', 'login-page');
echo <<<HTML
<main class="login-shell">
<section class="login-card" aria-labelledby="login-title">
<div class="login-brand">
<a class="brand brand-light" href="/panel" aria-label="صفحه اصلی آبان‌نت">
<span class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 48 48"><path d="M24 5a19 19 0 1 0 19 19A19 19 0 0 0 24 5Zm0 7a12 12 0 0 1 10.4 6H13.6A12 12 0 0 1 24 12Zm0 24a12 12 0 0 1-10.4-6h20.8A12 12 0 0 1 24 36Z"/></svg>
</span>
<span><b>آبان‌نت</b><small>اینترنت، همیشه در دسترس</small></span>
</a>
<div class="brand-message">
<span class="eyebrow">سامانه مشترکین</span>
<h2>همه‌چیز برای مدیریت بهتر سرویس شما</h2>
<p>مصرف اینترنت، وضعیت سرویس و جزئیات حساب خود را یک‌جا مشاهده و مدیریت کنید.</p>
</div>
<div class="brand-support">
<span>پشتیبانی شبانه‌روزی</span>
<b dir="ltr">۰۲۱-۹۱۰۰ ۱۰۱۰</b>
</div>
</div>
<div class="login-form-wrap">
<div class="mobile-brand">
<span class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 48 48"><path d="M24 5a19 19 0 1 0 19 19A19 19 0 0 0 24 5Zm0 7a12 12 0 0 1 10.4 6H13.6A12 12 0 0 1 24 12Zm0 24a12 12 0 0 1-10.4-6h20.8A12 12 0 0 1 24 36Z"/></svg>
</span>
<b>آبان‌نت</b>
</div>
<div class="form-heading">
<span class="eyebrow">خوش آمدید</span>
<h1 id="login-title">ورود به حساب کاربری</h1>
<p>برای مشاهده و مدیریت سرویس وارد حساب خود شوید.</p>
</div>
{$errorHtml}
<form method="post" action="/login" autocomplete="on">
<input type="hidden" name="csrf_token" value="{$safeCsrf}">
<label for="username">نام کاربری</label>
<div class="input-wrap">
<span class="field-icon" aria-hidden="true">
<svg viewBox="0 0 24 24"><path d="M12 12a4 4 0 1 0-4-4 4 4 0 0 0 4 4Zm0 2c-4.42 0-8 2.01-8 4.5V20h16v-1.5c0-2.49-3.58-4.5-8-4.5Z"/></svg>
</span>
<input id="username" name="username" type="text" value="{$safeUsername}" maxlength="128"
autocomplete="username" placeholder="نام کاربری خود را وارد کنید" required autofocus>
</div>
<div class="label-row">
<label for="password">رمز عبور</label>
<a href="#" class="subtle-link">رمز عبور را فراموش کرده‌اید؟</a>
</div>
<div class="input-wrap">
<span class="field-icon" aria-hidden="true">
<svg viewBox="0 0 24 24"><path d="M17 9h-1V7a4 4 0 0 0-8 0v2H7a2 2 0 0 0-2 2v9h14v-9a2 2 0 0 0-2-2Zm-5 7.75A1.75 1.75 0 1 1 13.75 15 1.75 1.75 0 0 1 12 16.75ZM14 9h-4V7a2 2 0 0 1 4 0Z"/></svg>
</span>
<input id="password" name="password" type="password" maxlength="256"
autocomplete="current-password" placeholder="رمز عبور خود را وارد کنید" required>
</div>
<label for="captcha">کد امنیتی</label>
<div class="captcha-row">
<div class="input-wrap">
<input id="captcha" name="captcha" type="text" maxlength="16" inputmode="text"
autocomplete="off" autocapitalize="characters" spellcheck="false"
placeholder="کد تصویر" required>
</div>
<a class="captcha-image" href="/panel" title="دریافت کد جدید">
<img src="{$captchaUrl}" width="220" height="72" alt="کد امنیتی">
</a>
</div>
<button class="primary-button" type="submit">
<span>ورود به پنل</span>
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m14.7 6.3-1.4 1.4 3.3 3.3H4v2h12.6l-3.3 3.3 1.4 1.4 5.7-5.7Z"/></svg>
</button>
</form>
<p class="privacy-note">
ورود شما به سامانه به معنای پذیرش
<a href="#">شرایط استفاده و حریم خصوصی</a>
است.
</p>
</div>
</section>
<footer class="page-footer">© ۱۴۰۵ آبان‌نت — تمامی حقوق محفوظ است.</footer>
</main>
HTML;
echo pageEnd();
exit;
}
function renderPanel(): never
{
$rawUsername = (string) ($_SESSION['username'] ?? '');
$username = htmlspecialchars(
$rawUsername,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
$avatarCharacter = 'ک';
if (preg_match('/^./u', $rawUsername, $avatarMatch) === 1) {
$avatarCharacter = htmlspecialchars($avatarMatch[0], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$traffic = envValue('PANEL_TRAFFIC_GB', DEFAULT_TRAFFIC_GB);
if (preg_match('/^\d+(?:\.\d+)?$/', $traffic) !== 1) {
$traffic = DEFAULT_TRAFFIC_GB;
}
$totalTraffic = envValue('PANEL_TOTAL_TRAFFIC_GB', '50');
if (preg_match('/^\d+(?:\.\d+)?$/', $totalTraffic) !== 1 || (float) $totalTraffic <= 0) {
$totalTraffic = '50';
}
$trafficPercent = min(100, max(0, ((float) $traffic / (float) $totalTraffic) * 100));
$trafficPercentCss = number_format($trafficPercent, 1, '.', '');
$usedTraffic = max(0, (float) $totalTraffic - (float) $traffic);
$usedTrafficText = number_format($usedTraffic, 1, '.', '');
$safeTraffic = htmlspecialchars($traffic, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$safeTotalTraffic = htmlspecialchars($totalTraffic, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$planName = htmlspecialchars(envValue('PANEL_PLAN_NAME', DEFAULT_PLAN_NAME), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$expiryDate = htmlspecialchars(envValue('PANEL_EXPIRY_DATE', '۱۴۰۵/۰۶/۲۸'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$safeCsrf = htmlspecialchars(csrfToken(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo pageStart('داشبورد مشترکین', 'dashboard-page');
echo <<<HTML
<div class="dashboard-layout">
<aside class="sidebar">
<a class="brand brand-dark" href="/panel">
<span class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 48 48"><path d="M24 5a19 19 0 1 0 19 19A19 19 0 0 0 24 5Zm0 7a12 12 0 0 1 10.4 6H13.6A12 12 0 0 1 24 12Zm0 24a12 12 0 0 1-10.4-6h20.8A12 12 0 0 1 24 36Z"/></svg>
</span>
<span><b>آبان‌نت</b><small>پنل مشترکین</small></span>
</a>
<nav class="side-nav" aria-label="منوی اصلی">
<a class="active" href="/panel">
<svg viewBox="0 0 24 24"><path d="M4 13h6V4H4Zm0 7h6v-5H4Zm8 0h8v-9h-8Zm0-16v5h8V4Z"/></svg>
<span>داشبورد</span>
</a>
<a href="#">
<svg viewBox="0 0 24 24"><path d="M4 4h16v4H4Zm0 6h16v10H4Zm3 3v2h4v-2Z"/></svg>
<span>سرویس‌های من</span>
</a>
<a href="#">
<svg viewBox="0 0 24 24"><path d="M3 13h2v-2H3Zm0 4h2v-2H3Zm0-8h2V7H3Zm4 4h14v-2H7Zm0 4h14v-2H7ZM7 7v2h14V7Z"/></svg>
<span>ریز مصرف</span>
</a>
<a href="#">
<svg viewBox="0 0 24 24"><path d="M11 8h2v2h-2Zm0 4h2v6h-2Zm1-10a10 10 0 1 0 10 10A10 10 0 0 0 12 2Z"/></svg>
<span>درخواست پشتیبانی</span>
</a>
<a href="#">
<svg viewBox="0 0 24 24"><path d="M12 12a4 4 0 1 0-4-4 4 4 0 0 0 4 4Zm0 2c-4.42 0-8 2.01-8 4.5V20h16v-1.5c0-2.49-3.58-4.5-8-4.5Z"/></svg>
<span>حساب کاربری</span>
</a>
</nav>
<div class="sidebar-help">
<span class="help-icon">؟</span>
<b>نیاز به راهنمایی دارید؟</b>
<small>کارشناسان ما شبانه‌روزی پاسخگوی شما هستند.</small>
<a href="#">ارتباط با پشتیبانی</a>
</div>
<form method="post" action="/logout" class="logout-form">
<input type="hidden" name="csrf_token" value="{$safeCsrf}">
<button type="submit">
<svg viewBox="0 0 24 24"><path d="M10 17v3H4V4h6v3h2V2H2v20h10v-5Zm10-5-4-4v3H8v2h8v3Z"/></svg>
خروج از حساب
</button>
</form>
</aside>
<main class="dashboard-main">
<header class="topbar">
<div class="mobile-logo"><span class="brand-mark"><svg viewBox="0 0 48 48"><path d="M24 5a19 19 0 1 0 19 19A19 19 0 0 0 24 5Zm0 7a12 12 0 0 1 10.4 6H13.6A12 12 0 0 1 24 12Zm0 24a12 12 0 0 1-10.4-6h20.8A12 12 0 0 1 24 36Z"/></svg></span><b>آبان‌نت</b></div>
<div class="top-actions">
<button class="icon-button" type="button" aria-label="اعلان‌ها">
<svg viewBox="0 0 24 24"><path d="M18 8a6 6 0 0 0-5-5.91V1h-2v1.09A6 6 0 0 0 6 8c0 7-3 7-3 9h18c0-2-3-2-3-9Zm-8 11a2 2 0 0 0 4 0Z"/></svg>
<span class="notification-dot"></span>
</button>
<div class="user-menu">
<span class="avatar">{$avatarCharacter}</span>
<span><small>مشترک آبان‌نت</small><b>{$username}</b></span>
</div>
</div>
</header>
<div class="dashboard-content">
<div class="welcome-row">
<div>
<p class="eyebrow">داشبورد مشترکین</p>
<h1>سلام {$username}، خوش آمدید</h1>
<p>در این صفحه می‌توانید وضعیت سرویس و مصرف خود را بررسی کنید.</p>
</div>
<span class="status-pill"><i></i> سرویس شما فعال است</span>
</div>
<section class="summary-grid" aria-label="خلاصه سرویس">
<article class="service-card">
<div class="card-head">
<div>
<span class="card-label">سرویس فعال</span>
<h2>{$planName}</h2>
</div>
<span class="round-icon blue"><svg viewBox="0 0 24 24"><path d="M4 6h16v12H4Zm2 2v8h12V8Zm2 2h5v2H8Z"/></svg></span>
</div>
<div class="service-meta">
<div><small>سرعت سرویس</small><b>۱۶ مگابیت</b></div>
<div><small>تاریخ انقضا</small><b>{$expiryDate}</b></div>
</div>
<a class="text-link" href="#">مشاهده جزئیات سرویس <span>←</span></a>
</article>
<article class="usage-card">
<div class="card-head">
<div>
<span class="card-label">حجم باقی‌مانده</span>
<h2><strong>{$safeTraffic}</strong> گیگابایت</h2>
</div>
<span class="round-icon green"><svg viewBox="0 0 24 24"><path d="M11 2v20a10 10 0 0 1 0-20Zm2 0a10 10 0 0 1 0 20Z"/></svg></span>
</div>
<div class="progress" aria-label="درصد حجم باقی‌مانده"><span style="width: {$trafficPercentCss}%"></span></div>
<div class="usage-meta"><span>{$usedTrafficText} گیگابایت مصرف‌شده</span><span>از {$safeTotalTraffic} گیگابایت</span></div>
<a class="text-link" href="#">مشاهده ریز مصرف <span>←</span></a>
</article>
</section>
<section class="quick-section">
<div class="section-heading"><h2>دسترسی سریع</h2><p>عملیات پرکاربرد حساب شما</p></div>
<div class="quick-grid">
<a href="#"><span class="quick-icon purple"><svg viewBox="0 0 24 24"><path d="M19 7h-1V6a3 3 0 0 0-6 0v1H5a2 2 0 0 0-2 2v10h18V9a2 2 0 0 0-2-2Zm-5-1a1 1 0 0 1 2 0v1h-2Z"/></svg></span><span><b>تمدید سرویس</b><small>تمدید یا تغییر طرح فعلی</small></span><i>‹</i></a>
<a href="#"><span class="quick-icon orange"><svg viewBox="0 0 24 24"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2Zm1 15h-2v-2h2Zm1.8-6.1-.9.9A3.1 3.1 0 0 0 13 14h-2v-.5a4 4 0 0 1 1.2-2.8l1.2-1.2A1.6 1.6 0 1 0 10.7 8H8.6a3.7 3.7 0 1 1 6.2 2.9Z"/></svg></span><span><b>پشتیبانی</b><small>ثبت و پیگیری درخواست</small></span><i>‹</i></a>
<a href="#"><span class="quick-icon cyan"><svg viewBox="0 0 24 24"><path d="M3 3v18h18v-2H5V3Zm4 12h3v2H7Zm0-4h5v2H7Zm0-4h10v2H7Zm7 4h3v6h-3Z"/></svg></span><span><b>گزارش مصرف</b><small>بررسی جزئیات مصرف دوره</small></span><i>‹</i></a>
</div>
</section>
<section class="notice">
<span class="notice-icon"><svg viewBox="0 0 24 24"><path d="M11 8h2v2h-2Zm0 4h2v5h-2Zm1-10a10 10 0 1 0 10 10A10 10 0 0 0 12 2Z"/></svg></span>
<div><b>یادآوری تمدید سرویس</b><p>برای جلوگیری از قطع سرویس، بهتر است پیش از پایان دوره نسبت به تمدید آن اقدام کنید.</p></div>
<a href="#">تمدید سرویس</a>
</section>
</div>
</main>
</div>
HTML;
echo pageEnd();
exit;
}
function renderErrorPage(int $status, string $message): never
{
http_response_code($status);
$safeMessage = htmlspecialchars($message, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo pageStart((string) $status, 'error-page');
echo <<<HTML
<main class="error-shell">
<section class="error-card">
<a class="brand" href="/panel"><span class="brand-mark"><svg viewBox="0 0 48 48"><path d="M24 5a19 19 0 1 0 19 19A19 19 0 0 0 24 5Zm0 7a12 12 0 0 1 10.4 6H13.6A12 12 0 0 1 24 12Zm0 24a12 12 0 0 1-10.4-6h20.8A12 12 0 0 1 24 36Z"/></svg></span><b>آبان‌نت</b></a>
<span class="error-code">{$status}</span>
<h1>خطایی رخ داده است</h1>
<p>{$safeMessage}</p>
<a class="primary-button link-button" href="/panel">بازگشت به پنل</a>
</section>
</main>
HTML;
echo pageEnd();
exit;
}
function pageStart(string $title, string $bodyClass = ''): string
{
$safeTitle = htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$safeBodyClass = htmlspecialchars($bodyClass, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
return <<<HTML
<!doctype html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#102e50">
<title>{$safeTitle} | آبان‌نت</title>
<style>
:root {
color-scheme: light;
font-family: Tahoma, Arial, sans-serif;
--navy: #102e50;
--navy-deep: #09213b;
--blue: #1769e0;
--blue-hover: #0d57c2;
--text: #182537;
--muted: #718096;
--line: #e5eaf0;
--surface: #fff;
--page: #f5f7fa;
--green: #1ea672;
}
* { box-sizing: border-box; }
html { min-height: 100%; }
body { margin: 0; min-height: 100vh; color: var(--text); background: var(--page); }
a { color: inherit; }
button, input { font: inherit; }
svg { display: block; width: 1em; height: 1em; fill: currentColor; }
.eyebrow { color: var(--blue); font-size: 12px; font-weight: 700; letter-spacing: .02em; }
.brand { display: inline-flex; align-items: center; gap: 11px; text-decoration: none; }
.brand-mark { display: inline-grid; width: 45px; height: 45px; place-items: center; color: #fff; background: var(--blue); border-radius: 14px; box-shadow: 0 8px 24px rgba(23, 105, 224, .24); }
.brand-mark svg { width: 29px; height: 29px; }
.brand b { display: block; font-size: 20px; }
.brand small { display: block; margin-top: 4px; font-size: 10px; font-weight: 400; opacity: .68; }
.primary-button {
display: inline-flex; min-height: 52px; align-items: center; justify-content: center; gap: 10px;
border: 0; border-radius: 10px; color: #fff; background: var(--blue); padding: 12px 20px;
font-weight: 700; cursor: pointer; transition: background .18s, transform .18s, box-shadow .18s;
}
.primary-button:hover { background: var(--blue-hover); box-shadow: 0 8px 22px rgba(23, 105, 224, .23); transform: translateY(-1px); }
.primary-button svg { width: 21px; height: 21px; }
.link-button { text-decoration: none; }
/* Login */
.login-shell {
min-height: 100vh; display: grid; place-items: center; padding: 34px 24px 62px;
background:
radial-gradient(circle at 10% 15%, rgba(28, 111, 227, .08), transparent 28%),
radial-gradient(circle at 87% 83%, rgba(16, 46, 80, .08), transparent 26%),
#f4f7fb;
}
.login-card {
display: grid; grid-template-columns: .95fr 1.05fr; width: min(100%, 990px); min-height: 630px;
overflow: hidden; background: var(--surface); border: 1px solid rgba(217, 225, 235, .8);
border-radius: 22px; box-shadow: 0 28px 75px rgba(22, 48, 78, .12);
}
.login-brand {
position: relative; display: flex; flex-direction: column; overflow: hidden; padding: 46px;
color: #fff; background: linear-gradient(150deg, #0d2a49 0%, #123f6e 58%, #1765ab 100%);
}
.login-brand::before, .login-brand::after {
content: ""; position: absolute; border: 1px solid rgba(255, 255, 255, .08); border-radius: 50%;
}
.login-brand::before { width: 390px; height: 390px; left: -230px; bottom: -160px; }
.login-brand::after { width: 270px; height: 270px; right: -160px; top: 80px; box-shadow: 0 0 0 70px rgba(255,255,255,.025), 0 0 0 140px rgba(255,255,255,.018); }
.brand-light { position: relative; z-index: 1; color: #fff; }
.brand-light .brand-mark { background: rgba(255, 255, 255, .13); box-shadow: none; backdrop-filter: blur(8px); }
.brand-message { position: relative; z-index: 1; margin: auto 0; max-width: 330px; }
.brand-message .eyebrow { color: #78b8ff; }
.brand-message h2 { margin: 12px 0 16px; font-size: clamp(27px, 3vw, 37px); line-height: 1.55; letter-spacing: -.02em; }
.brand-message p { margin: 0; color: rgba(255,255,255,.72); font-size: 14px; line-height: 2; }
.brand-support { position: relative; z-index: 1; display: flex; align-items: center; justify-content: space-between; padding-top: 24px; border-top: 1px solid rgba(255,255,255,.12); color: rgba(255,255,255,.67); font-size: 12px; }
.brand-support b { color: #fff; font-size: 14px; }
.login-form-wrap { display: flex; flex-direction: column; justify-content: center; padding: 52px 66px; }
.mobile-brand { display: none; align-items: center; gap: 10px; margin-bottom: 38px; color: var(--navy); }
.mobile-brand b { font-size: 21px; }
.form-heading { margin-bottom: 24px; }
.form-heading h1 { margin: 8px 0 9px; color: var(--navy-deep); font-size: 27px; }
.form-heading p { margin: 0; color: var(--muted); font-size: 13px; line-height: 1.8; }
label { display: block; margin: 15px 0 7px; color: #334155; font-size: 13px; font-weight: 700; }
.label-row { display: flex; align-items: center; justify-content: space-between; margin-top: 15px; }
.label-row label { margin-top: 0; }
.subtle-link { color: var(--blue); font-size: 11px; text-decoration: none; }
.input-wrap { position: relative; }
.input-wrap input {
width: 100%; min-height: 48px; padding: 11px 44px 11px 13px; color: var(--text);
background: #fbfcfe; border: 1px solid #d8e0e9; border-radius: 9px; outline: 0;
font-size: 13px; transition: border .18s, box-shadow .18s, background .18s;
}
.input-wrap input::placeholder { color: #a5afbd; }
.input-wrap input:focus { background: #fff; border-color: var(--blue); box-shadow: 0 0 0 3px rgba(23, 105, 224, .1); }
.field-icon { position: absolute; z-index: 1; top: 50%; right: 14px; color: #8a98aa; transform: translateY(-50%); pointer-events: none; }
.field-icon svg { width: 19px; height: 19px; }
.captcha-row { display: grid; grid-template-columns: 1fr 145px; gap: 10px; align-items: stretch; }
.captcha-row .input-wrap input { height: 54px; padding-right: 13px; text-align: center; direction: ltr; letter-spacing: .15em; }
.captcha-image { display: block; overflow: hidden; height: 54px; border: 1px solid #d8e0e9; border-radius: 9px; background: #f1f5fa; }
.captcha-image img { width: 100%; height: 100%; object-fit: cover; }
.login-form-wrap form > .primary-button { width: 100%; margin-top: 24px; }
.alert { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 6px; padding: 11px 12px; color: #9b2635; background: #fff1f3; border: 1px solid #ffdce2; border-radius: 9px; font-size: 12px; line-height: 1.7; }
.alert-icon { display: inline-grid; flex: 0 0 20px; height: 20px; place-items: center; margin-top: 1px; color: #fff; background: #c73549; border-radius: 50%; font-weight: 700; }
.privacy-note { margin: 19px 0 0; color: #8a96a6; text-align: center; font-size: 10px; line-height: 1.8; }
.privacy-note a { color: #687789; text-decoration: underline; text-underline-offset: 2px; }
.page-footer { position: fixed; bottom: 18px; color: #8a96a6; font-size: 10px; text-align: center; }
/* Dashboard */
.dashboard-layout { display: grid; grid-template-columns: 255px minmax(0, 1fr); min-height: 100vh; }
.sidebar { position: sticky; top: 0; display: flex; height: 100vh; flex-direction: column; padding: 28px 20px 20px; color: #dbe7f4; background: var(--navy-deep); }
.brand-dark { padding: 0 8px 27px; color: #fff; }
.brand-dark .brand-mark { background: var(--blue); }
.side-nav { display: grid; gap: 5px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,.08); }
.side-nav a { display: flex; align-items: center; gap: 13px; min-height: 46px; padding: 0 14px; color: #aebed0; border-radius: 9px; font-size: 13px; text-decoration: none; transition: .18s; }
.side-nav a:hover { color: #fff; background: rgba(255,255,255,.06); }
.side-nav a.active { color: #fff; background: var(--blue); box-shadow: 0 8px 22px rgba(0,0,0,.14); }
.side-nav svg { width: 19px; height: 19px; }
.sidebar-help { display: flex; flex-direction: column; align-items: center; margin-top: auto; padding: 18px 14px; background: rgba(255,255,255,.055); border: 1px solid rgba(255,255,255,.06); border-radius: 12px; text-align: center; }
.help-icon { display: grid; width: 34px; height: 34px; place-items: center; margin-bottom: 10px; color: #fff; background: rgba(255,255,255,.1); border-radius: 50%; font-weight: 700; }
.sidebar-help b { font-size: 12px; }
.sidebar-help small { margin: 8px 0 12px; color: #8fa5bc; font-size: 9px; line-height: 1.8; }
.sidebar-help a { color: #76b6ff; font-size: 10px; font-weight: 700; text-decoration: none; }
.logout-form { margin-top: 12px; }
.logout-form button { display: flex; width: 100%; align-items: center; gap: 12px; padding: 10px 14px; color: #94a9bf; background: transparent; border: 0; border-radius: 8px; font-size: 11px; cursor: pointer; }
.logout-form button:hover { color: #fff; background: rgba(255,255,255,.05); }
.logout-form svg { width: 18px; height: 18px; }
.dashboard-main { min-width: 0; }
.topbar { display: flex; height: 76px; align-items: center; justify-content: flex-end; padding: 0 38px; background: #fff; border-bottom: 1px solid var(--line); }
.mobile-logo { display: none; align-items: center; gap: 9px; color: var(--navy); }
.mobile-logo .brand-mark { width: 36px; height: 36px; border-radius: 10px; }
.mobile-logo .brand-mark svg { width: 23px; height: 23px; }
.top-actions { display: flex; align-items: center; gap: 21px; }
.icon-button { position: relative; display: grid; width: 38px; height: 38px; place-items: center; color: #6b7b8e; background: #f5f7fa; border: 0; border-radius: 10px; cursor: pointer; }
.icon-button svg { width: 18px; height: 18px; }
.notification-dot { position: absolute; top: 8px; right: 8px; width: 6px; height: 6px; background: #eb4c5c; border: 1px solid #fff; border-radius: 50%; }
.user-menu { display: flex; align-items: center; gap: 10px; padding-right: 20px; border-right: 1px solid var(--line); }
.avatar { display: grid; width: 39px; height: 39px; place-items: center; color: var(--blue); background: #eaf2ff; border-radius: 12px; font-size: 14px; font-weight: 700; }
.user-menu small, .user-menu b { display: block; }
.user-menu small { margin-bottom: 4px; color: #94a0af; font-size: 9px; }
.user-menu b { color: #26374a; font-size: 11px; }
.dashboard-content { width: min(100%, 1180px); margin: 0 auto; padding: 34px 38px 50px; }
.welcome-row { display: flex; align-items: center; justify-content: space-between; gap: 24px; margin-bottom: 27px; }
.welcome-row .eyebrow { margin: 0 0 7px; }
.welcome-row h1 { margin: 0 0 8px; color: var(--navy); font-size: 23px; }
.welcome-row > div > p:last-child { margin: 0; color: var(--muted); font-size: 11px; }
.status-pill { display: inline-flex; align-items: center; gap: 8px; padding: 8px 12px; color: #167d58; background: #eaf9f3; border: 1px solid #d4f1e5; border-radius: 999px; font-size: 10px; font-weight: 700; white-space: nowrap; }
.status-pill i { width: 7px; height: 7px; background: var(--green); border-radius: 50%; box-shadow: 0 0 0 4px rgba(30,166,114,.12); }
.summary-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
.service-card, .usage-card { padding: 23px; background: #fff; border: 1px solid var(--line); border-radius: 14px; box-shadow: 0 5px 18px rgba(25, 49, 76, .035); }
.card-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; }
.card-label { color: #8996a7; font-size: 10px; }
.card-head h2 { margin: 7px 0 0; color: var(--navy); font-size: 17px; }
.card-head h2 strong { font-size: 23px; }
.round-icon { display: grid; flex: 0 0 43px; height: 43px; place-items: center; border-radius: 12px; }
.round-icon svg { width: 21px; height: 21px; }
.round-icon.blue { color: var(--blue); background: #eaf2ff; }
.round-icon.green { color: var(--green); background: #e8f8f2; }
.service-meta { display: grid; grid-template-columns: 1fr 1fr; margin: 21px 0 15px; padding: 15px 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.service-meta > div + div { padding-right: 20px; border-right: 1px solid var(--line); }
.service-meta small, .service-meta b { display: block; }
.service-meta small { margin-bottom: 7px; color: #919dac; font-size: 9px; }
.service-meta b { color: #34465a; font-size: 11px; }
.text-link { display: flex; align-items: center; justify-content: space-between; color: var(--blue); font-size: 10px; font-weight: 700; text-decoration: none; }
.text-link span { font-size: 17px; }
.progress { height: 7px; overflow: hidden; margin: 27px 0 10px; background: #edf1f5; border-radius: 999px; direction: ltr; }
.progress span { display: block; height: 100%; background: linear-gradient(90deg, #27b17d, #58c99d); border-radius: inherit; }
.usage-meta { display: flex; justify-content: space-between; margin-bottom: 22px; color: #8a96a6; font-size: 9px; }
.quick-section { margin-top: 29px; }
.section-heading h2 { margin: 0 0 5px; color: var(--navy); font-size: 16px; }
.section-heading p { margin: 0; color: var(--muted); font-size: 10px; }
.quick-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; margin-top: 15px; }
.quick-grid > a { display: flex; align-items: center; gap: 12px; min-width: 0; padding: 17px; background: #fff; border: 1px solid var(--line); border-radius: 12px; text-decoration: none; transition: transform .18s, box-shadow .18s, border .18s; }
.quick-grid > a:hover { border-color: #ccdaeb; box-shadow: 0 9px 25px rgba(25,49,76,.07); transform: translateY(-2px); }
.quick-icon { display: grid; flex: 0 0 39px; height: 39px; place-items: center; border-radius: 10px; }
.quick-icon svg { width: 19px; height: 19px; }
.quick-icon.purple { color: #7e58d7; background: #f1edfc; }
.quick-icon.orange { color: #e98537; background: #fff1e6; }
.quick-icon.cyan { color: #1c93aa; background: #e7f7fa; }
.quick-grid b, .quick-grid small { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.quick-grid b { margin-bottom: 5px; color: #33465a; font-size: 11px; }
.quick-grid small { color: #929eac; font-size: 8px; }
.quick-grid i { margin-right: auto; color: #9eabb9; font-size: 22px; font-style: normal; }
.notice { display: flex; align-items: center; gap: 14px; margin-top: 24px; padding: 17px 20px; color: #5f4a17; background: #fff9e9; border: 1px solid #f7eac3; border-radius: 12px; }
.notice-icon { display: grid; flex: 0 0 35px; height: 35px; place-items: center; color: #d79021; background: #ffefc4; border-radius: 9px; }
.notice-icon svg { width: 18px; height: 18px; }
.notice b { display: block; margin-bottom: 4px; font-size: 10px; }
.notice p { margin: 0; color: #8b7543; font-size: 9px; line-height: 1.7; }
.notice a { margin-right: auto; padding: 8px 13px; color: #8a5c0c; background: #fff; border: 1px solid #eedcae; border-radius: 8px; font-size: 9px; font-weight: 700; text-decoration: none; white-space: nowrap; }
/* Error */
.error-shell { min-height: 100vh; display: grid; place-items: center; padding: 24px; background: #f4f7fb; }
.error-card { width: min(100%, 430px); padding: 42px; background: #fff; border: 1px solid var(--line); border-radius: 18px; box-shadow: 0 22px 55px rgba(22,48,78,.1); text-align: center; }
.error-card .brand { color: var(--navy); }
.error-code { display: block; margin: 32px 0 3px; color: var(--blue); font-size: 64px; font-weight: 800; }
.error-card h1 { margin: 0; color: var(--navy); font-size: 23px; }
.error-card p { margin: 13px 0 25px; color: var(--muted); font-size: 13px; line-height: 1.8; }
@media (max-width: 900px) {
.login-card { grid-template-columns: 1fr; width: min(100%, 510px); min-height: auto; }
.login-brand { display: none; }
.login-form-wrap { padding: 45px 48px; }
.mobile-brand { display: flex; }
.dashboard-layout { grid-template-columns: 1fr; }
.sidebar { display: none; }
.topbar { justify-content: space-between; padding: 0 24px; }
.mobile-logo { display: flex; }
.dashboard-content { padding: 28px 24px 44px; }
}
@media (max-width: 650px) {
.login-shell { padding: 0; place-items: stretch; background: #fff; }
.login-card { width: 100%; min-height: 100vh; border: 0; border-radius: 0; box-shadow: none; }
.login-form-wrap { justify-content: flex-start; padding: 34px 24px; }
.page-footer { display: none; }
.captcha-row { grid-template-columns: 1fr 130px; }
.topbar { height: 66px; padding: 0 17px; }
.user-menu > span:not(.avatar) { display: none; }
.user-menu { padding-right: 13px; }
.dashboard-content { padding: 23px 17px 35px; }
.welcome-row { align-items: flex-start; flex-direction: column; gap: 14px; }
.summary-grid { grid-template-columns: 1fr; }
.quick-grid { grid-template-columns: 1fr; }
.notice { align-items: flex-start; flex-wrap: wrap; }
.notice a { margin-right: 49px; }
}
</style>
</head>
<body class="{$safeBodyClass}">
HTML;
}
function pageEnd(): string
{
return "</body>\n</html>\n";
}
+450 -189
View File
@@ -1,16 +1,18 @@
from __future__ import annotations
import base64
import csv
import hashlib
import http.cookiejar
import http.server
import json
import os
import re
import shutil
import socket
import sqlite3
import subprocess
import sys
import tempfile
import threading
import time
import unittest
import urllib.error
@@ -21,6 +23,7 @@ from pathlib import Path
PROJECT = Path(__file__).resolve().parents[1]
PNG = b"\x89PNG\r\n\x1a\n" + b"test-image-payload"
CSV_COLUMNS = ["filename", "label", "batch_id", "verified", "hash"]
class ToolTests(unittest.TestCase):
@@ -37,10 +40,7 @@ class ToolTests(unittest.TestCase):
image.write_bytes(PNG)
csv_path = root / "labels.csv"
with csv_path.open("w", newline="", encoding="utf-8") as output:
writer = csv.DictWriter(
output,
fieldnames=["filename", "label", "batch_id", "verified", "hash"],
)
writer = csv.DictWriter(output, fieldnames=CSV_COLUMNS)
writer.writeheader()
writer.writerow(
{
@@ -63,11 +63,16 @@ class ToolTests(unittest.TestCase):
[
sys.executable,
str(PROJECT / "download_dataset.py"),
"--url", url,
"--output", str(dataset),
"--count", "3",
"--workers", "2",
"--flush-every", "1",
"--url",
url,
"--output",
str(dataset),
"--count",
"3",
"--workers",
"2",
"--flush-every",
"1",
],
text=True,
capture_output=True,
@@ -77,20 +82,24 @@ class ToolTests(unittest.TestCase):
[
sys.executable,
str(PROJECT / "download_dataset.py"),
"--url", url,
"--output", str(dataset),
"--count", "5",
"--workers", "2",
"--url",
url,
"--output",
str(dataset),
"--count",
"5",
"--workers",
"2",
],
text=True,
capture_output=True,
)
self.assertEqual(second.returncode, 0, second.stderr)
with (dataset / "labels.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
with (dataset / "labels.csv").open(newline="", encoding="utf-8") as source:
rows = list(csv.DictReader(source))
self.assertEqual(len(rows), 5)
self.assertEqual(list(rows[0]), ["filename", "label", "batch_id", "verified", "hash"])
self.assertEqual(list(rows[0]), CSV_COLUMNS)
self.assertEqual(rows[0]["hash"], hashlib.sha256(PNG).hexdigest())
self.assertTrue(all((dataset / row["filename"]).is_file() for row in rows))
@@ -99,15 +108,17 @@ class ToolTests(unittest.TestCase):
[
sys.executable,
str(PROJECT / "find_duplicates.py"),
"--csv", str(dataset / "labels.csv"),
"--output", str(report),
"--csv",
str(dataset / "labels.csv"),
"--output",
str(report),
],
text=True,
capture_output=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
with report.open(newline="", encoding="utf-8") as f:
duplicates = list(csv.DictReader(f))
with report.open(newline="", encoding="utf-8") as source:
duplicates = list(csv.DictReader(source))
self.assertEqual(len(duplicates), 4)
def test_verifier_normalizes_persian_digits_and_saves_on_quit(self):
@@ -118,10 +129,7 @@ class ToolTests(unittest.TestCase):
image.write_bytes(PNG)
csv_path = root / "labels.csv"
with csv_path.open("w", newline="", encoding="utf-8") as output:
writer = csv.DictWriter(
output,
fieldnames=["filename", "label", "batch_id", "verified", "hash"],
)
writer = csv.DictWriter(output, fieldnames=CSV_COLUMNS)
writer.writeheader()
for suffix in ("0", "1"):
writer.writerow(
@@ -130,7 +138,9 @@ class ToolTests(unittest.TestCase):
"label": "",
"batch_id": "0",
"verified": "0",
"hash": hashlib.sha256(PNG + suffix.encode()).hexdigest(),
"hash": hashlib.sha256(
PNG + suffix.encode()
).hexdigest(),
}
)
@@ -140,12 +150,15 @@ class ToolTests(unittest.TestCase):
fake_kitten.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
fake_kitten.chmod(0o755)
environment = os.environ.copy()
environment["PATH"] = f"{binary_dir}{os.pathsep}{environment.get('PATH', '')}"
environment["PATH"] = (
f"{binary_dir}{os.pathsep}{environment.get('PATH', '')}"
)
result = subprocess.run(
[
sys.executable,
str(PROJECT / "verify_labels.py"),
"--csv", str(csv_path),
"--csv",
str(csv_path),
],
input="۱۲۳\nq\n",
text=True,
@@ -179,8 +192,10 @@ class ToolTests(unittest.TestCase):
str(PROJECT / "merge_datasets.py"),
str(source_one),
str(source_two / "labels.csv"),
"--output", str(destination),
"--batch-size", "1",
"--output",
str(destination),
"--batch-size",
"1",
],
text=True,
capture_output=True,
@@ -203,63 +218,261 @@ class ToolTests(unittest.TestCase):
self.assertTrue(original_one.is_file())
self.assertTrue(original_two.is_file())
def test_php_web_verifier_initializes_saves_skips_edits_and_syncs(self):
def test_php_collector_loads_project_env_with_server_precedence(self):
php = shutil.which("php")
if php is None:
self.skipTest("PHP is not installed")
sqlite_support = subprocess.run(
[php, "-r", "exit(extension_loaded('pdo_sqlite') ? 0 : 1);"]
with tempfile.TemporaryDirectory() as temp:
env_path = Path(temp) / ".env"
env_path.write_text(
"\n".join(
[
'# Collector settings',
'PANEL_LOGIN_USERNAME="project user"',
'PANEL_LOGIN_PASSWORD="p@ss # $word"',
'PANEL_BASE_URL="https://example.test/panel/"',
'PANEL_REQUEST_TIMEOUT=17 # seconds',
'OCR_DATASET_DIR="/srv/tci dataset"',
'UNRELATED_SETTING="ignored"',
]
),
encoding="utf-8",
)
if sqlite_support.returncode != 0:
self.skipTest("PHP PDO SQLite is not installed")
environment = os.environ.copy()
for name in (
"PANEL_LOGIN_PASSWORD",
"PANEL_BASE_URL",
"PANEL_REQUEST_TIMEOUT",
"OCR_DATASET_DIR",
):
environment.pop(name, None)
environment["PANEL_LOGIN_USERNAME"] = "server-user"
script = (
f"require {json.dumps(str(PROJECT / 'web' / 'collector.php'))};"
"$config = collectorConfig($argv[1]);"
"echo json_encode($config, JSON_THROW_ON_ERROR);"
)
result = subprocess.run(
[php, "-r", script, str(env_path)],
text=True,
capture_output=True,
env=environment,
)
self.assertEqual(result.returncode, 0, result.stderr)
config = json.loads(result.stdout)
self.assertEqual(config["panel_username"], "server-user")
self.assertEqual(config["panel_password"], "p@ss # $word")
self.assertEqual(
config["panel_base_url"],
"https://example.test/panel",
)
self.assertEqual(config["timeout"], 17)
self.assertEqual(config["dataset"], "/srv/tci dataset")
def test_php_panel_collector_validates_and_appends_samples(self):
php = shutil.which("php")
if php is None:
self.skipTest("PHP is not installed")
class PanelHandler(http.server.BaseHTTPRequestHandler):
sessions: dict[str, dict[str, object]] = {}
sequence = 0
latest_code = ""
reject_credentials = False
next_fixture: tuple[str, bytes] | None = None
def log_message(self, *_args):
return
def send_body(
self,
status: int,
body: bytes,
*,
content_type: str = "text/html; charset=UTF-8",
headers: dict[str, str] | None = None,
) -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
for name, value in (headers or {}).items():
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)
def session_id(self) -> str:
cookie = self.headers.get("Cookie", "")
for part in cookie.split(";"):
name, separator, value = part.strip().partition("=")
if separator and name == "PHPSESSID":
return value
return ""
def render_login(self, session_id: str) -> bytes:
type(self).sequence += 1
nonce = type(self).sequence
session = type(self).sessions[session_id]
message = session.pop("message", "")
notification = (
"<script>UIkit.notification("
f"{json.dumps(message, ensure_ascii=False)}"
");</script>"
if message
else ""
)
host = self.headers["Host"]
return (
f"{notification}"
f'<form action="http://{host}/panel/login/{nonce}" method="POST">'
'<input type="hidden" name="redirect" value="">'
'<input name="username"><input name="password">'
'<img id="loginCaptchaImage" '
f'src="http://{host}/panel/captcha/?r={nonce}">'
'<input name="captcha"><button name="LoginFromWeb"></button>'
"</form>"
).encode()
def do_GET(self):
path = urllib.parse.urlsplit(self.path).path
if path in {"/panel", "/panel/"}:
session_id = self.session_id()
session = type(self).sessions.get(session_id)
headers = None
if session is None:
type(self).sequence += 1
session_id = f"session-{type(self).sequence}"
session = {}
type(self).sessions[session_id] = session
headers = {
"Set-Cookie": (
f"PHPSESSID={session_id}; Path=/; HttpOnly"
)
}
if session.get("authenticated"):
body = '<a href="/panel/logout">خروج</a>'.encode()
else:
body = self.render_login(session_id)
self.send_body(
200,
body,
headers=headers,
)
return
if path == "/panel/captcha/":
session = type(self).sessions.get(self.session_id())
if session is None:
self.send_body(400, b"missing session")
return
type(self).sequence += 1
fixture = type(self).next_fixture
type(self).next_fixture = None
if fixture is None:
code = str(10000 + type(self).sequence)
image = PNG + b"-" + code.encode()
else:
code, image = fixture
session["code"] = code
session["image"] = image
type(self).latest_code = code
self.send_body(
200,
image,
content_type="image/png",
headers={"Set-Cookie": "captcha_seen=1; Path=/"},
)
return
self.send_body(404, b"not found")
def do_POST(self):
path = urllib.parse.urlsplit(self.path).path
if not path.startswith("/panel/login/"):
self.send_body(404, b"not found")
return
length = int(self.headers.get("Content-Length", "0"))
values = urllib.parse.parse_qs(
self.rfile.read(length).decode(),
keep_blank_values=True,
)
session = type(self).sessions.get(self.session_id())
if (
session is None
or "captcha_seen=1" not in self.headers.get("Cookie", "")
or values.get("redirect") != [""]
or values.get("LoginFromWeb") != ["1"]
):
self.send_body(400, b"invalid login request")
return
if values.get("captcha", [""])[0] != session.get("code"):
session["message"] = "کد امنیتی وارد شده نادرست است."
self.send_body(
302,
b"",
headers={"Location": "/panel/"},
)
return
if (
type(self).reject_credentials
or values.get("username", [""])[0] != "username"
or values.get("password", [""])[0] != "password"
):
session["message"] = "نام کاربری یا گذرواژه نادرست است."
self.send_body(
302,
b"",
headers={"Location": "/panel/"},
)
return
session["authenticated"] = True
self.send_body(302, b"", headers={"Location": "/panel/"})
panel_server = http.server.ThreadingHTTPServer(
("127.0.0.1", 0),
PanelHandler,
)
panel_thread = threading.Thread(
target=panel_server.serve_forever,
daemon=True,
)
panel_thread.start()
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
dataset = root / "dataset"
image = dataset / "images" / "000000" / "000000000.png"
image.parent.mkdir(parents=True)
web_png = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwC"
"AAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
old_hash = hashlib.sha256(PNG).hexdigest()
old_image = self.make_dataset(
dataset,
label="123",
verified="1",
digest=old_hash,
)
image.write_bytes(web_png)
outside_image = root / "outside.png"
outside_image.write_bytes(web_png)
csv_path = dataset / "labels.csv"
with csv_path.open("w", newline="", encoding="utf-8") as output:
writer = csv.DictWriter(
output,
fieldnames=["filename", "label", "batch_id", "verified", "hash"],
)
writer.writeheader()
for index, (label, verified) in enumerate(
[("123", "1"), ("", "0"), ("", "0")]
):
writer.writerow(
{
"filename": (
"../outside.png"
if index == 2
else image.relative_to(dataset).as_posix()
),
"label": label,
"batch_id": "0",
"verified": verified,
"hash": hashlib.sha256(web_png + str(index).encode()).hexdigest(),
}
)
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
port = listener.getsockname()[1]
collector_port = listener.getsockname()[1]
environment = os.environ.copy()
for name in (
"PANEL_LOGIN_USERNAME",
"PANEL_LOGIN_PASSWORD",
"PANEL_USERNAME",
"PANEL_PASSWORD",
):
environment.pop(name, None)
environment["OCR_DATASET_DIR"] = str(dataset)
server = subprocess.Popen(
environment["PANEL_BASE_URL"] = (
f"http://127.0.0.1:{panel_server.server_port}"
)
environment["PANEL_REQUEST_TIMEOUT"] = "2"
collector = subprocess.Popen(
[
php,
"-S",
f"127.0.0.1:{port}",
f"127.0.0.1:{collector_port}",
"-t",
str(PROJECT / "web"),
],
@@ -268,166 +481,214 @@ class ToolTests(unittest.TestCase):
text=True,
env=environment,
)
base_url = f"http://127.0.0.1:{port}/"
base_url = f"http://127.0.0.1:{collector_port}/"
opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())
)
def get(path: str = "") -> tuple[int, bytes, dict[str, str]]:
request = urllib.request.Request(base_url + path)
with urllib.request.urlopen(request, timeout=10) as response:
with opener.open(base_url + path, timeout=10) as response:
return response.status, response.read(), dict(response.headers)
def post(values: dict[str, str]) -> tuple[int, bytes, dict[str, str]]:
body = urllib.parse.urlencode(values).encode()
request = urllib.request.Request(base_url, data=body, method="POST")
with urllib.request.urlopen(request, timeout=20) as response:
def post(
values: dict[str, str],
) -> tuple[int, bytes, dict[str, str]]:
request = urllib.request.Request(
base_url,
data=urllib.parse.urlencode(values).encode(),
method="POST",
headers={"Accept": "application/json"},
)
with opener.open(request, timeout=15) as response:
return response.status, response.read(), dict(response.headers)
try:
for _ in range(50):
for _ in range(60):
try:
status, page, _ = get()
status, page, headers = get()
if status == 200:
break
except urllib.error.URLError:
time.sleep(0.05)
else:
self.fail("PHP development server did not start")
self.fail("PHP collector server did not start")
self.assertIn(b"Initialize verifier", page)
status, payload, _ = post({"action": "initialize"})
self.assertEqual(status, 200)
self.assertIn(b'"done":true', payload)
self.assertIn(b"Captcha collector", page)
self.assertIn(b'inputmode="numeric"', page)
self.assertIn(b'enterkeyhint="go"', page)
self.assertIn("no-store", headers["Cache-Control"])
self.assertIn("default-src 'self'", headers["Content-Security-Policy"])
_, page, _ = get()
self.assertIn(b'OCR verifier', page)
self.assertRegex(page, rb'name="row_id" value="1"')
self.assertRegex(page, rb'name="revision" value="0"')
csrf = re.search(
rb'name="csrf_token" value="([a-f0-9]{64})"',
page,
)
challenge = re.search(
rb'name="challenge_id" value="([a-f0-9]{32})"',
page,
)
self.assertIsNotNone(csrf)
self.assertIsNotNone(challenge)
csrf_token = csrf.group(1).decode()
first_challenge = challenge.group(1).decode()
status, image_body, headers = get("?action=image&id=1")
self.assertEqual(status, 200)
self.assertEqual(image_body, web_png)
self.assertEqual(headers["Content-Type"], "image/png")
_, first_image, image_headers = get(
f"?action=captcha&id={first_challenge}"
)
self.assertEqual(image_headers["Content-Type"], "image/png")
with self.assertRaises(urllib.error.HTTPError) as invalid:
post(
try:
_, rejected_body, _ = post(
{
"action": "save",
"row_id": "1",
"revision": "0",
"mode": "queue",
"label": "12x",
"action": "submit",
"csrf_token": csrf_token,
"challenge_id": first_challenge,
"label": "99999",
}
)
self.assertEqual(invalid.exception.code, 422)
self.assertIn(b"Enter digits only", invalid.exception.read())
invalid.exception.close()
_, page, _ = post(
{
"action": "save",
"row_id": "1",
"revision": "0",
"mode": "queue",
"label": "۱۲۳۴",
}
)
self.assertIn(b"Label saved", page)
self.assertRegex(page, rb'name="row_id" value="2"')
self.assertRegex(page, rb'name="revision" value="1"')
except urllib.error.HTTPError as problem:
details = problem.read().decode(errors="replace")
problem.close()
self.fail(f"captcha rejection returned {problem.code}: {details}")
rejected = json.loads(rejected_body)
self.assertEqual(rejected["outcome"], "rejected")
self.assertNotEqual(rejected["challenge"]["id"], first_challenge)
with csv_path.open(newline="", encoding="utf-8") as source:
self.assertEqual(len(list(csv.DictReader(source))), 1)
with self.assertRaises(urllib.error.HTTPError) as stale:
post(
{
"action": "save",
"row_id": "1",
"revision": "0",
"mode": "queue",
"label": "999",
"action": "submit",
"csrf_token": csrf_token,
"challenge_id": first_challenge,
"label": "99999",
}
)
self.assertEqual(stale.exception.code, 409)
self.assertIn(b"stale", stale.exception.read())
stale.exception.close()
with self.assertRaises(urllib.error.HTTPError) as escaped_image:
get("?action=image&id=2")
self.assertEqual(escaped_image.exception.code, 404)
escaped_image.exception.close()
_, page, _ = post(
accepted_challenge = rejected["challenge"]["id"]
_, accepted_image, _ = get(
f"?action=captcha&id={accepted_challenge}"
)
ascii_code = PanelHandler.latest_code
persian_code = ascii_code.translate(
str.maketrans("0123456789", "۰۱۲۳۴۵۶۷۸۹")
)
PanelHandler.next_fixture = (ascii_code, accepted_image)
_, saved_body, _ = post(
{
"action": "skip",
"row_id": "2",
"revision": "1",
"action": "submit",
"csrf_token": csrf_token,
"challenge_id": accepted_challenge,
"label": persian_code,
}
)
self.assertIn(b"Image skipped", page)
self.assertRegex(page, rb'name="row_id" value="2"')
saved = json.loads(saved_body)
self.assertEqual(saved["outcome"], "saved")
self.assertEqual(saved["saved_this_session"], 1)
_, edit_page, _ = get("?edit=1")
revision = re.search(rb'name="revision" value="(\d+)"', edit_page)
self.assertIsNotNone(revision)
_, corrected_page, _ = post(
{
"action": "save",
"row_id": "1",
"revision": revision.group(1).decode(),
"mode": "edit",
"label": "4567",
}
)
self.assertIn(b"corrected", corrected_page)
state = sqlite3.connect(dataset / "verification.sqlite")
try:
saved = state.execute(
"SELECT label, verified, dirty FROM labels WHERE id = 1"
).fetchone()
pending = state.execute(
"SELECT value FROM metadata WHERE key = 'pending_count'"
).fetchone()
finally:
state.close()
self.assertEqual(saved, ("4567", 1, 1))
self.assertEqual(pending, ("1",))
_, synced_page, _ = post({"action": "sync"})
self.assertIn(b"updated atomically", synced_page)
with csv_path.open(newline="", encoding="utf-8") as source:
rows = list(csv.DictReader(source))
self.assertEqual(rows[1]["label"], "4567")
self.assertEqual(len(rows), 2)
self.assertEqual(rows[0]["filename"], old_image.relative_to(dataset).as_posix())
self.assertEqual(rows[1]["label"], ascii_code)
self.assertEqual(rows[1]["batch_id"], "panel")
self.assertEqual(rows[1]["verified"], "1")
self.assertEqual(rows[2]["verified"], "0")
self.assertEqual(
rows[1]["hash"],
hashlib.sha256(accepted_image).hexdigest(),
)
self.assertEqual(
(dataset / rows[1]["filename"]).read_bytes(),
accepted_image,
)
state = sqlite3.connect(dataset / "verification.sqlite")
try:
pending = state.execute(
"SELECT value FROM metadata WHERE key = 'pending_count'"
).fetchone()
duplicate_challenge = saved["challenge"]["id"]
_, duplicate_image, _ = get(
f"?action=captcha&id={duplicate_challenge}"
)
self.assertEqual(duplicate_image, accepted_image)
_, duplicate_body, _ = post(
{
"action": "submit",
"csrf_token": csrf_token,
"challenge_id": duplicate_challenge,
"label": ascii_code,
}
)
duplicate = json.loads(duplicate_body)
self.assertEqual(duplicate["outcome"], "duplicate")
self.assertEqual(duplicate["saved_this_session"], 1)
with csv_path.open(newline="", encoding="utf-8") as source:
self.assertEqual(len(list(csv.DictReader(source))), 2)
# Removing the old dataset must not require resetting collector state.
next_challenge = duplicate["challenge"]["id"]
_, recreated_image, _ = get(
f"?action=captcha&id={next_challenge}"
)
recreate_code = PanelHandler.latest_code
shutil.rmtree(dataset)
_, recreated_body, _ = post(
{
"action": "submit",
"csrf_token": csrf_token,
"challenge_id": next_challenge,
"label": recreate_code,
}
)
recreated = json.loads(recreated_body)
self.assertEqual(recreated["outcome"], "saved")
with csv_path.open(newline="", encoding="utf-8") as source:
recreated_rows = list(csv.DictReader(source))
self.assertEqual(len(recreated_rows), 1)
self.assertEqual(
(dataset / recreated_rows[0]["filename"]).read_bytes(),
recreated_image,
)
PanelHandler.reject_credentials = True
credential_challenge = recreated["challenge"]["id"]
credential_code = PanelHandler.latest_code
with self.assertRaises(urllib.error.HTTPError) as credentials:
post(
{
"action": "submit",
"csrf_token": csrf_token,
"challenge_id": credential_challenge,
"label": credential_code,
}
)
self.assertEqual(credentials.exception.code, 502)
credential_payload = json.loads(credentials.exception.read())
self.assertIn("username or password", credential_payload["error"])
self.assertIsNone(credential_payload["challenge"])
credentials.exception.close()
with csv_path.open(newline="", encoding="utf-8") as source:
self.assertEqual(len(list(csv.DictReader(source))), 1)
node = shutil.which("node")
if node is not None:
syntax = subprocess.run(
[node, "--check", str(PROJECT / "web" / "app.js")],
text=True,
capture_output=True,
)
self.assertEqual(syntax.returncode, 0, syntax.stderr)
finally:
state.close()
self.assertEqual(pending, ("0",))
with self.assertRaises(urllib.error.HTTPError) as missing:
get("?action=image&id=999")
self.assertEqual(missing.exception.code, 404)
missing.exception.close()
with csv_path.open("a", encoding="utf-8") as output:
output.write("\n")
with self.assertRaises(urllib.error.HTTPError) as conflict:
get()
self.assertEqual(conflict.exception.code, 409)
self.assertIn(b"The source CSV changed", conflict.exception.read())
conflict.exception.close()
finally:
server.terminate()
collector.terminate()
try:
server.wait(timeout=5)
collector.wait(timeout=5)
except subprocess.TimeoutExpired:
server.kill()
server.wait(timeout=5)
if server.stderr is not None:
server.stderr.close()
collector.kill()
collector.wait(timeout=5)
if collector.stderr is not None:
collector.stderr.close()
panel_server.shutdown()
panel_server.server_close()
panel_thread.join(timeout=5)
if __name__ == "__main__":
+249
View File
@@ -0,0 +1,249 @@
:root {
color-scheme: dark;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #09111d;
color: #eaf1fb;
--panel: #111d2d;
--line: #26364b;
--muted: #91a2b8;
--accent: #67e8b8;
--accent-dark: #073c31;
--danger: #ff9a9a;
}
* {
box-sizing: border-box;
}
body {
min-height: 100dvh;
margin: 0;
background:
radial-gradient(circle at top, rgba(46, 91, 126, .28), transparent 36rem),
#09111d;
}
button,
input {
font: inherit;
}
.shell {
width: min(100% - 2rem, 42rem);
margin: 0 auto;
padding: max(1.25rem, env(safe-area-inset-top)) 0 max(2rem, env(safe-area-inset-bottom));
}
.topbar {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1.2rem;
}
.eyebrow {
margin: 0 0 .2rem;
color: var(--accent);
font-size: .75rem;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
}
h1,
h2,
p {
margin-top: 0;
}
h1 {
margin-bottom: 0;
font-size: clamp(1.55rem, 6vw, 2.2rem);
}
.counter {
flex: 0 0 auto;
text-align: right;
}
.counter strong {
display: block;
color: var(--accent);
font-size: 1.5rem;
line-height: 1;
}
.counter span,
.privacy {
color: var(--muted);
font-size: .78rem;
}
.status {
min-height: 2.8rem;
margin-bottom: .9rem;
padding: .75rem .9rem;
border: 1px solid rgba(103, 232, 184, .24);
border-radius: .8rem;
background: rgba(103, 232, 184, .08);
color: #c7f9e8;
}
.status.error {
border-color: rgba(255, 154, 154, .3);
background: rgba(255, 99, 99, .09);
color: var(--danger);
}
.card {
padding: clamp(1rem, 4vw, 1.6rem);
border: 1px solid var(--line);
border-radius: 1.15rem;
background: rgba(17, 29, 45, .96);
box-shadow: 0 1.5rem 4rem rgba(0, 0, 0, .28);
}
.image-stage {
display: grid;
min-height: 9.5rem;
place-items: center;
margin-bottom: 1.2rem;
border: 1px solid var(--line);
border-radius: .9rem;
background: #f3f6fa;
overflow: hidden;
}
.image-stage img {
width: min(100%, 27.5rem);
height: auto;
image-rendering: auto;
}
label {
display: block;
margin-bottom: .45rem;
color: var(--muted);
font-size: .86rem;
font-weight: 700;
}
.entry-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: .7rem;
}
input {
min-width: 0;
height: 3.35rem;
padding: 0 .95rem;
border: 1px solid #39506c;
border-radius: .75rem;
outline: 0;
background: #09131f;
color: #fff;
font-size: 1.25rem;
font-variant-numeric: tabular-nums;
letter-spacing: .08em;
}
input:focus {
border-color: var(--accent);
box-shadow: 0 0 0 .2rem rgba(103, 232, 184, .12);
}
button,
.button-link {
min-height: 3.35rem;
padding: 0 1rem;
border: 0;
border-radius: .75rem;
cursor: pointer;
font-weight: 800;
text-decoration: none;
}
button:disabled {
cursor: wait;
opacity: .55;
}
.primary {
background: var(--accent);
color: var(--accent-dark);
}
.secondary {
width: 100%;
min-height: 2.8rem;
margin-top: .7rem;
border: 1px solid var(--line);
background: transparent;
color: var(--muted);
}
.button-link {
display: inline-flex;
align-items: center;
}
.unavailable {
padding: 2rem 1rem;
text-align: center;
}
.unavailable p {
color: var(--muted);
}
.privacy {
margin: .9rem 0 0;
text-align: center;
}
[hidden] {
display: none !important;
}
@media (max-width: 560px) {
.shell {
width: min(100% - 1rem, 42rem);
padding-top: max(.7rem, env(safe-area-inset-top));
}
.topbar {
align-items: center;
margin-bottom: .7rem;
}
.counter span {
display: none;
}
.card {
padding: .8rem;
border-radius: .9rem;
}
.image-stage {
min-height: 7.7rem;
margin-bottom: .8rem;
}
.entry-row {
grid-template-columns: minmax(0, 1fr) 7.3rem;
gap: .45rem;
}
input,
button {
height: 3.2rem;
}
.primary {
padding: 0 .65rem;
font-size: .88rem;
}
}
+117
View File
@@ -0,0 +1,117 @@
(() => {
const answerForm = document.querySelector('#answer-form');
const nextForm = document.querySelector('#next-form');
const input = document.querySelector('#label');
const image = document.querySelector('#captcha-image');
const status = document.querySelector('#status');
const savedCount = document.querySelector('#saved-count');
const submitButton = document.querySelector('#submit-button');
let busy = false;
if (!answerForm || !nextForm || !input || !image || !status || !submitButton) {
return;
}
const digitMap = {
'۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4',
'۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9',
'٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4',
'٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9',
};
const showStatus = (message, isError = false) => {
status.hidden = false;
status.textContent = message;
status.classList.toggle('error', isError);
};
const setBusy = value => {
busy = value;
submitButton.disabled = value;
nextForm.querySelector('button').disabled = value;
};
const applyChallenge = challenge => {
if (!challenge) {
answerForm.hidden = true;
image.closest('.image-stage').hidden = true;
nextForm.querySelector('button').textContent = 'Try another captcha';
return;
}
answerForm.hidden = false;
image.closest('.image-stage').hidden = false;
nextForm.querySelector('button').textContent = 'New captcha';
answerForm.elements.challenge_id.value = challenge.id;
image.src = `${challenge.image_url}&nonce=${Date.now()}`;
input.value = '';
input.focus({preventScroll: true});
};
const submit = async form => {
if (busy) return;
setBusy(true);
try {
const response = await fetch(form.action, {
method: 'POST',
body: new FormData(form),
headers: {'Accept': 'application/json'},
});
let payload;
try {
payload = await response.json();
} catch {
throw new Error('The server returned an invalid response.');
}
if (!response.ok) {
const problem = new Error(payload.error || 'The request failed.');
problem.payload = payload;
throw problem;
}
if (savedCount) {
savedCount.textContent = new Intl.NumberFormat().format(
payload.saved_this_session
);
}
applyChallenge(payload.challenge);
showStatus(
payload.warning
? `${payload.message} ${payload.warning}`
: payload.message,
Boolean(payload.warning),
);
} catch (problem) {
if (
problem.payload
&& Object.prototype.hasOwnProperty.call(problem.payload, 'challenge')
) {
applyChallenge(problem.payload.challenge);
}
showStatus(problem.message || 'Connection error. Refresh and try again.', true);
if (!answerForm.hidden) {
input.focus({preventScroll: true});
input.select();
}
} finally {
setBusy(false);
}
};
input.addEventListener('input', () => {
input.value = Array.from(
input.value,
character => digitMap[character] ?? character,
).join('').replace(/[^0-9]/g, '');
});
answerForm.addEventListener('submit', event => {
event.preventDefault();
submit(answerForm);
});
nextForm.addEventListener('submit', event => {
event.preventDefault();
submit(nextForm);
});
input.focus();
})();
+942
View File
@@ -0,0 +1,942 @@
<?php
declare(strict_types=1);
const DATASET_COLUMNS = ['filename', 'label', 'batch_id', 'verified', 'hash'];
const MAX_PANEL_RESPONSE_BYTES = 2_000_000;
const CHALLENGE_MAX_AGE = 240;
final class CollectorError extends RuntimeException
{
public function __construct(
string $message,
public readonly int $status = 400,
) {
parent::__construct($message);
}
}
final class PanelResponse
{
/**
* @param array<string, list<string>> $headers
*/
public function __construct(
public readonly int $status,
public readonly array $headers,
public readonly string $body,
) {
}
public function header(string $name): ?string
{
$values = $this->headers[strtolower($name)] ?? [];
return $values[0] ?? null;
}
/** @return list<string> */
public function headers(string $name): array
{
return $this->headers[strtolower($name)] ?? [];
}
}
/**
* @return array<string, string>
*/
function readProjectEnvironment(string $path): array
{
if (!file_exists($path)) {
return [];
}
if (!is_file($path) || !is_readable($path)) {
throw new CollectorError('The project .env file is not readable.', 500);
}
$contents = @file_get_contents($path);
if ($contents === false) {
throw new CollectorError('Could not read the project .env file.', 500);
}
if (strlen($contents) > 65_536) {
throw new CollectorError('The project .env file is unexpectedly large.', 500);
}
$supported = array_fill_keys([
'PANEL_BASE_URL',
'PANEL_LOGIN_USERNAME',
'PANEL_LOGIN_PASSWORD',
'PANEL_REQUEST_TIMEOUT',
'OCR_DATASET_DIR',
], true);
$values = [];
$lines = preg_split('/\R/', $contents);
if ($lines === false) {
throw new CollectorError('Could not parse the project .env file.', 500);
}
foreach ($lines as $index => $line) {
if ($index === 0) {
$line = preg_replace('/^\xEF\xBB\xBF/', '', $line) ?? $line;
}
$trimmed = trim($line);
if ($trimmed === '' || str_starts_with($trimmed, '#')) {
continue;
}
if (
preg_match(
'/^(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*(.*)$/D',
$trimmed,
$matches,
) !== 1
) {
throw new CollectorError(
'Invalid project .env syntax on line ' . ($index + 1) . '.',
500,
);
}
$name = $matches[1];
if (!isset($supported[$name])) {
continue;
}
$values[$name] = parseProjectEnvironmentValue(
$matches[2],
$index + 1,
);
}
return $values;
}
function parseProjectEnvironmentValue(string $raw, int $line): string
{
$raw = ltrim($raw);
if ($raw === '') {
return '';
}
$quote = $raw[0];
if ($quote !== '"' && $quote !== "'") {
return trim(preg_replace('/\s+#.*$/', '', $raw) ?? $raw);
}
$value = '';
$escaped = false;
$length = strlen($raw);
for ($index = 1; $index < $length; $index++) {
$character = $raw[$index];
if ($quote === '"' && $escaped) {
$value .= match ($character) {
'n' => "\n",
'r' => "\r",
't' => "\t",
'"', '\\', '$' => $character,
default => '\\' . $character,
};
$escaped = false;
continue;
}
if ($quote === '"' && $character === '\\') {
$escaped = true;
continue;
}
if ($character !== $quote) {
$value .= $character;
continue;
}
$remainder = trim(substr($raw, $index + 1));
if ($remainder !== '' && !str_starts_with($remainder, '#')) {
throw new CollectorError(
"Invalid project .env value on line {$line}.",
500,
);
}
return $value;
}
throw new CollectorError(
"Unclosed quote in project .env on line {$line}.",
500,
);
}
function collectorSetting(
string $name,
array $projectEnvironment,
string $default = '',
): string {
$serverValue = $_SERVER[$name] ?? null;
if (is_string($serverValue) && $serverValue !== '') {
return $serverValue;
}
$processValue = getenv($name);
if ($processValue !== false && $processValue !== '') {
return $processValue;
}
$projectValue = $projectEnvironment[$name] ?? '';
return $projectValue !== '' ? $projectValue : $default;
}
function collectorConfig(?string $projectEnvPath = null): array
{
$projectEnvironment = readProjectEnvironment(
$projectEnvPath ?? dirname(__DIR__) . '/.env',
);
$configuredDataset = collectorSetting(
'OCR_DATASET_DIR',
$projectEnvironment,
);
$timeoutValue = collectorSetting(
'PANEL_REQUEST_TIMEOUT',
$projectEnvironment,
'10',
);
$timeout = filter_var($timeoutValue, FILTER_VALIDATE_INT);
return [
'dataset' => rtrim(
$configuredDataset !== '' ? $configuredDataset : dirname(__DIR__) . '/dataset',
DIRECTORY_SEPARATOR,
),
'panel_base_url' => rtrim(
collectorSetting(
'PANEL_BASE_URL',
$projectEnvironment,
'https://internet.tci.ir',
),
'/',
),
'panel_username' => collectorSetting(
'PANEL_LOGIN_USERNAME',
$projectEnvironment,
'username',
),
'panel_password' => collectorSetting(
'PANEL_LOGIN_PASSWORD',
$projectEnvironment,
'password',
),
'timeout' => $timeout === false ? 10 : max(1, min(60, $timeout)),
];
}
function sendSecurityHeaders(): void
{
header_remove('X-Powered-By');
header('Cache-Control: no-store, max-age=0');
header('Pragma: no-cache');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header("Content-Security-Policy: default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'");
header('Referrer-Policy: no-referrer');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
}
function h(string|int|null $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function jsonResponse(array $payload, int $status = 200): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
exit;
}
function redirect(string $location): never
{
header('Location: ' . $location, true, 303);
exit;
}
function wantsJson(): bool
{
return str_contains(
strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')),
'application/json',
);
}
function scalarRequestValue(string $key, int $maxLength): ?string
{
$value = $_POST[$key] ?? $_GET[$key] ?? null;
return is_string($value) && strlen($value) <= $maxLength ? $value : null;
}
function scalarPostValue(string $key, int $maxLength): ?string
{
$value = $_POST[$key] ?? null;
return is_string($value) && strlen($value) <= $maxLength ? $value : null;
}
function localCsrfToken(): string
{
if (!isset($_SESSION['local_csrf']) || !is_string($_SESSION['local_csrf'])) {
$_SESSION['local_csrf'] = bin2hex(random_bytes(32));
}
return $_SESSION['local_csrf'];
}
function requireLocalCsrf(): void
{
$submitted = scalarPostValue('csrf_token', 64);
if ($submitted === null || !hash_equals(localCsrfToken(), $submitted)) {
throw new CollectorError('This page has expired. Refresh it and try again.', 403);
}
}
function normalizeAnswer(string $answer): string
{
$answer = strtr(trim($answer), [
'۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4',
'۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9',
'٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4',
'٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9',
]);
if ($answer === '' || strlen($answer) > 16 || preg_match('/^[0-9]+$/D', $answer) !== 1) {
throw new CollectorError('Enter digits only.', 422);
}
return $answer;
}
function panelUrl(array $config, string $path): string
{
$base = $config['panel_base_url'];
$parts = parse_url($base);
if (
$parts === false
|| !isset($parts['scheme'], $parts['host'])
|| !in_array(strtolower((string) $parts['scheme']), ['http', 'https'], true)
|| isset($parts['user'])
|| isset($parts['pass'])
|| isset($parts['query'])
|| isset($parts['fragment'])
) {
throw new CollectorError('PANEL_BASE_URL must be a valid HTTP or HTTPS URL.', 500);
}
$scheme = strtolower((string) $parts['scheme']);
$host = strtolower((string) $parts['host']);
$port = isset($parts['port']) ? ':' . (int) $parts['port'] : '';
$origin = $scheme . '://' . $parts['host'] . $port;
if (str_starts_with($path, '//')) {
$url = $scheme . ':' . $path;
} elseif (preg_match('#^https?://#i', $path) === 1) {
$url = $path;
} elseif (str_starts_with($path, '/')) {
$url = $origin . $path;
} else {
$basePath = (string) ($parts['path'] ?? '');
$directory = $basePath === '' || $basePath === '/'
? '/panel/'
: rtrim($basePath, '/') . '/';
$url = $origin . $directory . $path;
}
$target = parse_url($url);
if ($target === false) {
throw new CollectorError('The panel returned an unsafe URL.', 502);
}
$targetPort = isset($target['port']) ? ':' . (int) $target['port'] : '';
if (
!isset($target['scheme'], $target['host'])
|| strtolower((string) $target['scheme']) !== $scheme
|| strtolower((string) $target['host']) !== $host
|| $targetPort !== $port
|| isset($target['user'])
|| isset($target['pass'])
|| isset($target['fragment'])
) {
throw new CollectorError('The panel returned an unsafe URL.', 502);
}
return $url;
}
/**
* @param list<string> $headers
*/
function panelRequest(
array $config,
string $method,
string $path,
array $headers = [],
string $body = '',
): PanelResponse {
foreach ($headers as $header) {
if (str_contains($header, "\r") || str_contains($header, "\n")) {
throw new CollectorError('Unsafe outbound panel header.', 500);
}
}
$headers[] = 'Accept: text/html, image/*;q=0.9, */*;q=0.5';
$headers[] = 'User-Agent: tci-ocr-panel-collector/1.0';
$options = [
'http' => [
'method' => strtoupper($method),
'header' => implode("\r\n", $headers),
'content' => $body,
'ignore_errors' => true,
'follow_location' => 0,
'timeout' => $config['timeout'],
'protocol_version' => 1.1,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
];
$stream = @fopen(panelUrl($config, $path), 'rb', false, stream_context_create($options));
if ($stream === false) {
$details = error_get_last();
$message = is_array($details) ? (string) ($details['message'] ?? '') : '';
error_log('Panel request failed: ' . $message);
throw new CollectorError('Could not connect to the panel.', 502);
}
try {
$responseBody = stream_get_contents($stream, MAX_PANEL_RESPONSE_BYTES + 1);
$metadata = stream_get_meta_data($stream);
} finally {
fclose($stream);
}
if ($responseBody === false || ($metadata['timed_out'] ?? false) === true) {
throw new CollectorError('The panel request timed out.', 504);
}
if (strlen($responseBody) > MAX_PANEL_RESPONSE_BYTES) {
throw new CollectorError('The panel returned an unexpectedly large response.', 502);
}
$rawHeaders = $metadata['wrapper_data'] ?? [];
if (!is_array($rawHeaders)) {
throw new CollectorError('The panel returned malformed HTTP headers.', 502);
}
$status = 0;
$parsedHeaders = [];
foreach ($rawHeaders as $line) {
if (!is_string($line)) {
continue;
}
if (preg_match('#^HTTP/\S+\s+(\d{3})#i', $line, $matches) === 1) {
$status = (int) $matches[1];
$parsedHeaders = [];
continue;
}
$separator = strpos($line, ':');
if ($separator === false) {
continue;
}
$name = substr($line, 0, $separator);
$value = substr($line, $separator + 1);
if (trim($name) === '') {
continue;
}
$parsedHeaders[strtolower(trim($name))][] = trim($value);
}
if ($status === 0) {
throw new CollectorError('The panel returned a response without an HTTP status.', 502);
}
return new PanelResponse($status, $parsedHeaders, $responseBody);
}
/** @return array<string, string> */
function panelCookieMap(string $cookieHeader): array
{
$cookies = [];
foreach (explode(';', $cookieHeader) as $pair) {
$separator = strpos($pair, '=');
if ($separator === false) {
continue;
}
$name = trim(substr($pair, 0, $separator));
$value = trim(substr($pair, $separator + 1));
if (
preg_match('/^[A-Za-z0-9_.-]+$/D', $name) === 1
&& preg_match('/[\x00-\x20\x7f;]/', $value) !== 1
) {
$cookies[$name] = $value;
}
}
return $cookies;
}
function mergePanelCookies(
string $cookieHeader,
PanelResponse $response,
bool $required = false,
): string {
$cookies = panelCookieMap($cookieHeader);
foreach ($response->headers('set-cookie') as $header) {
$pair = trim(explode(';', $header, 2)[0]);
$separator = strpos($pair, '=');
if ($separator === false) {
continue;
}
$name = substr($pair, 0, $separator);
$value = substr($pair, $separator + 1);
if (
preg_match('/^[A-Za-z0-9_.-]+$/D', $name) !== 1
|| preg_match('/[\x00-\x20\x7f;]/', $value) === 1
) {
continue;
}
$cookies[$name] = $value;
}
if ($required && $cookies === []) {
throw new CollectorError('The panel did not create a login session.', 502);
}
$parts = [];
foreach ($cookies as $name => $value) {
$parts[] = $name . '=' . $value;
}
return implode('; ', $parts);
}
function extractPanelFormAction(string $html): string
{
$patterns = [
'/<form\b[^>]*\baction\s*=\s*(["\'])(.*?)\1/is',
'/<form\b[^>]*\baction\s*=\s*([^\s>"\']+)/is',
];
foreach ($patterns as $pattern) {
if (preg_match($pattern, $html, $matches) === 1) {
$value = html_entity_decode(
$matches[count($matches) - 1],
ENT_QUOTES | ENT_HTML5,
'UTF-8',
);
if ($value !== '') {
return $value;
}
}
}
throw new CollectorError('Could not find the panel login form action.', 502);
}
function extractPanelCaptchaUrl(string $html): string
{
if (
preg_match(
'/<img\b(?=[^>]*\bid\s*=\s*(["\'])loginCaptchaImage\1)[^>]*\bsrc\s*=\s*(["\'])(.*?)\2/is',
$html,
$matches,
) !== 1
) {
throw new CollectorError('Could not find the panel captcha image.', 502);
}
$url = html_entity_decode($matches[3], ENT_QUOTES | ENT_HTML5, 'UTF-8');
if ($url === '') {
throw new CollectorError('The panel returned an empty captcha URL.', 502);
}
return $url;
}
function imageType(string $bytes, ?string $contentType): array
{
$mediaType = strtolower(trim(explode(';', (string) $contentType, 2)[0]));
$types = [
'image/jpeg' => ['extension' => '.jpg', 'magic' => str_starts_with($bytes, "\xff\xd8\xff")],
'image/png' => ['extension' => '.png', 'magic' => str_starts_with($bytes, "\x89PNG\r\n\x1a\n")],
'image/gif' => ['extension' => '.gif', 'magic' => str_starts_with($bytes, 'GIF87a') || str_starts_with($bytes, 'GIF89a')],
'image/bmp' => ['extension' => '.bmp', 'magic' => str_starts_with($bytes, 'BM')],
'image/webp' => [
'extension' => '.webp',
'magic' => strlen($bytes) >= 12
&& substr($bytes, 0, 4) === 'RIFF'
&& substr($bytes, 8, 4) === 'WEBP',
],
];
$type = $types[$mediaType] ?? null;
if ($type === null || $type['magic'] !== true) {
throw new CollectorError('The panel returned an unsupported captcha image.', 502);
}
return ['mime' => $mediaType, 'extension' => $type['extension']];
}
function fetchPanelChallenge(array $config): array
{
$login = panelRequest($config, 'GET', '/panel/');
if ($login->status !== 200) {
throw new CollectorError('The panel login page is unavailable.', 502);
}
$cookie = mergePanelCookies('', $login, true);
$loginUrl = panelUrl($config, extractPanelFormAction($login->body));
$captchaUrl = panelUrl($config, extractPanelCaptchaUrl($login->body));
$captcha = panelRequest(
$config,
'GET',
$captchaUrl,
['Cookie: ' . $cookie],
);
if ($captcha->status !== 200 || $captcha->body === '') {
throw new CollectorError('The panel captcha is unavailable.', 502);
}
$cookie = mergePanelCookies($cookie, $captcha);
$type = imageType($captcha->body, $captcha->header('content-type'));
return [
'id' => bin2hex(random_bytes(16)),
'cookie' => $cookie,
'login_url' => $loginUrl,
'image' => $captcha->body,
'mime' => $type['mime'],
'extension' => $type['extension'],
'issued_at' => time(),
];
}
function challengeIsUsable(mixed $challenge): bool
{
return is_array($challenge)
&& isset(
$challenge['id'],
$challenge['cookie'],
$challenge['login_url'],
$challenge['image'],
$challenge['mime'],
$challenge['extension'],
$challenge['issued_at'],
)
&& is_string($challenge['id'])
&& is_string($challenge['cookie'])
&& is_string($challenge['login_url'])
&& is_string($challenge['image'])
&& is_string($challenge['mime'])
&& is_string($challenge['extension'])
&& is_int($challenge['issued_at'])
&& (time() - $challenge['issued_at']) <= CHALLENGE_MAX_AGE;
}
function ensurePanelChallenge(array $config, bool $force = false): array
{
$current = $_SESSION['panel_challenge'] ?? null;
if (!$force && challengeIsUsable($current)) {
return $current;
}
unset($_SESSION['panel_challenge']);
$challenge = fetchPanelChallenge($config);
$_SESSION['panel_challenge'] = $challenge;
return $challenge;
}
function challengeImageUrl(array $challenge): string
{
return '?action=captcha&id=' . rawurlencode($challenge['id']);
}
function challengePayload(array $challenge): array
{
return [
'id' => $challenge['id'],
'image_url' => challengeImageUrl($challenge),
];
}
function servePendingCaptcha(): never
{
$id = scalarRequestValue('id', 64) ?? '';
$challenge = $_SESSION['panel_challenge'] ?? null;
if (
!challengeIsUsable($challenge)
|| $id === ''
|| !hash_equals($challenge['id'], $id)
) {
throw new CollectorError('Captcha not found or expired.', 404);
}
header('Content-Type: ' . $challenge['mime']);
header('Content-Length: ' . strlen($challenge['image']));
echo $challenge['image'];
exit;
}
function validatePendingChallenge(array $config, string $challengeId, string $answer): array
{
$challenge = $_SESSION['panel_challenge'] ?? null;
if (
!challengeIsUsable($challenge)
|| $challengeId === ''
|| !hash_equals($challenge['id'], $challengeId)
) {
throw new CollectorError('This captcha has expired. Load a new one.', 409);
}
// A panel captcha can be used only once. Discard it before the network request
// so an ambiguous timeout can never cause a guessed label to be submitted twice.
unset($_SESSION['panel_challenge']);
$body = http_build_query([
'username' => $config['panel_username'],
'password' => $config['panel_password'],
'captcha' => $answer,
'redirect' => '',
'LoginFromWeb' => '1',
], '', '&', PHP_QUERY_RFC3986);
$response = panelRequest(
$config,
'POST',
$challenge['login_url'],
[
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: ' . strlen($body),
'Cookie: ' . $challenge['cookie'],
],
$body,
);
$location = $response->header('location');
if (
!in_array($response->status, [301, 302, 303, 307, 308], true)
|| $location === null
) {
throw new CollectorError(
'The panel returned an unexpected login response; nothing was saved.',
502,
);
}
$cookie = mergePanelCookies($challenge['cookie'], $response);
$result = panelRequest(
$config,
'GET',
panelUrl($config, $location),
['Cookie: ' . $cookie],
);
if ($result->status !== 200) {
throw new CollectorError(
'The panel login result page is unavailable; nothing was saved.',
502,
);
}
if (
stripos($result->body, 'logout') !== false
|| str_contains($result->body, 'خروج')
) {
return storeValidatedSample($config, $challenge, $answer);
}
if (
str_contains($result->body, 'کد امنیتی وارد شده نادرست است')
|| str_contains($result->body, 'کد امنیتی منقضی شده است')
) {
return ['stored' => false, 'rejected' => true];
}
if (
str_contains($result->body, 'loginCaptchaImage')
|| preg_match('/<input\b[^>]*\bname\s*=\s*(["\'])password\1/is', $result->body) === 1
) {
throw new CollectorError(
'The panel rejected the configured username or password.',
502,
);
}
throw new CollectorError(
'The panel returned an unexpected login response; nothing was saved.',
502,
);
}
function outcomeMessage(string $outcome): string
{
return match ($outcome) {
'saved' => 'Correct — saved.',
'duplicate' => 'Correct — already saved.',
'rejected' => 'Rejected — showing the next captcha.',
'skipped' => 'New captcha loaded.',
default => 'Ready.',
};
}
function ensureDirectory(string $path): void
{
if (!is_dir($path) && !@mkdir($path, 0775, true) && !is_dir($path)) {
throw new CollectorError("Cannot create dataset directory: {$path}", 500);
}
}
function writeAtomic(string $path, string $bytes): void
{
ensureDirectory(dirname($path));
$temporary = dirname($path) . DIRECTORY_SEPARATOR
. '.' . basename($path) . '.' . bin2hex(random_bytes(6)) . '.tmp';
$handle = @fopen($temporary, 'xb');
if ($handle === false) {
throw new CollectorError('Cannot create a temporary dataset file.', 500);
}
$completed = false;
try {
try {
$written = 0;
$length = strlen($bytes);
while ($written < $length) {
$count = fwrite($handle, substr($bytes, $written));
if ($count === false || $count === 0) {
throw new CollectorError('Could not write the captcha image.', 500);
}
$written += $count;
}
if (!fflush($handle) || (function_exists('fsync') && !fsync($handle))) {
throw new CollectorError('Could not safely flush the captcha image.', 500);
}
} finally {
fclose($handle);
}
if (!@rename($temporary, $path)) {
throw new CollectorError('Could not finalize the captcha image.', 500);
}
$completed = true;
} finally {
if (!$completed && is_file($temporary)) {
@unlink($temporary);
}
}
}
function csvContainsFilename($handle, string $filename): bool
{
rewind($handle);
fgetcsv($handle, null, ',', '"', '');
while (($row = fgetcsv($handle, null, ',', '"', '')) !== false) {
if (($row[0] ?? null) === $filename) {
return true;
}
}
return false;
}
function validateOrCreateCsvHeader($handle): void
{
$stats = fstat($handle);
if ($stats === false) {
throw new CollectorError('Could not inspect labels.csv.', 500);
}
if ((int) $stats['size'] === 0) {
if (fputcsv($handle, DATASET_COLUMNS, ',', '"', '', "\n") === false) {
throw new CollectorError('Could not initialize labels.csv.', 500);
}
return;
}
rewind($handle);
$header = fgetcsv($handle, null, ',', '"', '');
if ($header !== DATASET_COLUMNS) {
throw new CollectorError('labels.csv has an incompatible header.', 409);
}
}
function appendCsvRow($handle, array $row): void
{
if (fseek($handle, 0, SEEK_END) !== 0) {
throw new CollectorError('Could not seek to the end of labels.csv.', 500);
}
$position = ftell($handle);
if ($position === false) {
throw new CollectorError('Could not inspect labels.csv.', 500);
}
if ($position > 0) {
if (fseek($handle, -1, SEEK_END) !== 0) {
throw new CollectorError('Could not inspect the end of labels.csv.', 500);
}
$last = fread($handle, 1);
if (fseek($handle, 0, SEEK_END) !== 0) {
throw new CollectorError('Could not seek to the end of labels.csv.', 500);
}
if ($last !== "\n" && fwrite($handle, "\n") !== 1) {
throw new CollectorError('Could not repair the labels.csv line ending.', 500);
}
}
if (fputcsv($handle, $row, ',', '"', '', "\n") === false) {
throw new CollectorError('Could not append to labels.csv.', 500);
}
if (!fflush($handle) || (function_exists('fsync') && !fsync($handle))) {
throw new CollectorError('Could not safely flush labels.csv.', 500);
}
}
function storeValidatedSample(array $config, array $challenge, string $label): array
{
$dataset = $config['dataset'];
ensureDirectory($dataset);
$hash = hash('sha256', $challenge['image']);
$relative = 'images/panel/' . substr($hash, 0, 2) . '/'
. $hash . $challenge['extension'];
$imagePath = $dataset . DIRECTORY_SEPARATOR
. str_replace('/', DIRECTORY_SEPARATOR, $relative);
$marker = $dataset . DIRECTORY_SEPARATOR . '.panel-samples'
. DIRECTORY_SEPARATOR . substr($hash, 0, 2)
. DIRECTORY_SEPARATOR . $hash . '.done';
$csvPath = $dataset . DIRECTORY_SEPARATOR . 'labels.csv';
$lockPath = $dataset . DIRECTORY_SEPARATOR . '.panel-collector.lock';
$lock = @fopen($lockPath, 'c');
if ($lock === false || !flock($lock, LOCK_EX)) {
if (is_resource($lock)) {
fclose($lock);
}
throw new CollectorError('Could not lock the dataset for writing.', 503);
}
try {
$csv = @fopen($csvPath, 'c+b');
if ($csv === false) {
throw new CollectorError('Could not open labels.csv for writing.', 500);
}
try {
validateOrCreateCsvHeader($csv);
$csvChecked = false;
if (is_file($marker)) {
$csvChecked = true;
if (csvContainsFilename($csv, $relative)) {
return ['stored' => false, 'hash' => $hash, 'filename' => $relative];
}
if (!@unlink($marker)) {
throw new CollectorError('Could not repair stale panel sample state.', 500);
}
}
if (is_file($imagePath)) {
$existingHash = @hash_file('sha256', $imagePath);
if (!is_string($existingHash) || !hash_equals($hash, $existingHash)) {
throw new CollectorError('An existing captcha file failed its hash check.', 500);
}
if (!$csvChecked && csvContainsFilename($csv, $relative)) {
writeAtomic($marker, "saved\n");
return ['stored' => false, 'hash' => $hash, 'filename' => $relative];
}
} else {
writeAtomic($imagePath, $challenge['image']);
}
appendCsvRow($csv, [$relative, $label, 'panel', '1', $hash]);
writeAtomic($marker, "saved\n");
} finally {
fclose($csv);
}
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
return ['stored' => true, 'hash' => $hash, 'filename' => $relative];
}
+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="14" fill="#17181c"/>
<path
d="M9 21V13a4 4 0 0 1 4-4h8M43 9h8a4 4 0 0 1 4 4v8M55 43v8a4 4 0 0 1-4 4h-8M21 55h-8a4 4 0 0 1-4-4v-8"
fill="none"
stroke="#ffcc66"
stroke-linecap="round"
stroke-width="4"
/>
<g fill="#f7f6f2">
<rect x="24" y="16" width="15" height="4" rx="2"/>
<rect x="37" y="18" width="4" height="12" rx="2"/>
<rect x="24" y="30" width="15" height="4" rx="2"/>
<rect x="37" y="32" width="4" height="12" rx="2"/>
<rect x="24" y="44" width="15" height="4" rx="2"/>
</g>
<path d="M7 32h50" stroke="#fe8f62" stroke-linecap="round" stroke-width="2"/>
<circle cx="17" cy="32" r="3" fill="#ffcc66"/>
</svg>

After

Width:  |  Height:  |  Size: 761 B

+186 -1263
View File
File diff suppressed because it is too large. Load diff