debianU.html 里的代码示例包含特殊字符,原来的 strip_tags() 在提取整篇 HTML 正文时,把部分本应保留的文字一起吞掉了。我们修改了 extractPage(),先保护 <pre> 代码块,再提取正文
sudo python3 - <<'PY'
from pathlib import Path
path = Path("/var/www/html/search.php")
source = path.read_text(encoding="utf-8")
old = r'''function extractPage(string $html): array
{
$title = '';
if (preg_match('/]*>(.*?)<\/title>/is', $html, $match)) {
$title = normalizeText(strip_tags($match[1]));
}
$html = preg_replace(
'~<(script|style|noscript|template)\b[^>]*>.*?\1>~is',
' ',
$html
) ?? $html;
$text = normalizeText(strip_tags($html));
return [
'title' => $title !== '' ? $title : '未命名页面',
'text' => $text,
];
}'''
new = r'''function extractPage(string $html): array
{
$title = '';
if (preg_match('/<title\b[^>]*>(.*?)<\/title>/is', $html, $match)) {
$title = normalizeText(strip_tags($match[1]));
}
// 先保护代码块,避免其中的 < 和 > 干扰正文提取。
$html = preg_replace_callback(
'~<pre\b[^>]*>(.*?)</pre>~is',
static function (array $match): string {
$code = preg_replace(
'~?code\b[^>]*>~i',
'',
$match[1]
) ?? $match[1];
return '<pre>' . htmlspecialchars(
$code,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
) . '</pre>';
},
$html
) ?? $html;
$html = preg_replace(
'~<(script|style|noscript|template)\b[^>]*>.*?</\1>~is',
' ',
$html
) ?? $html;
$text = normalizeText(strip_tags($html));
return [
'title' => $title !== '' ? $title : '未命名页面',
'text' => $text,
];
}'''
count = source.count(old)
if count != 1:
raise SystemExit(f"停止:预期找到 1 个旧函数,实际找到 {count} 个;文件未修改。")
path.write_text(source.replace(old, new, 1), encoding="utf-8")
print("已成功更新 extractPage()。")
PY
sudo python3 - <<'PY'
import os
import re
import json
from html.parser import HTMLParser
ROOT = "/var/www/html"
EXCLUDED = {"login", ".git", "vendor", "node_modules"}
MAX_BYTES = 2 * 1024 * 1024
MAX_FILES = 1000
KNOWN_TAGS = set("""
html head body title meta link base style script noscript template
header footer main nav section article aside address h1 h2 h3 h4 h5 h6
p div span br hr pre code kbd samp var blockquote q cite
a img picture source audio video track iframe embed object param
ul ol li dl dt dd figure figcaption details summary
table caption colgroup col thead tbody tfoot tr th td
form label input button select option optgroup textarea fieldset legend
strong b em i u s small mark abbr time data sub sup
del ins ruby rt rp wbr
canvas svg path circle rect line polyline polygon g defs use
area map progress meter output dialog
""".split())
class AuditParser(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.unknown = []
self.code_depth = 0
def handle_starttag(self, tag, attrs):
if tag in ("pre", "code", "textarea"):
self.code_depth += 1
if tag not in KNOWN_TAGS and "-" not in tag:
self.unknown.append({
"line": self.getpos()[0],
"tag": tag,
"inside_code": self.code_depth > 0
})
def handle_endtag(self, tag):
if tag in ("pre", "code", "textarea"):
self.code_depth = max(0, self.code_depth - 1)
records = []
scanned = 0
skipped_large = 0
for current, dirs, names in os.walk(ROOT, followlinks=False):
dirs[:] = [
d for d in dirs
if d.lower() not in EXCLUDED
and not os.path.islink(os.path.join(current, d))
]
for name in names:
if not name.lower().endswith(".html"):
continue
path = os.path.join(current, name)
if os.path.islink(path):
continue
try:
size = os.path.getsize(path)
if size > MAX_BYTES:
skipped_large += 1
continue
with open(path, "r", encoding="utf-8", errors="replace") as f:
source = f.read()
scanned += 1
parser = AuditParser()
parser.feed(source)
parser.close()
# 检查不太像正常 HTML 标签起始的裸 < 字符。
suspicious_lt = [
{
"line": source.count("\n", 0, m.start()) + 1,
"sample": source[m.start():m.start() + 45]
.split("\n", 1)[0]
}
for m in re.finditer(r"<(?=[\s=]|['\"`]|[0-9])", source)
]
if parser.unknown or suspicious_lt:
records.append({
"file": "/" + os.path.relpath(path, ROOT).replace(os.sep, "/"),
"unknown_tag_count": len(parser.unknown),
"unknown_tag_examples": parser.unknown[:12],
"suspicious_lt_count": len(suspicious_lt),
"suspicious_lt_examples": suspicious_lt[:12]
})
if scanned >= MAX_FILES:
break
except (OSError, UnicodeError) as e:
records.append({
"file": path,
"read_error": str(e)
})
if scanned >= MAX_FILES:
break
report = {
"root": ROOT,
"scanned_html_files": scanned,
"skipped_large_files": skipped_large,
"files_with_suspicious_patterns": len(records),
"findings": records
}
out = "/tmp/search-html-audit.json"
with open(out, "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
print("扫描完成")
print("已扫描 HTML 文件:", scanned)
print("因超过 2 MiB 跳过的文件:", skipped_large)
print("存在可疑模式的文件:", len(records))
print("报告路径:", out)
print("注意:可疑模式不等于确认存在故障。")
PY
sudo python3 -c '
import json
p = "/tmp/search-html-audit.json"
d = json.load(open(p, encoding="utf-8"))
print("扫描文件数:", d["scanned_html_files"])
print("可疑文件数:", d["files_with_suspicious_patterns"])
for f in d["findings"][:15]:
print("\n文件:", f["file"])
print("可疑标签:", f.get("unknown_tag_examples", [])[:5])
print("可疑字符:", f.get("suspicious_lt_examples", [])[:5])
'
sudo python3 - <<'PY'
import os, re, json
ROOT = "/var/www/html"
EXCLUDED = {"login", ".git", "vendor", "node_modules"}
findings = []
scanned = 0
for current, dirs, names in os.walk(ROOT, followlinks=False):
dirs[:] = [
d for d in dirs
if d.lower() not in EXCLUDED
and not os.path.islink(os.path.join(current, d))
]
for name in names:
if not name.lower().endswith(".html"):
continue
path = os.path.join(current, name)
if os.path.islink(path):
continue
try:
if os.path.getsize(path) > 2 * 1024 * 1024:
continue
with open(path, encoding="utf-8", errors="replace") as f:
source = f.read()
except OSError:
continue
scanned += 1
# 检查 <pre> 外部的内容,不修改原文件。
outside = re.sub(
r"<pre\b[^>]*>.*?",
lambda m: "\n" * m.group(0).count("\n"),
source,
flags=re.I | re.S
)
hits = []
for m in re.finditer(r"<(?=[\s=]|['\"`]|[0-9])", outside):
line = outside.count("\n", 0, m.start()) + 1
sample = outside[m.start():m.start()+60].split("\n", 1)[0]
hits.append({"line": line, "sample": sample})
if hits:
findings.append({
"file": "/" + os.path.relpath(path, ROOT).replace(os.sep, "/"),
"hits": hits[:15],
"total": len(hits)
})
report = {
"scanned_html_files": scanned,
"files_with_suspicious_lt_outside_pre": len(findings),
"findings": findings
}
out = "/tmp/search-html-outside-pre.json"
with open(out, "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
print("已扫描 HTML 文件:", scanned)
print("存在可疑字符的文件:", len(findings))
print("报告:", out)
for item in findings[:25]:
print("\n文件:", item["file"], "可疑数量:", item["total"])
for hit in item["hits"][:5]:
print(" 第", hit["line"], "行:", hit["sample"])
PY
/programming/jL.html:将 left<=right 中的 < 转义为 <,验证已能正确提取。
/office/excel/hanSHU.html:将公式中的 < 转义为 <,验证 DATE(2013,1,31) 已能正确提取
sudo python3 - <<'PY'
from pathlib import Path
changes = [
(
Path("/var/www/html/programming/jL.html"),
"left<=right",
"left<=right",
),
(
Path("/var/www/html/office/excel/hanSHU.html"),
'"<="&DATE(2013,1,31)',
'"<="&DATE(2013,1,31)',
),
]
# 先检查全部文件,避免只修改一半。
for path, old, new in changes:
text = path.read_text(encoding="utf-8")
count = text.count(old)
if count != 1:
raise SystemExit(
f"停止:{path} 中目标内容出现 {count} 次,预期恰好 1 次;未进行修改。"
)
for path, old, new in changes:
text = path.read_text(encoding="utf-8")
path.write_text(text.replace(old, new, 1), encoding="utf-8")
print(f"已修复:{path}")
print("完成。")
PY
sudo python3 - <<'PY'
from pathlib import Path
import re
path = Path("/var/www/html/search.php")
source = path.read_text(encoding="utf-8")
pattern = re.compile(
r'function extractPage\(string \$html\): array\s*\{.*?\n\}',
re.S
)
new_function = r'''function extractPage(string $html): array
{
$title = '';
if (preg_match('/]*>(.*?)<\/title>/is', $html, $match)) {
$title = normalizeText(strip_tags($match[1]));
}
// 删除注释,避免注释中的内容进入搜索索引。
$html = preg_replace('~~s', ' ', $html) ?? $html;
// 删除不需要搜索的内容。
$html = preg_replace(
'~<(script|style|noscript|template)\b[^>]*>.*?\1\s*>~is',
' ',
$html
) ?? $html;
// 临时保护 pre 代码块,防止代码中的尖括号被当成 HTML 标签。
$codeBlocks = [];
$markerPrefix = 'SEARCHCODE' . bin2hex(random_bytes(8)) . 'TOKEN';
$html = preg_replace_callback(
'~]*>(.*?)
~is',
static function (array $match) use (&$codeBlocks, $markerPrefix): string {
$code = $match[1];
// 去掉通常用于包裹代码的最外层 code 标签。
$code = preg_replace(
'~^\s*]*>~i',
'',
$code,
1
) ?? $code;
$code = preg_replace(
'~\s*$~i',
'',
$code,
1
) ?? $code;
$marker = $markerPrefix . count($codeBlocks) . 'END';
$codeBlocks[$marker] = $code;
return ' ' . $marker . ' ';
},
$html
) ?? $html;
// 只删除已识别的 HTML 标签;未知的尖括号表达式尽可能作为文本保留。
$knownTags = implode('|', [
'html','head','body','title','meta','link','base',
'style','script','noscript','template',
'header','footer','main','nav','section','article','aside',
'h1','h2','h3','h4','h5','h6','p','div','span','br','hr',
'a','img','picture','source','audio','video','track','iframe',
'embed','object','param','ul','ol','li','dl','dt','dd',
'figure','figcaption','details','summary',
'table','caption','colgroup','col','thead','tbody','tfoot',
'tr','th','td','form','label','input','button','select',
'option','optgroup','textarea','fieldset','legend',
'strong','b','em','i','u','s','small','mark','abbr','time',
'data','sub','sup','del','ins','ruby','rt','rp','wbr',
'canvas','svg','path','circle','rect','line','polyline',
'polygon','g','defs','use','area','map','progress','meter',
'output','dialog','font','center','left','right','big',
'titlefifty','ifmodule','virtualhost','address','blockquote',
'q','cite','kbd','samp','var','code'
]);
$tagPattern = '~?(?:' . $knownTags .
')\b(?:[^>"\']|"[^"]*"|\'[^\']*\')*>~i';
$html = preg_replace($tagPattern, ' ', $html) ?? $html;
// 还原代码块,保留代码本身的特殊字符。
if ($codeBlocks) {
$html = str_replace(
array_keys($codeBlocks),
array_values($codeBlocks),
$html
);
}
$text = normalizeText($html);
return [
'title' => $title !== '' ? $title : '未命名页面',
'text' => $text,
];
}'''
matches = list(pattern.finditer(source))
if len(matches) != 1:
raise SystemExit(
f"停止:预期找到 1 个 extractPage() 函数,实际找到 {len(matches)} 个;文件未修改。"
)
updated = pattern.sub(lambda _: new_function, source, count=1)
path.write_text(updated, encoding="utf-8")
print("已更新 extractPage(),其他搜索逻辑保持不变。")
PY
sudo php -l /var/www/html/search.php
sudo tee /var/www/html/search-highlight.js >/dev/null <<'JS'
(() => {
const keyword = (new URLSearchParams(location.search).get('find') || '').trim();
if (!keyword) return;
const needle = keyword.toLocaleLowerCase();
const style = document.createElement('style');
style.textContent = `
mark.search-hit {
background: #ffeb3b !important;
color: #111 !important;
border-radius: 2px;
}
mark.search-hit-active {
outline: 2px solid #f59e0b;
}
`;
document.head.appendChild(style);
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
{
acceptNode(node) {
const parent = node.parentElement;
if (!parent || parent.closest(
'script,style,noscript,textarea,input,select,option,button,mark'
) || !node.nodeValue.trim()) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
const nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
let firstMark = null;
for (const node of nodes) {
const text = node.nodeValue;
const lower = text.toLocaleLowerCase();
let pos = lower.indexOf(needle);
if (pos < 0) continue;
const fragment = document.createDocumentFragment();
let last = 0;
while (pos >= 0) {
fragment.appendChild(document.createTextNode(text.slice(last, pos)));
const mark = document.createElement('mark');
mark.className = 'search-hit';
mark.textContent = text.slice(pos, pos + keyword.length);
fragment.appendChild(mark);
if (!firstMark) firstMark = mark;
last = pos + keyword.length;
pos = lower.indexOf(needle, last);
}
fragment.appendChild(document.createTextNode(text.slice(last)));
node.parentNode.replaceChild(fragment, node);
}
if (firstMark) {
firstMark.classList.add('search-hit-active');
firstMark.scrollIntoView({ behavior: 'auto', block: 'center' });
}
})();
JS
sudo python3 - <<'PY'
from pathlib import Path
p = Path("/var/www/html/search.php")
s = p.read_text()
<a href="<?= h($result['url']) ?>">
<a href="<?= h($result['url'] . '?find=' . rawurlencode($query)) ?>">
if s.count(old) != 1:
raise SystemExit("未找到唯一的目标代码,已停止修改。")
p.write_text(s.replace(old, new, 1))
print("搜索结果链接修改成功。")
PY
sudo php -l /var/www/html/search.php
Apache 会在 HTML 响应的
前自动插入脚本引用,包括以后新增的 HTML 页面。
sudo a2enmod substitute
sudo tee /etc/apache2/conf-available/search-highlight.conf >/dev/null <<'CONF'
AddOutputFilterByType SUBSTITUTE text/html
Substitute "s|||ni"
CONF
sudo a2enconf search-highlight
sudo apache2ctl configtest
sudo systemctl reload apache2