Files
SimpleNav/admin/update_all.php
T

62 lines
2.0 KiB
PHP
Raw Normal View History

<?php
/**
* 简航 SimpleNav —— 一键“全部更新”(分批)。
* 批量刷新每个网站的图标与名称;**保留用户自定义的简称 short_name 不变**。
* 前端按 offset 分批调用,避免一次请求超时。
* 返回:{ done, total, offset, updated, failed }
*/
declare(strict_types=1);
require_once __DIR__ . '/_auth.php';
require_login();
header('Content-Type: application/json; charset=utf-8');
set_time_limit(30);
$offset = max(0, (int)($_GET['offset'] ?? 0));
$limit = min(12, max(1, (int)($_GET['limit'] ?? 6)));
$pdo = db();
$total = (int)$pdo->query('SELECT COUNT(*) FROM sites')->fetchColumn();
$rows = $pdo->query('SELECT id, url FROM sites ORDER BY id LIMIT ' . $limit . ' OFFSET ' . $offset)->fetchAll();
$updated = 0;
$failed = 0;
$now = date('Y-m-d H:i:s');
foreach ($rows as $row) {
$url = norm_url((string)$row['url']);
$meta = fetch_site_meta($url);
$domain = domain_of($meta['final_url'] ?: $url);
$name = $meta['name'] !== '' ? $meta['name'] : $meta['title'];
$iconFile = '';
if (!empty($meta['icon'])) {
$iconFile = download_icon($meta['icon'], $domain);
}
if ($iconFile === '' && $domain !== '') {
$iconFile = download_icon('http://' . $domain . '/favicon.ico', $domain);
}
$sets = ['updated_at=?'];
$args = [$now];
if ($name !== '') { $sets[] = 'name=?'; $args[] = $name; }
if ($iconFile !== '') { $sets[] = 'icon=?'; $args[] = $iconFile; }
// 注意:这里绝不修改 short_name(用户自定义简称)
$args[] = (int)$row['id'];
try {
$pdo->prepare('UPDATE sites SET ' . implode(',', $sets) . ' WHERE id=?')->execute($args);
if ($iconFile !== '' || $name !== '') { $updated++; } else { $failed++; }
} catch (Throwable $e) {
$failed++;
}
}
$next = $offset + count($rows);
echo json_encode([
'done' => $next >= $total || count($rows) === 0,
'total' => $total,
'offset' => $next,
'updated' => $updated,
'failed' => $failed,
], JSON_UNESCAPED_UNICODE);