修复修改账号页面迁移后菜单与更新日志无法访问的问题,保留新版账号表单,在当前账号页面独立显示标签编辑,并保留 AC 代码导出功能。旧账号链接自动跳转到当前页面。恢复个人中心的身份信息、评分、标签、最后在线与已解决题目,修复请求失败后的空白信息及图例重叠。移除语言切换入口,经典界面和新版竞赛界面统一使用中文,隐藏账号表单中的语言选项并统一提交中文。修复最后在线时间显示为 HTML 源码的问题。重新绘制个人中心提交与正确数量的历史图表,兼容浅色、深色主题及移动端,默认清理设置不再隐藏图表。提交与正确数量在同一图表中以细线和半透明柱形叠加展示,减少密集曲线遮挡。恢复暂存更改中的 API 请求超时和错误日志。
"
}
}
}
\ No newline at end of file
diff --git a/XMOJ.user.js b/XMOJ.user.js
index ea1c87d8..ab400e36 100644
--- a/XMOJ.user.js
+++ b/XMOJ.user.js
@@ -1,6 +1,6 @@
// ==UserScript==
// @name XMOJ
-// @version 3.8.2
+// @version 3.8.3
// @description XMOJ增强脚本
// @author @XMOJ-Script-dev, @langningchen and the community
// @namespace https://github/langningchen
@@ -44,6 +44,115 @@
* You should have received a copy of the GNU General Public License along with this program. If not, see .
*/
+// Set the app preference at document-start, before Vue requests /api/nav.
+function InitializeChineseLanguage() {
+ let wasEnglish = document.cookie.split(";").some(cookie => cookie.trim() == "XMOJ_LANG=en");
+ document.cookie = "XMOJ_LANG=zh; path=/; max-age=31536000; SameSite=Lax" + (location.protocol == "https:" ? "; Secure" : "");
+ return wasEnglish;
+}
+
+const chineseAccountForms = new WeakSet();
+function EnforceChineseAccountLanguage(root) {
+ const radios = [...root.querySelectorAll('input[type="radio"]')];
+ const Matches = (radio, language) => {
+ const label = [...radio.labels || []].map(node => node.textContent.trim());
+ return language == "zh" ? /^(cn|zh|zh[-_]cn)$/i.test(radio.value) || label.some(text => /^(中文|简体中文|Chinese)$/i.test(text)) :
+ /^en(?:[-_]us)?$/i.test(radio.value) || label.some(text => /^English$/i.test(text));
+ };
+ for (const chinese of radios.filter(radio => Matches(radio, "zh"))) {
+ const english = radios.find(radio => radio !== chinese && radio.name === chinese.name && radio.form === chinese.form && Matches(radio, "en"));
+ if (!chinese.name || !english) continue;
+ if (!chinese.checked) chinese.click();
+ chinese.setAttribute("data-xmoj-script-chinese-language", "");
+ let group = chinese.parentElement;
+ while (group && !group.contains(english)) group = group.parentElement;
+ if (group && !group.matches("form, body, html") && !group.querySelector('input:not([type="radio"]), select, textarea, button')) {
+ group.setAttribute("data-xmoj-script-language-selector", "");
+ const heading = group.previousElementSibling;
+ if (heading && /^(界面语言|语言|Language)$/i.test(heading.textContent.trim())) heading.setAttribute("data-xmoj-script-language-selector", "");
+ } else {
+ for (const radio of [chinese, english]) {
+ radio.setAttribute("data-xmoj-script-language-selector", "");
+ for (const label of radio.labels || []) label.setAttribute("data-xmoj-script-language-selector", "");
+ }
+ }
+ for (const label of root.querySelectorAll("label, legend")) {
+ if (/^(界面语言|语言|Language)$/i.test(label.textContent.trim())) label.setAttribute("data-xmoj-script-language-selector", "");
+ }
+ const form = chinese.form;
+ if (form && !chineseAccountForms.has(form)) {
+ chineseAccountForms.add(form);
+ // Keep the native field enabled so the hidden Chinese value is submitted.
+ form.addEventListener("submit", () => EnforceChineseAccountLanguage(form), true);
+ form.addEventListener("formdata", event => {
+ EnforceChineseAccountLanguage(form);
+ for (const radio of form.querySelectorAll("input[data-xmoj-script-chinese-language]")) event.formData.set(radio.name, radio.value);
+ });
+ }
+ }
+}
+
+function EnforceChineseView(root = document) {
+ document.documentElement.lang = "zh-CN";
+ if (!document.getElementById("UserScript-ChineseLanguage")) {
+ let style = document.createElement("style");
+ style.id = "UserScript-ChineseLanguage";
+ style.textContent = `#lang_cn_to_en, #lang_en_to_cn, .xmoj-lang-switch,
+ [data-xmoj-script-language-selector] { display: none !important; }
+ .lang_en { display: none !important; }
+ .lang_cn { display: revert !important; }`;
+ document.head.appendChild(style);
+ }
+ if (location.pathname === "/modify_user_info.php") EnforceChineseAccountLanguage(root);
+ // Keep Vue's nodes and handlers intact; it can replace the navbar on navigation.
+ for (let link of root.querySelectorAll('#xmoj-navbar > ul.navbar-right > li > a[href="#"]:not(.dropdown-toggle)')) {
+ if (/^(English|中文)$/.test(link.textContent.trim())) link.setAttribute("data-xmoj-script-language-selector", "");
+ }
+ // The problem/solution selector has its own reactive language, separate from nav.
+ for (let button of root.querySelectorAll(".xmoj-lang-switch button")) {
+ if (button.textContent.trim() == "中文" && !button.classList.contains("hidden") && !button.hidden) button.click();
+ }
+}
+
+async function EnsureChinesePage() {
+ EnforceChineseView();
+ const retryKey = "UserScript-ChineseLanguageReload";
+ const pageKey = location.pathname + location.search + location.hash;
+ // Classic pages persist the preference through the current account form.
+ // change_lang.php is defunct; do not call it or reload classic pages for it.
+ if (!(IsContestWebApp() && initiallyEnglishLanguage)) {
+ sessionStorage.removeItem(retryKey);
+ return false;
+ }
+ try {
+ // A server that refuses the preference must not trap the user in a reload loop.
+ if (sessionStorage.getItem(retryKey) == pageKey) throw new Error("中文设置未生效");
+ sessionStorage.setItem(retryKey, pageKey);
+ location.reload();
+ } catch (error) {
+ console.error("[XMOJ-Script] Chinese language:", error);
+ let alert = document.createElement("div");
+ alert.className = "alert alert-warning";
+ alert.role = "alert";
+ alert.textContent = "切换中文失败,请检查网络后重试。 ";
+ let retry = document.createElement("button");
+ retry.type = "button";
+ retry.className = "btn btn-outline-secondary";
+ retry.textContent = "重试";
+ retry.addEventListener("click", () => {
+ sessionStorage.removeItem(retryKey);
+ location.reload();
+ });
+ alert.appendChild(retry);
+ document.body.prepend(alert);
+ RevealPage();
+ return false;
+ }
+ return true;
+}
+
+const initiallyEnglishLanguage = InitializeChineseLanguage();
+
// The /web application owns its DOM. Never run the legacy body.innerHTML rewrites
// inside it; InitializeContestWebApp maps its Bootstrap 3 markup to Bootstrap 5.
function IsContestWebApp(pathname = location.pathname) {
@@ -605,6 +714,11 @@ let _earlyObs = null;
// the saved theme and inject Bootstrap CSS + the skin CSS before the first paint,
// and we block the page's own old stylesheets from loading at all.
(() => {
+ const AccountRedirect = GetAccountSettingsRedirect();
+ if (AccountRedirect) {
+ location.replace(AccountRedirect);
+ return;
+ }
// Old contest pages: move to the /web app before anything is drawn.
const ContestWebRedirect = GetContestWebRedirect();
if (ContestWebRedirect) {
@@ -1695,7 +1809,14 @@ let clearCredential = async () => {
}
}
};
-let RequestAPI = (Action, Data, CallBack) => {
+let RequestAPI = (Action, Data, CallBack, ErrorCallBack) => {
+ let completed = false;
+ let Fail = (message) => {
+ if (completed) return;
+ completed = true;
+ if (ErrorCallBack) ErrorCallBack(message);
+ else console.error("[XMOJ-Script] Request " + Action + ": " + message);
+ };
try {
let Session = "";
let Temp = document.cookie.split(";");
@@ -1738,18 +1859,38 @@ let RequestAPI = (Action, Data, CallBack) => {
"DebugMode": UtilityEnabled("DebugMode")
},
data: DataString,
+ // Preserve the stashed general request limit and faster badge retries.
+ timeout: ErrorCallBack ? 15000 : 30000,
+ onerror: () => Fail("网络错误,请重试"),
+ ontimeout: () => Fail("请求超时,请重试"),
+ onabort: () => Fail("请求已取消,请重试"),
onload: (Response) => {
+ if (completed) return;
if (UtilityEnabled("DebugMode")) {
console.log("Received for", Action + ":", Response.responseText);
}
+ if (ErrorCallBack && (Response.status < 200 || Response.status >= 300)) {
+ Fail("请求失败(HTTP " + Response.status + "),请重试");
+ return;
+ }
+ let result;
try {
- CallBack(JSON.parse(Response.responseText));
+ result = JSON.parse(Response.responseText);
} catch (Error) {
console.log(Response.responseText);
+ Fail("服务器响应异常,请重试");
+ return;
+ }
+ completed = true;
+ try {
+ if (CallBack) CallBack(result);
+ } catch (Error) {
+ console.error(Error);
}
}
});
} catch (e) {
+ Fail("请求失败,请重试");
console.error(e);
if (UtilityEnabled("DebugMode")) {
SmartAlert("XMOJ-Script internal error!\n\n" + e + "\n\n" + "If you see this message, please report it to the developer.\nDon't forget to include console logs and a way to reproduce the error!\n\nDon't want to see this message? Disable DebugMode.");
@@ -2148,15 +2289,470 @@ function CreateProblemSwitcher(ProblemList, IsCurrent) {
return problemSwitcher;
}
+// Read server-rendered links, or the numeric p(id, count) calls in unexecuted HTML.
+// Never eval profile scripts: document.write after page load can replace the page.
+function GetProfileSolvedProblems(root = document) {
+ let table = root.querySelector("#statics");
+ let problems = new Set();
+ for (let link of table?.querySelectorAll("a[href]") || []) {
+ try {
+ let url = new URL(link.getAttribute("href"), location.href);
+ let value = url.searchParams.get("id");
+ let id = Number(value);
+ if (url.pathname == "/problem.php" && /^\d+$/.test(value) && Number.isSafeInteger(id) && id > 0) problems.add(id);
+ } catch { /* Ignore malformed links rather than aborting the profile. */ }
+ }
+ for (let script of table?.querySelectorAll("script") || []) {
+ for (let match of script.textContent.matchAll(/\bp\(\s*(\d+)\s*,\s*\d+\s*\)/g)) {
+ if (Number.isSafeInteger(Number(match[1])) && Number(match[1]) > 0) problems.add(Number(match[1]));
+ }
+ }
+ return [...problems];
+}
+
+function InitializeProfileBadge(container, userID, isAdmin) {
+ let badge = document.createElement("span");
+ badge.className = "badge me-2";
+ badge.id = "UserScriptProfileBadge";
+ let status = document.createElement("span");
+ status.setAttribute("role", "status");
+ let retry = document.createElement("button");
+ retry.type = "button";
+ retry.className = "btn btn-outline-secondary btn-sm";
+ retry.textContent = "重试加载标签";
+ let controls = document.createElement("span");
+ container.append(badge, status, retry, controls);
+ const ClearCache = () => {
+ let keys = [];
+ for (let i = 0; i < localStorage.length; i++) {
+ let key = localStorage.key(i);
+ if (key.startsWith("UserScript-User-" + userID + "-Badge-")) keys.push(key);
+ }
+ keys.forEach(key => localStorage.removeItem(key));
+ };
+ const Fail = message => {
+ status.textContent = "标签暂不可用:" + message;
+ retry.hidden = false;
+ retry.disabled = false;
+ };
+ const Load = () => {
+ status.textContent = "正在加载标签...";
+ retry.hidden = true;
+ retry.disabled = true;
+ controls.replaceChildren();
+ RequestAPI("GetBadge", {UserID: userID}, response => {
+ if (!response?.Success) { Fail(response?.Message || "服务器响应异常,请重试"); return; }
+ let data = response.Data ?? {};
+ let content = String(data.Content ?? "");
+ badge.textContent = content;
+ badge.hidden = content === "";
+ badge.style.backgroundColor = /^#[0-9a-f]{6}$/i.test(data.BackgroundColor) ? data.BackgroundColor : "#000000";
+ badge.style.color = /^#[0-9a-f]{6}$/i.test(data.Color) ? data.Color : "#ffffff";
+ status.textContent = "";
+ retry.disabled = false;
+ if (!isAdmin) return;
+ let button = document.createElement("button");
+ button.type = "button";
+ button.className = "btn btn-outline-primary btn-sm";
+ button.textContent = content === "" ? "添加标签" : "删除标签";
+ controls.appendChild(button);
+ button.addEventListener("click", () => {
+ if (content !== "" && !confirm("您确定要删除此标签吗?")) return;
+ button.disabled = true;
+ const Failed = message => { status.textContent = message; button.disabled = false; };
+ RequestAPI(content === "" ? "NewBadge" : "DeleteBadge", {UserID: userID}, result => {
+ if (!result?.Success) { Failed(result?.Message || "服务器响应异常,请重试"); return; }
+ ClearCache();
+ Load();
+ }, Failed);
+ });
+ }, Fail);
+ };
+ retry.addEventListener("click", Load);
+ Load();
+}
+
+function GetProfileActivityData(root = document) {
+ // Read only the numeric history statements emitted by userinfo.php. Never eval
+ // the page's graph initializer: the old Flot renderer is unreliable here.
+ const script = [...root.querySelectorAll("script")].find(node => /\$\.plot\s*\(/.test(node.textContent) && /["']#submission["']/.test(node.textContent));
+ if (!script) return null;
+ const series = [new Map(), new Map()];
+ for (const match of script.textContent.matchAll(/\bd([12])\.push\(\s*\[\s*(\d+)\s*,\s*(\d+)\s*\]\s*\)\s*;?/g)) {
+ const timestamp = Number(match[2]), count = Number(match[3]);
+ if (!Number.isSafeInteger(timestamp) || timestamp <= 0 || timestamp > 8640000000000000 || !Number.isSafeInteger(count)) continue;
+ series[Number(match[1]) - 1].set(timestamp, count);
+ }
+ return series.map(points => [...points].sort((a, b) => a[0] - b[0]));
+}
+
+function InitializeProfileActivityChart(chart) {
+ const data = GetProfileActivityData();
+ chart.style.cssText = "width:100%;max-width:600px;text-align:left;border:1px solid var(--bs-border-color, #adb5bd);box-sizing:border-box;padding:12px;margin-top:12px";
+ chart.replaceChildren();
+ if (!data || !data.some(points => points.length)) {
+ chart.textContent = data ? "暂无提交记录" : "暂时无法读取提交记录";
+ chart.setAttribute("role", "status");
+ return;
+ }
+ const colors = ["#d4a017", "#4799cc"], labels = ["提交", "正确"];
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+ svg.setAttribute("role", "img");
+ svg.setAttribute("aria-label", "提交与正确数量随时间的变化");
+ svg.style.cssText = "display:block;width:100%;height:auto";
+ chart.appendChild(svg);
+ const Node = (tag, attributes, text, parent = svg) => {
+ const node = document.createElementNS(svg.namespaceURI, tag);
+ for (const [name, value] of Object.entries(attributes)) node.setAttribute(name, value);
+ if (text != null) node.textContent = text;
+ parent.appendChild(node);
+ return node;
+ };
+ const date = new Intl.DateTimeFormat("zh-CN", {timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit"});
+ const DateLabel = timestamp => date.format(new Date(timestamp)).replaceAll("/", "-");
+ const points = data.flat();
+ let min = Math.min(...points.map(point => point[0])), max = Math.max(...points.map(point => point[0]));
+ const day = 86400000;
+ min -= day / 2;
+ max += day / 2;
+ const maximum = Math.max(1, ...points.map(point => point[1]));
+ const power = 10 ** Math.floor(Math.log10(maximum / 4));
+ const step = Math.max(1, [1, 2, 5, 10].find(value => value * power >= maximum / 4) * power);
+ const limit = Math.ceil(maximum / step) * step;
+ let previousWidth = 0;
+ const Draw = () => {
+ const width = Math.max(280, Math.min(600, svg.clientWidth || 600));
+ if (width === previousWidth) return;
+ previousWidth = width;
+ svg.replaceChildren();
+ svg.setAttribute("viewBox", "0 0 " + width + " 280");
+ const left = 45, right = width - 12, top = 28, bottom = 238;
+ const X = timestamp => left + (timestamp - min) / (max - min) * (right - left);
+ const Y = count => bottom - count / limit * (bottom - top);
+ for (let tick = 0; tick <= limit; tick += step) {
+ Node("line", {x1: left, x2: right, y1: Y(tick), y2: Y(tick), stroke: "var(--bs-border-color, #adb5bd)", opacity: "0.5"});
+ Node("text", {x: left - 6, y: Y(tick) + 4, "text-anchor": "end", "font-size": "12", fill: "var(--bs-body-color, currentColor)"}, Number(tick.toPrecision(12)));
+ }
+ for (let index = 0; index < labels.length; index++) Node("text", {x: left + index * 65, y: 16, "font-size": "13", fill: colors[index]}, labels[index]);
+ // Paint translucent accepted bars first, with a thin submission line above
+ // them. Invisible hover targets preserve tooltips without dense dot markers.
+ const accepted = Node("g", {"data-layer": "accepted"});
+ const barWidth = Math.max(1, Math.min(12, (right - left) * day / (max - min) * 0.6));
+ for (const [timestamp, count] of data[1]) {
+ const bar = Node("rect", {x: X(timestamp) - barWidth / 2, y: Y(count), width: barWidth, height: bottom - Y(count), fill: colors[1], "fill-opacity": "0.55", "data-series": "accepted"}, null, accepted);
+ Node("title", {}, DateLabel(timestamp) + " 正确:" + count, bar);
+ }
+ const submitted = Node("g", {"data-layer": "submitted"});
+ if (data[0].length) Node("path", {d: data[0].map(([timestamp, count], index) => (index ? "L" : "M") + X(timestamp) + " " + Y(count)).join(" "), fill: "none", stroke: colors[0], "stroke-width": "1.25", "stroke-opacity": "0.8", "data-series": "submitted"}, null, submitted);
+ for (const [timestamp, count] of data[0]) {
+ const point = Node("circle", {cx: X(timestamp), cy: Y(count), r: data[0].length === 1 ? "3" : "5", fill: data[0].length === 1 ? colors[0] : "transparent", "data-series": "submitted"}, null, submitted);
+ Node("title", {}, DateLabel(timestamp) + " 提交:" + count, point);
+ }
+ const singleDate = max - min === day;
+ const ticks = singleDate ? 1 : Math.max(2, Math.floor((right - left) / 110));
+ for (let i = 0; i < ticks; i++) {
+ const timestamp = singleDate ? min + day / 2 : min + day / 2 + i / (ticks - 1) * (max - min - day);
+ Node("text", {x: X(timestamp), y: bottom + 22, "text-anchor": singleDate ? "middle" : i === 0 ? "start" : i === ticks - 1 ? "end" : "middle", "font-size": "11", fill: "var(--bs-body-color, currentColor)", "data-axis": "date"}, DateLabel(timestamp));
+ }
+ };
+ Draw();
+ if (typeof ResizeObserver === "function") {
+ const observer = new ResizeObserver(() => {
+ if (!chart.isConnected) { observer.disconnect(); return; }
+ Draw();
+ });
+ observer.observe(chart);
+ }
+}
+
+function InitializeProfileChart(table) {
+ let chart = table.querySelector("#PieDiv");
+ if (!chart) return;
+ let entries = [...table.rows].filter(row => row.cells[1]?.querySelector('a[href*="jresult="]') && !/^(解决|Solved)/i.test(row.cells[0]?.textContent.trim()))
+ .map(row => ({label: row.cells[0].textContent.trim(), value: Number(row.cells[1].textContent.trim())}))
+ .filter(entry => Number.isFinite(entry.value) && entry.value >= 0);
+ let total = entries.reduce((sum, entry) => sum + entry.value, 0);
+ if (!entries.length) return;
+ let colors = ["#FF8080", "#8080FF", "#80bb80", "#FF0066", "#9900FF", "#996633", "#006633", "#000000", "#66cddd", "#0066FF"];
+ let pie = document.createElement("div");
+ pie.setAttribute("role", "img");
+ pie.setAttribute("aria-label", "判题结果分布");
+ pie.style.cssText = "width:100px;height:100px;border-radius:50%;flex-shrink:0";
+ pie.style.setProperty("border-radius", "50%", "important");
+ let legend = document.createElement("ul");
+ legend.className = "list-unstyled mb-0";
+ legend.style.textAlign = "left";
+ let position = 0;
+ let segments = entries.map((entry, index) => {
+ let start = position;
+ position += total ? entry.value / total * 100 : 0;
+ let color = colors[index % colors.length];
+ let item = document.createElement("li");
+ let marker = document.createElement("span");
+ marker.style.cssText = "display:inline-block;width:10px;height:10px;margin-right:6px;background:" + color;
+ item.append(marker, document.createTextNode(entry.label + " [" + (total ? Math.round(entry.value / total * 100) : 0) + "%]"));
+ legend.appendChild(item);
+ return color + " " + start + "% " + position + "%";
+ });
+ pie.style.background = total ? "conic-gradient(" + segments.join(",") + ")" : "#808080";
+ // The old canvas positions ten labels within 100px; normal flow prevents overlap.
+ chart.style.cssText = "display:flex;flex-wrap:wrap;align-items:center;gap:12px;width:auto;height:auto";
+ chart.replaceChildren(pie, legend);
+}
+
+// Commit the complete profile before any optional API call can fail or stall.
+function InitializeUserProfile(isAdmin = false) {
+ if (location.pathname != "/userinfo.php" || new URLSearchParams(location.search).has("ByUserScript") || document.getElementById("UserScriptProfile")) return;
+ let table = document.getElementById("statics");
+ if (!table) return;
+ let caption = table.caption?.cloneNode(true);
+ caption?.querySelectorAll("a").forEach(link => link.remove());
+ let identity = caption?.textContent.trim() || "";
+ let separator = identity.indexOf("--");
+ let userID = separator >= 0 ? identity.slice(0, separator).trim() : new URLSearchParams(location.search).get("user");
+ let nickname = separator >= 0 ? identity.slice(separator + 2).trim() : identity;
+ if (!userID) return;
+ let problems = GetProfileSolvedProblems();
+ let rows = [...table.rows];
+ const Value = pattern => rows.find(row => pattern.test(row.cells[0]?.textContent.trim() || ""))?.cells[1]?.textContent.trim();
+ let email = Value(/^(电子邮箱|Email:?)$/i) || "";
+ let submitted = Number(Value(/^(提交|Submit(?:ted)?|Submissions?:?)$/i));
+ let accepted = Number(Value(/^(正确|Accepted:?)$/i));
+ let rating = submitted > 0 && Number.isFinite(accepted) ? Math.round(accepted / submitted * 1000) : 0;
+ let profile = document.createElement("div");
+ profile.id = "UserScriptProfile";
+ profile.className = "row text-start text-left";
+ let left = document.createElement("div");
+ left.className = "col-md-5";
+ let right = document.createElement("div");
+ right.className = "col-md-7";
+ profile.append(left, right);
+ let header = document.createElement("div");
+ header.className = "row mb-2";
+ let avatarContainer = document.createElement("div");
+ avatarContainer.className = "col-auto";
+ let avatar = document.createElement("img");
+ avatar.className = "rounded me-2";
+ avatar.alt = userID + " 的头像";
+ avatar.width = avatar.height = 120;
+ avatar.src = "https://cravatar.cn/avatar/00000000000000000000000000000000?d=mp&f=y";
+ // The native profile already contains the email and statistics. No second
+ // profile fetch is needed to show the avatar or compute the rating.
+ if (email) {
+ try { avatar.src = "https://cravatar.cn/avatar/" + CryptoJS.MD5(email).toString() + "?d=retro"; }
+ catch (error) { console.error("[XMOJ-Script] Profile avatar:", error); }
+ }
+ avatarContainer.appendChild(avatar);
+ let info = document.createElement("div");
+ info.className = "col-auto";
+ info.style.lineHeight = "40px";
+ const Line = text => {
+ let line = document.createElement("div");
+ line.textContent = text;
+ info.appendChild(line);
+ return line;
+ };
+ Line("用户名:" + userID);
+ Line("昵称:" + nickname);
+ if (UtilityEnabled("Rating")) Line("评分:" + rating);
+ let lastOnline = Line("最后在线:加载中...");
+ lastOnline.id = "UserScriptProfileLastOnline";
+ let badges = document.createElement("div");
+ info.appendChild(badges);
+ header.append(avatarContainer, info);
+ left.appendChild(header);
+ let heading = document.createElement("h5");
+ heading.textContent = "已解决题目";
+ right.appendChild(heading);
+ let solved = document.createElement("div");
+ solved.id = "UserScriptProfileSolved";
+ solved.style.lineHeight = "1.8";
+ for (let id of problems) {
+ let link = document.createElement("a");
+ link.href = "/problem.php?id=" + id;
+ link.target = "_blank";
+ link.textContent = id;
+ solved.append(link, document.createTextNode(" "));
+ }
+ right.appendChild(solved);
+
+ // Move the original statistics nodes so their links and handlers survive.
+ table.insertAdjacentElement("beforebegin", profile);
+ for (let link of table.caption?.querySelectorAll("a") || []) info.appendChild(link);
+ table.caption?.remove();
+ let solvedCell = [...table.querySelectorAll("td[rowspan]")].find(cell =>
+ cell.querySelector('a[href*="problem.php"]') || [...cell.querySelectorAll("script")].some(script => /\bfunction\s+p\s*\(/.test(script.textContent)));
+ let activity = document.getElementById("submission");
+ if (solvedCell?.querySelector('a[href*="problem.php"]')) {
+ // Keep the native per-problem submission-count links and their handlers.
+ solved.replaceChildren();
+ let group = null;
+ for (let node of [...solvedCell.childNodes]) {
+ if (node.nodeName == "SCRIPT" || node === activity) continue;
+ if (node.nodeName == "A" && node.getAttribute("href")?.includes("problem.php")) {
+ group = document.createElement("span");
+ group.style.cssText = "display:inline-block;white-space:nowrap;margin-right:8px";
+ solved.appendChild(group);
+ }
+ (group || solved).appendChild(node);
+ }
+ }
+ // Submission history is functional and must survive the default cleanup setting.
+ if (activity) {
+ right.appendChild(activity);
+ InitializeProfileActivityChart(activity);
+ }
+ solvedCell?.remove();
+ let firstRow = table.rows[0];
+ if (firstRow?.cells.length >= 2 && !firstRow.cells[0].textContent.trim() && !firstRow.cells[1].textContent.trim()) firstRow.remove();
+ for (let row of table.rows) {
+ if (row.cells[0]?.textContent.trim() == "Statistics") row.cells[0].textContent = "统计";
+ if (row.cells[0]?.textContent.trim() == "Email:") row.cells[0].textContent = "电子邮箱";
+ for (let cell of row.cells) cell.removeAttribute("align");
+ }
+ table.removeAttribute("width");
+ left.appendChild(table);
+ InitializeProfileChart(table);
+ document.title = "用户 " + userID + " 的个人中心";
+ InitializeProfileBadge(badges, userID, isAdmin);
+ RequestAPI("LastOnline", {Username: userID}, response => {
+ lastOnline.innerHTML = "最后在线:" + (response?.Success && response.Data?.logintime != null ? GetRelativeTime(response.Data.logintime) : "暂无记录");
+ }, () => { lastOnline.textContent = "最后在线:暂不可用"; });
+}
+
+function IsAccountSettingsPage(pathname) {
+ return pathname == "/modify_user_info.php";
+}
+
+function GetAccountSettingsRedirect() {
+ return location.pathname == "/modifypage.php" ? "/modify_user_info.php" + location.search + location.hash : null;
+}
+
+function InitializeAccountFeatures(authenticated) {
+ if (!authenticated || !CurrentUsername || !IsAccountSettingsPage(location.pathname) || new URLSearchParams(location.search).has("ByUserScript")) return;
+ InitializeAccountBadgeEditor();
+}
+
+function LoadAccountBadge(content, background, color, onLoad, onError) {
+ RequestAPI("GetBadge", {"UserID": String(CurrentUsername)}, (response) => {
+ if (!response?.Success) {
+ onError(response?.Message || "服务器响应异常,请重试");
+ return;
+ }
+ let badge = response.Data ?? {};
+ content.value = String(badge.Content ?? "");
+ // Color inputs cannot represent an empty value. Use explicit defaults
+ // for missing/invalid colors rather than the browser's silent fallback.
+ background.value = /^#[0-9a-f]{6}$/i.test(badge.BackgroundColor) ? badge.BackgroundColor : "#000000";
+ color.value = /^#[0-9a-f]{6}$/i.test(badge.Color) ? badge.Color : "#ffffff";
+ onLoad();
+ }, onError);
+}
+
+// Unloaded fields must never be saved as a blank replacement for an existing badge.
+function InitializeAccountBadgeLoading(content, background, color, status, onReady = () => {}) {
+ let state = {loaded: false};
+ let retry = document.createElement("button");
+ retry.type = "button";
+ retry.className = "btn btn-outline-secondary mt-2";
+ retry.innerText = "重试加载标签";
+ status.insertAdjacentElement("afterend", retry);
+ let Load = () => {
+ state.loaded = false;
+ [content, background, color].forEach(input => { input.disabled = true; });
+ onReady(false);
+ status.innerText = "正在加载标签...";
+ retry.hidden = true;
+ retry.disabled = true;
+ LoadAccountBadge(content, background, color, () => {
+ state.loaded = true;
+ [content, background, color].forEach(input => { input.disabled = false; });
+ status.innerText = "";
+ retry.disabled = false;
+ onReady(true);
+ }, message => {
+ status.innerText = "标签加载失败:" + message;
+ retry.hidden = false;
+ retry.disabled = false;
+ });
+ };
+ retry.addEventListener("click", Load);
+ Load();
+ return state;
+}
+
+function SaveAccountBadge(content, background, color) {
+ let userID = String(CurrentUsername);
+ return new Promise(resolve => {
+ RequestAPI("EditBadge", {
+ "UserID": userID,
+ "Content": String(content),
+ "BackgroundColor": String(background),
+ "Color": String(color)
+ }, (response) => {
+ if (!response?.Success) {
+ resolve({Success: false, Message: response?.Message || "服务器响应异常,请重试"});
+ return;
+ }
+ let keys = [];
+ for (let i = 0; i < localStorage.length; i++) {
+ let key = localStorage.key(i);
+ if (key.startsWith("UserScript-User-" + userID + "-Badge-")) keys.push(key);
+ }
+ keys.forEach(key => localStorage.removeItem(key));
+ resolve(response);
+ }, message => resolve({Success: false, Message: message}));
+ });
+}
+
+// Keep the migrated site's form, including its submit handler and CSRF fields.
+// Script badges are saved separately so they cannot interfere with account edits.
+function InitializeAccountBadgeEditor() {
+ if (document.getElementById("UserScriptBadgeEditor")) return;
+ let container = document.querySelector("main") || document.querySelector("body > .container") || document.body;
+ let editor = document.createElement("div");
+ editor.id = "UserScriptBadgeEditor";
+ editor.className = "border p-2 my-3";
+ editor.innerHTML = `
标签编辑
+
+
+
+
+
+
+
+ `;
+ let content = editor.querySelector("#UserScriptBadgeContent");
+ let background = editor.querySelector("#UserScriptBadgeBackground");
+ let color = editor.querySelector("#UserScriptBadgeColor");
+ let button = editor.querySelector("button");
+ let status = editor.querySelector("[role='status']");
+ container.appendChild(editor);
+ let badgeState = InitializeAccountBadgeLoading(content, background, color, status, loaded => {
+ button.disabled = !loaded;
+ });
+ button.addEventListener("click", async () => {
+ if (!badgeState.loaded) return;
+ button.disabled = true;
+ status.innerText = "";
+ try {
+ let result = await SaveAccountBadge(content.value, background.value, color.value);
+ status.innerText = result.Success ? "修改成功" : result.Message;
+ } finally {
+ button.disabled = false;
+ }
+ });
+}
+
// The ResetType user menu. Shared by the legacy navbar and the /web app so both
// menus offer the same entries and animate the same way.
function CreateUserMenuItems() {
let Entries = [
- ["修改帐号", () => { location.href = "https://www.xmoj.tech/modifypage.php"; }],
+ ["修改帐号", () => { location.href = "https://www.xmoj.tech/modify_user_info.php"; }],
["个人中心", () => { location.href = "https://www.xmoj.tech/userinfo.php?user=" + CurrentUsername; }],
["短消息", () => { location.href = "https://www.xmoj.tech/mail.php"; }],
["插件设置", () => { location.href = "https://www.xmoj.tech/index.php?ByUserScript=1"; }],
- ["插件更新日志", () => { location.href = "https://www.xmoj.tech/modifypage.php?ByUserScript=1"; }],
+ ["插件更新日志", () => { location.href = "https://www.xmoj.tech/modify_user_info.php?ByUserScript=1"; }],
["注销", () => {
clearCredential();
GM.cookie.set({
@@ -2749,6 +3345,7 @@ async function InitializeContestWebApp() {
return false;
});
if (UtilityEnabled("NewBootstrap")) ApplyBootstrap5Markup();
+ EnforceChineseView(root);
EnhanceNav();
if (!revealed && root.querySelector(".navbar")) {
// As on the legacy pages: top bar first, then show the page.
@@ -3009,6 +3606,7 @@ class NavbarStyler {
// which executes userscripts as classic scripts (not ES modules).
(async () => {
if (GetContestWebRedirect()) return;
+if (GetAccountSettingsRedirect()) return;
if (document.readyState === "loading") {
await new Promise(r => document.addEventListener("DOMContentLoaded", r, { once: true }));
}
@@ -3026,6 +3624,7 @@ if (_foucStyle) {
}
setTimeout(RevealPage, 4000);
}
+if (await EnsureChinesePage()) return;
if (IsContestWebApp()) {
await InitializeContestWebApp();
return;
@@ -3054,7 +3653,10 @@ if (profileElement === null) {
}
CurrentUsername = profileElement.innerText;
CurrentUsername = CurrentUsername.replaceAll(/[^a-zA-Z0-9]/g, "");
+// Initialize migrated account tools independently of the legacy navbar/layout handler.
+InitializeAccountFeatures(logined || (CurrentUsername && !/^(Login|Guest)$/i.test(CurrentUsername)));
let IsAdmin = AdminUserList.indexOf(CurrentUsername) !== -1;
+InitializeUserProfile(IsAdmin);
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)");
const applyTheme = (theme) => {
@@ -3113,12 +3715,15 @@ async function main() {
if (UtilityEnabled("Translate")) {
if (document.querySelector("#navbar > ul:nth-child(1) > li:nth-child(2) > a") != null) document.querySelector("#navbar > ul:nth-child(1) > li:nth-child(2) > a").innerText = "题库";
}
- //send analytics
+ // Preserve native account listeners during page-wide customization.
RequestAPI("SendData", {});
- if (UtilityEnabled("ReplaceLinks")) {
+ // Whole-body replacements discard native forms, profile charts,
+ // and listeners already installed on the enhanced profile.
+ let preserveNativePage = ["/modify_user_info.php", "/modify_password.php", "/userinfo.php"].includes(location.pathname);
+ if (UtilityEnabled("ReplaceLinks") && !preserveNativePage) {
document.body.innerHTML = String(document.body.innerHTML).replaceAll(/\[([^<]*)<\/a>\]/g, "");
}
- if (UtilityEnabled("ReplaceXM")) {
+ if (UtilityEnabled("ReplaceXM") && !preserveNativePage) {
document.body.innerHTML = String(document.body.innerHTML).replaceAll("我", "高老师");
document.body.innerHTML = String(document.body.innerHTML).replaceAll("小明", "高老师");
document.body.innerHTML = String(document.body.innerHTML).replaceAll("下海", "上海");
@@ -3131,6 +3736,7 @@ async function main() {
document.title = String(document.title).replaceAll("小明", "高老师");
}
+ // Bootstrap stylesheet and markup migration.
if (UtilityEnabled("NewBootstrap")) {
// Remove any old Bootstrap/theme stylesheets that the browser's preload
// scanner may have fetched and applied before the document-start
@@ -3503,7 +4109,7 @@ async function main() {
Alert.classList.add("alert-primary");
Alert.role = "alert";
Alert.innerHTML = `欢迎您使用XMOJ增强脚本!点击
- 此处
+ 此处
查看更新日志。`;
Container.appendChild(Alert);
let UtilitiesCard = document.createElement("div");
@@ -3622,7 +4228,7 @@ async function main() {
}, {"ID": "AddAnimation", "Type": "A", "Name": "增加动画"}, {
"ID": "ReplaceYN", "Type": "F", "Name": "题目前状态提示替换为好看的图标"
}, {"ID": "RemoveAlerts", "Type": "D", "Name": "去除多余反复的提示"}, {
- "ID": "Translate", "Type": "F", "Name": "统一使用中文,翻译了部分英文*"
+ "ID": "Translate", "Type": "F", "Name": "翻译部分英文和统一用语*"
}, {
"ID": "ReplaceLinks", "Type": "F", "Name": "将网站中所有以方括号包装的链接替换为按钮"
}, {"ID": "RemoveUseless", "Type": "D", "Name": "删去无法使用的功能*"}, {
@@ -5089,9 +5695,9 @@ async function main() {
PassCheck.click();
}
});
- } else if (location.pathname == "/modifypage.php" && document.querySelector("body > div > div") == null) {
- //页面结构异常(如403/404页面),跳过处理
- } else if (location.pathname == "/modifypage.php") {
+ } else if (IsAccountSettingsPage(location.pathname) && (document.querySelector("body > div > div") == null || (SearchParams.get("ByUserScript") == null && document.querySelector("body > div > div form") == null))) {
+ //页面结构异常或未登录,保留站点提示
+ } else if (IsAccountSettingsPage(location.pathname)) {
if (SearchParams.get("ByUserScript") != null) {
document.title = "XMOJ-Script 更新日志";
if (document.querySelector("body > div > div.mt-3") != null) document.querySelector("body > div > div.mt-3").innerHTML = "";
@@ -5145,388 +5751,72 @@ async function main() {
UpdateDataCardLink.innerText = "查看该版本";
}
});
- } else {
- document.title = "修改账号";
- let Nickname = document.getElementsByName("nick")[0].value;
- let School = document.getElementsByName("school")[0].value;
- let EmailAddress = document.getElementsByName("email")[0].value;
- let CodeforcesAccount = document.getElementsByName("acc_cf")[0].value;
- let AtcoderAccount = document.getElementsByName("acc_atc")[0].value;
- let USACOAccount = document.getElementsByName("acc_usaco")[0].value;
- let LuoguAccount = document.getElementsByName("acc_luogu")[0].value;
- if (document.querySelector("body > div > div") != null) document.querySelector("body > div > div").innerHTML = `