Extract the pre-casualty defender report block into a new private method
collectReinforcementReport(): reset and rebuild the reinforcement unit totals
($DefenderEnf) and per-tribe hero totals from a fresh re-select, fold
reinforcement heroes into the defender's hero count, build the "units sent"
report rows (own troops + reinforcements and their masked variants), and
(re)initialise the per-tribe dead-hero accumulator. The bundle is returned to
the caller and the defender's folded hero count is reassigned at the call site.
Pure behaviour-preserving extraction. Method name matches the maintainer's
roadmap for #155.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Extract the "kill other defence in village" block (reinforcement casualties)
into a new private method applyReinforcementCasualties(): compute each
reinforcement's dead units/hero, persist them (modifyEnforce), notify the
reinforcing players, and delete fully-wiped reinforcements. Dead counts are
accumulated into $alldead and dead heroes into $DefenderHeroesDeadArray (both
passed by reference); the tribe-presence flags (rom/ger/gal/nat/natar) are
returned to the caller.
Pure behaviour-preserving extraction. Also drops two dead recomputations of
$totalsend_att/$totaldead_att that sat inside the loop and were immediately
overwritten right after it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Move the in-village defender casualty handling (kill ratio applied to the
defender's own troops + hero, persisted via modifyUnit) out of the giant
sendunitsComplete() loop into a dedicated private method returning the
$owndead map. Pure behaviour-preserving extraction; also drops a dead $u
variable that was assigned but never read.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
On some servers the NPC ("merchant") distribution screen could lock on
"Rest: NaN", hiding the trade button and making the NPC unusable. The "Rest"
value never returned to 0, so the player could not complete the trade.
Two layers of hardening:
* Client (Templates/Build/17_3.tpl):
- add a safe npcDiv() helper (returns 0 on a 0 divisor or non-finite value)
and route every division in portionOut() through it, so Infinity/NaN can no
longer leak into the inputs;
- in calculateRest(), coerce "Rest"/overall to a finite value (fall back to
the total when org4 cannot be parsed) so the submit button can always
reappear once the distribution is balanced;
- coerce each resource, $totalRes, $maxstore and $maxcrop to a valid,
non-negative integer before they reach the page/JS, so a resource computed
as NaN/INF cannot poison org4/summe in the first place.
* Server (Market::tradeResource): clamp each requested amount to [0, maxstore]
(crop to maxcrop) before persisting, so a forged or corrupted POST can no
longer write out-of-range resources.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add an admin-controlled debug mode that captures PHP errors of all
players into var/log/debug-players.log, to hunt remaining PHP 8.3 bugs
from real play sessions. Fully transparent to players: no redirect, no
gameplay change, errors are never displayed.
- DB: new debug_log table (one row), mirroring the maintenance pattern.
- Database: getDebugMode()/setDebugMode()/setDebugSettings(), defensive
when the table is absent (no blank page).
- Session: register a custom error + shutdown handler when enabled; the
handler runs even when php.ini error_reporting masks warnings/notices,
so capture is complete without a Docker rebuild. Auto-disables after a
configurable window.
- DebugErrorLogger: size-capped file with a single .log.1 rotation,
honours the @ operator, never throws.
- Admin: new "Debug Error Log" page (levels, size cap, auto-off, on-page
viewer, clear, download) + debugLog action mod.
- Menu: admin-only quick on/off widget (TZ_DEBUG_ON/OFF, EN/FR/RO).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Implement the "Time Preference" section of the player preferences (issue
#198), which until now was stored in DB but never applied in-game.
procMtime() — the central date/time formatter used across reports, messages,
notices and troop movements — now honours the per-user settings:
- timezone: the stored value is mapped to a DateTimeZone, either a named
DST-aware region (Europe, UK, Turkey, Kolkata, Bangkok, New York,
Chicago, New Zealand) or a fixed UTC offset (general zones); timestamps
are converted before formatting.
- tformat: drives the date layout and 12h/24h clock (0=EU dd.mm.yy 24h,
1=US mm/dd/yy 12h, 2=UK dd/mm/yy 12h, 3=ISO yy/mm/dd 24h). tformat 0
keeps the previous EU output unchanged.
The today/yesterday sentinels are preserved (callers compare them) and are
computed in the player's timezone. The time-only path (mode 9) stays 24h
H:i:s because it feeds the live JS clock counters (unx.js), which parse
"H:i:s" by splitting on ":". A few alliance/report/farm-list rows that
combined procMtime's day part with a raw date('H:i') now take the time from
the same procMtime result, to avoid mixing timezones.
A second "local time" clock is shown next to the server-time one: a small
vanilla-JS snippet emitted once from menu.tpl finds the visible #tp1 clock
and appends a row ticking in the player's timezone (Date.now() + UTC offset),
independent of the browser timezone and of the unx.js counters. It aligns the
value under the server time, is skipped when the player's timezone matches
the server's, and lets the clock box grow so the extra row fits the frame.
Adds the LOCAL_TIME string (EN/FR/RO). When no player session is available
(admin / pre-login) procMtime falls back to the server timezone and EU
layout, i.e. the previous behaviour. Removes the last "not coded yet" tag
from the preferences form.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The #155 refactor that extracted buildCombatReport() turned one comma
into a literal dot in the non-scout data2 string:
...$info_chief.'.'.(isset($info_spy) ? ... // was ','
That dropped one CSV field, shifting every following field left by one
(hero troops t11, casualties, prisoners 182-192) and injecting a stray
"." into a numeric cell. Visible attack reports rendered with misplaced
hero/prisoner data, and the shifted text in the prisoner slots is what
made Templates/Notice/1.tpl array_sum() warn under PHP 8.
Restore the comma so the layout matches what the report template
(Notice/1.tpl) and the pre-refactor code expect. Reports stored before
this fix keep their corrupted string; the int-cast guard added in the
previous commit keeps them from re-emitting the warning.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
PHP 8.x turned several long-standing implicit accesses into runtime
warnings that flooded the error log during attacks and report viewing:
- Battle.report (Templates/Notice/1.tpl): the prisoner check ran
array_sum() over slots that may hold non-numeric text (the
"Information" line can shift indices), raising
"Addition is not supported on type string". Sum int-cast values.
- Database::getUnitsNumber(): movement/reinforcement arrays can be null
or miss tribe-specific unit keys, raising "Undefined array key" and
"Trying to access array offset on null". Null-coalesce to 0.
- Automation (combat resolver): $scout was only defined for scouting
attacks (type 1) yet always passed to buildCombatReport(), raising
"Undefined variable $scout". Initialize it for every attack type.
- Automation: the destroy-village check read $to['natar'] which is not
always set, raising "Undefined array key". Use empty().
Pure null-safety / behaviour-preserving changes; no gameplay logic
altered.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Honour the per-user auto-completion checkboxes on the rally point and the
marketplace, where the target village is typed by name (dname field):
- v1: own villages
- v2: villages in the surroundings of the active village
- v3: villages of the player's alliance members
A new Database::getAutoCompleteVillages() builds the bounded, de-duplicated
name list from the enabled categories (system accounts excluded). A shared
Templates/villageAutocomplete.tpl renders a native <datalist> consumed by
the dname input via list="dnameSuggest"; nothing is emitted when every box
is unchecked, keeping the previous behaviour. Removes the "not coded yet"
tag from the auto-completion section in the preferences form.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Honour the per-user report-filter checkboxes in marketComplete():
- v4: recipient gets no report for transfers between own villages
- v6: recipient gets no report for transfers from foreign villages
- v5: sender gets no report for transfers to foreign villages
The user row is already fully loaded by getUserFields(), so the prefs
are read without extra queries. Removes the "not coded yet" tag from
the report-filter section in the preferences form.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
userinfo is served from a 30s session cache (Session::PopulateVar), so a
freshly saved preference (e.g. the large-map checkbox) only reflected after
the cache expired or a re-login — the box appeared unchanged on OK.
Invalidate the per-user session cache after saving so the redirected page
reloads the values from the DB right away.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The ft=p2 handler (Profile::updatePreferences) only saved the language
column, so the large-map checkbox — and v1-v6 / timezone / tformat — never
persisted: the box reverted to unchecked on OK. The full save block in
preference.tpl was dead code (the handler header()+exit before it runs).
Persist the whole preferences form in the handler (checkboxes as 0/1,
timezone/tformat as validated ints) so the Large map preference actually
sticks. The other fields are stored now and applied in-game in later
steps of #198.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
On a fresh install several strings were still hardcoded in English
(reported on the live server, RO locale):
- statistiken.php: the page <title>, the <h1> and the tab bar
(Player / Alliances / Villages / Heroes / General) were literal English.
- Templates/Ranking/ranksearch.tpl: the "back | forward" pagination links.
- Templates/troops.tpl: the "Hero" troop-row label.
Wire them to language constants. Reuse existing ones
(STATISTICS, PLAYER, PLAYERS, VILLAGES, BACK, FORWARD, U0) and add three
new constants (ALLIANCES, HEROES, GENERAL) to en/fr/ro. WW is kept as-is
(universal acronym).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Phase C of the sendunitsComplete() refactor (issue #155).
- handlePrisoners(): extracts the ~100-line block that releases troops
trapped in the defender's traps during a conquest attack (type 3),
sends them home with 25% casualties, repairs destroyed traps, and
returns the HTML fragment for the battle-report trap line.
- buildCombatReport(): extracts the assembly of the $data2 (main report)
and $data_fail (all-attacker-dead fallback) CSV strings, including the
"village destroyed" annotation in $info_cat and the final appending of
$info_trap / $info_troop / $info_hero.
Pure behaviour-preserving extractions — no logic change.
Validated by deterministic A/B harness (infantry, evasion, conquest).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Localize the 17 "new features" manual pages (Templates/Manual/1111-1126.tpl
and the 1331.tpl index, typ=11/13) so they render in the player's language
instead of hardcoded English.
- Replace hardcoded page titles, descriptions and nav tooltips with constants.
- The 1331 index reuses the per-page title constants and gains
MANUAL_NF_ENABLED / MANUAL_NF_DISABLED for the on/off status labels.
- Add 33 constants each to GameEngine/Lang/{en,fr,ro}.php
(2 status labels + 15 page titles + 16 descriptions).
- en.php uses tz_def() as the English fallback; fr/ro use define().
- Reuse existing constants where they already exist: VACATION_MODE (page 19),
NEW_FEATURES, FORWARD, BACK, OVERVIEW.
it/zh fall back to English. RO strings pending native review.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Localize the 51 in-game manual unit detail pages (Templates/Manual/1*.tpl,
typ=1) so they render in the player's language instead of English, continuing
the manual l10n started in the building pages PR.
What changed:
- 51 unit pages (Romans/Teutons/Gauls/Nature/Natars) now use translation
constants for every hardcoded string: tribe tags -> TRIBE1..5, the stat
labels (attack value, defence vs infantry/cavalry, Velocity, fields/hour,
Can carry, Duration of training), the unit descriptions, the NPC reference
notes and the "forward" nav.
- 48 new constants added to en/fr/ro:
* 7 shared stat labels (MANUAL_ATTACK_VALUE, MANUAL_DEF_INFANTRY,
MANUAL_DEF_CAVALRY, MANUAL_VELOCITY, MANUAL_FIELDS_HOUR, MANUAL_CAN_CARRY,
MANUAL_TRAINING_DURATION)
* 2 NPC reference notes (MANUAL_NPC_NATARS, MANUAL_NPC_NATURE)
* 1 templated Nature-animal blurb (MANUAL_UDESC_ANIMAL_EXP, used via
printf with the animal name + xp value, so the 10 animal pages share it)
* 38 unit descriptions (MANUAL_UDESC_*). Identical descriptions are shared:
settlers (110/120/130) and rams (117/127) reuse one constant each.
- Reuses constants already present upstream and in the building pages branch:
TRIBE1..5, LEVEL, FORWARD, CROP_CONSUMPTION, PREREQUISITES, UPKEEP, DURATION,
RESOURCES, U1..U50.
English render is unchanged: the English constant values are the existing page
text extracted verbatim (whitespace-collapsed). it/zh are intentionally left to
fall back to English via the en.php fallback wired up earlier.
Scope note: this builds on the manual building-pages l10n branch (reuses
CROP_CONSUMPTION). The 17 "new features" pages (typ=11/13) are out of scope and
will be a follow-up PR. RO strings are functional but would benefit from a
native review.
The #182 merge resolution left buildScoutReport() defined but never called,
while the original inline scout-report block was kept at the call site — so
the method was dead code and the scout-report logic was duplicated.
This wires it up: the inline block in the `if (!empty($scout))` branch is
replaced by a single `$info_spy = $this->buildScoutReport(...)` call. The
method already exists and its body is identical to the removed inline block,
so behaviour is unchanged — this just removes the duplication and makes the
extraction actually take effect. Brace balance even (634/634).
Co-authored-by: TravianZ Patcher <patcher@localhost>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The merge of #180 (applyBounty) and #181 (buildScoutReport) — both of which
inserted a new private method just before sendunitsComplete() — dropped the
closing brace of buildScoutReport(). As a result applyBounty() was declared
INSIDE buildScoutReport(), producing:
PHP Parse error: syntax error, unexpected token "private"
in GameEngine/Automation.php
This crashes Automation.php entirely (HTTP 500), so the whole game automation
stops: troop movements never resolve, buildings never finish, etc.
Fix: restore the missing `}` closing buildScoutReport() before the applyBounty()
docblock. Brace balance is now even again (634/634). One-character structural
fix, no logic change.
Co-authored-by: TravianZ Patcher <patcher@localhost>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Catalin Novgorodschi <cata7007@gmail.com>
Phase B — pure behaviour-preserving extraction (issue #155).
buildScoutReport(): extracts the scout-report (info_spy) HTML assembly
(~25 lines) into a helper returning the info_spy string. Handles both
spy modes: resources (spy=1) and defence/buildings (spy=2). The block's
body is moved verbatim (multi-line strings with their exact embedded
whitespace preserved). The reassigned $walllevel/$residencelevel/
$palacelevel were local to this block and never read downstream. No
logic change.
Co-authored-by: TravianZ Patcher <patcher@localhost>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Catalin Novgorodschi <cata7007@gmail.com>
The profile already had a language selector (Templates/Profile/preference.tpl)
that saved the choice into users.lang and $_SESSION['lang'], but the saved
preference was never used to actually load the language: every page loads
include("Lang/".LANG.".php") with the server-wide LANG constant, so changing
the language in the profile had no visible effect.
This wires it up:
- Introduce SERVER_LANG (the server default) and make LANG the EFFECTIVE
display language, resolved from the player's saved preference
($_SESSION['lang']) with a fallback to SERVER_LANG
(install/data/constant_format.tpl).
SECURITY: the value is sanitized to [a-z_] and the target Lang/<x>.php
file must exist, otherwise we fall back to the server default. This
prevents Local File Inclusion via include("Lang/".LANG.".php").
- Seed $_SESSION['lang'] from users.lang on login (GameEngine/Session.php,
PopulateVar), so the chosen language applies right after logging in.
- Keep the SERVER default intact when an admin saves settings: the admin
config regenerators and the "Server Settings"/config displays now use
SERVER_LANG (the server default) instead of the per-user LANG, so an
admin browsing in their own language can't accidentally overwrite the
server default (6 Admin/Mods/edit*.php + editServerSet.tpl + config.tpl).
Note: existing installs must also add SERVER_LANG + the LANG resolution to
their generated GameEngine/config.php (and the Admin/Mods/constant_format.tpl
copy) since config is generated at install time.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The admin panel had a "Create System Message" page (admin.php?p=sysmessage
-> Admin/Templates/sysmessage.tpl) whose form posts to
GameEngine/Admin/Mods/sysmessage.php, but that backend file never existed,
so submitting returned a 404 (Not Found).
Add the handler implementing the prepare -> confirm -> execute flow used by
the template. On execute it displays a global system message to all players
using the existing mechanism (writes Templates/text.tpl from
text_format.tpl and sets users.ok = 1), same as the legacy sysmsg.php.
%TEKST% is escaped for the PHP double-quoted string context to avoid
breakage/injection.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Replace GameEngine/Lang/fr.php with a complete, reviewed French
translation:
- Full coverage: all 1439 language keys present (matches en.php), none
missing or extra.
- Valid PHP: all French apostrophes properly escaped, no unterminated
strings.
- Months localized, quest tutorial numbering kept consistent with en.php.
- Fixed gender agreement on EMAIL_TAKEN ("Cet e-mail ... utilisé").
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Addresses the five bugs found on master (6e139a1b) during a fresh
Docker install and admin testing:
1. Missing `details` column in gold_fin_log (HTTP 500 on finishing
construction with gold, buying Gold Club, admin giving gold):
- Add `details varchar(255)` to the gold_fin_log schema, matching
every INSERT and the a2b2.php reader that already use it.
- Fix the broken positional INSERT in Logging::goldFinLog() (it sent
3 values for a 7-column table) which 500'd on the same gold path.
2. Admin "View Player Info" fatal error: `<? php` -> `<?php` in
Admin/Templates/playerinfo.tpl.
3. "Reset Server" leaving the DB corrupted (Duplicate key name
'idx_ft_bonus_xy'): move the croppers indexes inline into the
CREATE TABLE IF NOT EXISTS so structure recreation is idempotent,
and add `croppers` to the reset truncate list.
4. Install wizard crash on failed DB connection (mysqli_error(false)):
use mysqli_connect_error() and show a friendly, actionable message
(incl. the Docker "db" hostname hint).
5. PHP exposing errors/stack traces to end users: ship a production
php.ini baseline + docker/php/zz-travianz.ini that turns off
display_errors and logs to stderr instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>