Merge feature/t1250-t1253-auth-locale-and-profiles: auth locale default and public profile names (t1250, t1253)
@@ -20,9 +20,11 @@ Live (na de eerste deploy): https://projects.timfalken.com/meteors/
20
20
(het getal waar het puntenscherm naartoe telt). Een tweede tab toont
21
21
alleen mensen op je vriendenlijst van
22
22
[auth.timfalken.com](https://auth.timfalken.com). Namen en avatars
23
komen uit die vriendenlijst (en uit je eigen login) en worden
24
gecached, zodat ook gasten ze later zien. Ontbreekt die info, dan
25
blijft de oude terugval (het cijfer uit het account-id). Gasten zien
23
komen van de publieke auth-API `GET /api/profiles?ids=…` (gecached
24
zo’n 10 minuten, t1253), en worden teruggeschreven op bestaande
25
profielen. Is auth onbereikbaar, dan blijven de eerdere terugvallen
26
(vriendenlijst, opgeslagen naam, anders het cijfer uit het
27
account-id). Gasten zien
26
28
de wereldwijde top 10; de vriendentab vraagt hen in te loggen. Sta je
27
29
zelf in de lijst, dan is je rij gemarkeerd, met avatar en naam.
28
30
Hieronder de regels van het veld zelf.
@@ -209,8 +211,11 @@ Uitgelogd verandert er niets. Zie `docs/ASSUMPTIONS.md` (t1173).
209
211
Het spel is standaard Engels. Rechtsonder op het hoofdmenu staat de
210
212
vlag van de huidige taal; een klik opent tien vlaggen (VK, Nederland,
211
213
Duitsland, Frankrijk, Japan, China, Korea, Polen, Rusland, Spanje).
212
De keuze blijft lokaal bewaard, en wordt als je bent ingelogd ook in
213
je profiel gezet zodat ze bij een volgende login automatisch geldt.
214
Gasten houden hun keuze in deze browser. Ben je ingelogd, dan is de
215
taal op auth.timfalken.com (`locale`-claim op `/oauth/token` en
216
`GET /api/me`, BCP 47; `zh-Hans` wordt hier `zh`) de standaard, totdat
217
je in het spel zelf een taal kiest. Die expliciete keuze wordt
218
opgeslagen en wint altijd (t1250).
214
219
215
220
## Deploy
216
221
@@ -20,9 +20,11 @@ Live (na de eerste deploy): https://projects.timfalken.com/meteors/20
(het getal waar het puntenscherm naartoe telt). Een tweede tab toont20
(het getal waar het puntenscherm naartoe telt). Een tweede tab toont21
alleen mensen op je vriendenlijst van21
alleen mensen op je vriendenlijst van22
[auth.timfalken.com](https://auth.timfalken.com). Namen en avatars22
[auth.timfalken.com](https://auth.timfalken.com). Namen en avatars23
komen uit die vriendenlijst (en uit je eigen login) en worden23
komen van de publieke auth-API `GET /api/profiles?ids=…` (gecached24
gecached, zodat ook gasten ze later zien. Ontbreekt die info, dan24
zo’n 10 minuten, t1253), en worden teruggeschreven op bestaande25
blijft de oude terugval (het cijfer uit het account-id). Gasten zien25
profielen. Is auth onbereikbaar, dan blijven de eerdere terugvallen26
(vriendenlijst, opgeslagen naam, anders het cijfer uit het27
account-id). Gasten zien26
de wereldwijde top 10; de vriendentab vraagt hen in te loggen. Sta je28
de wereldwijde top 10; de vriendentab vraagt hen in te loggen. Sta je27
zelf in de lijst, dan is je rij gemarkeerd, met avatar en naam.29
zelf in de lijst, dan is je rij gemarkeerd, met avatar en naam.28
Hieronder de regels van het veld zelf.30
Hieronder de regels van het veld zelf.@@ -209,8 +211,11 @@ Uitgelogd verandert er niets. Zie `docs/ASSUMPTIONS.md` (t1173).209
Het spel is standaard Engels. Rechtsonder op het hoofdmenu staat de211
Het spel is standaard Engels. Rechtsonder op het hoofdmenu staat de210
vlag van de huidige taal; een klik opent tien vlaggen (VK, Nederland,212
vlag van de huidige taal; een klik opent tien vlaggen (VK, Nederland,211
Duitsland, Frankrijk, Japan, China, Korea, Polen, Rusland, Spanje).213
Duitsland, Frankrijk, Japan, China, Korea, Polen, Rusland, Spanje).212
De keuze blijft lokaal bewaard, en wordt als je bent ingelogd ook in214
Gasten houden hun keuze in deze browser. Ben je ingelogd, dan is de213
je profiel gezet zodat ze bij een volgende login automatisch geldt.215
taal op auth.timfalken.com (`locale`-claim op `/oauth/token` en216
`GET /api/me`, BCP 47; `zh-Hans` wordt hier `zh`) de standaard, totdat217
je in het spel zelf een taal kiest. Die expliciete keuze wordt218
opgeslagen en wint altijd (t1250).214
219
215
## Deploy220
## Deploy216
221
@@ -4160,6 +4160,7 @@ var I18n = {
4160
4160
],
4161
4161
DEFAULT: 'en',
4162
4162
STORAGE_KEY: 'meteors-locale',
4163
EXPLICIT_KEY: 'meteors-locale-chosen',
4163
4164
COOKIE: 'meteors-locale',
4164
4165
locale: 'en',
4165
4166
_catalog: null,
@@ -4196,6 +4197,48 @@ I18n.known = function (id)
4196
4197
return false;
4197
4198
};
4198
4199
4200
/**
4201
* Map a BCP 47 auth claim (zh-Hans) or a stored id to a Meteors locale.
4202
* Unknown values return null.
4203
*/
4204
I18n.normalize = function (id)
4205
{
4206
if (id == null || id === '')
4207
{ return null; }
4208
var s = String(id).trim().toLowerCase().replace(/_/g, '-');
4209
if (s === 'zh-hans' || s === 'zh-cn' || s === 'zh-sg' || s === 'zh-my')
4210
{ return 'zh'; }
4211
if (this.known(s))
4212
{ return s; }
4213
var primary = s.split('-')[0];
4214
return this.known(primary) ? primary : null;
4215
};
4216
4217
I18n.hasExplicitChoice = function ()
4218
{
4219
try
4220
{
4221
if (typeof localStorage !== 'undefined')
4222
{ return localStorage.getItem(this.EXPLICIT_KEY) === '1'; }
4223
}
4224
catch (e) { /* private mode */ }
4225
return false;
4226
};
4227
4228
I18n.markExplicit = function (on)
4229
{
4230
try
4231
{
4232
if (typeof localStorage === 'undefined')
4233
{ return; }
4234
if (on === false)
4235
{ localStorage.removeItem(this.EXPLICIT_KEY); }
4236
else
4237
{ localStorage.setItem(this.EXPLICIT_KEY, '1'); }
4238
}
4239
catch (e) { /* ignore */ }
4240
};
4241
4199
4242
I18n.info = function (id)
4200
4243
{
4201
4244
id = id || this.locale;
@@ -4374,12 +4417,15 @@ I18n._writeStored = function (id)
4374
4417
I18n.setLocale = function (id, opts)
4375
4418
{
4376
4419
opts = opts || {};
4377
if (!this.known(id))
4420
id = this.normalize(id);
4421
if (!id)
4378
4422
{ id = this.DEFAULT; }
4379
4423
var changed = id !== this.locale;
4380
4424
this.locale = id;
4381
4425
if (opts.persist !== false)
4382
4426
{ this._writeStored(id); }
4427
if (opts.explicit !== false && opts.persist !== false)
4428
{ this.markExplicit(); }
4383
4429
if (typeof document !== 'undefined' && document.documentElement)
4384
4430
{
4385
4431
document.documentElement.lang = this.info(id).htmlLang;
@@ -4563,8 +4609,35 @@ I18n.init = function ()
4563
4609
4564
4610
I18n.applyFromProfile = function (locale)
4565
4611
{
4566
if (this.known(locale))
4567
{ this.setLocale(locale, { sync: false, persist: true }); }
4612
this.applyPreferred({ locale: locale, explicit: true });
4613
};
4614
4615
/**
4616
* t1250: an explicit in-game choice always wins. Otherwise a logged-in
4617
* player follows the auth OIDC locale (mapped, e.g. zh-Hans → zh).
4618
* Guests are left to init()/localStorage.
4619
*/
4620
I18n.applyPreferred = function (opts)
4621
{
4622
opts = opts || {};
4623
var chosen = this.normalize(opts.locale);
4624
var auth = this.normalize(opts.authLocale);
4625
var explicit = !!(opts.explicit && chosen) || this.hasExplicitChoice();
4626
if (explicit)
4627
{
4628
var id = chosen || this.readStored();
4629
if (this.known(id))
4630
{
4631
this.setLocale(id, { sync: false, persist: true, explicit: true });
4632
if (opts.syncExplicit && typeof Online !== 'undefined' && Online.me && Online.setLocale
4633
&& Online.locale !== id)
4634
{ Online.setLocale(id); }
4635
}
4636
return id;
4637
}
4638
if (auth)
4639
{ return this.setLocale(auth, { persist: false, sync: false, explicit: false }); }
4640
return this.locale;
4568
4641
};
4569
4642
4570
4643
if (typeof module !== 'undefined' && module.exports)
@@ -9574,6 +9647,8 @@ var Online = {
9574
9647
me: null,
9575
9648
lifetimePoints: 0,
9576
9649
locale: null,
9650
localeExplicit: false,
9651
authLocale: null,
9577
9652
blocks: [],
9578
9653
planets: [],
9579
9654
lobby: null,
@@ -9635,6 +9710,10 @@ Online._apply = function (data)
9635
9710
{ this.lifetimePoints = data.lifetime_points; }
9636
9711
if (data.locale !== undefined)
9637
9712
{ this.locale = data.locale; }
9713
if (data.locale_explicit !== undefined)
9714
{ this.localeExplicit = !!data.locale_explicit; }
9715
if (data.auth_locale !== undefined)
9716
{ this.authLocale = data.auth_locale; }
9638
9717
if (data.last_planet !== undefined)
9639
9718
{ this.lastPlanet = data.last_planet; }
9640
9719
if (data.blocks)
@@ -16723,10 +16802,14 @@ function applyProfileLocale ()
16723
16802
{
16724
16803
if (typeof I18n === 'undefined' || typeof Online === 'undefined')
16725
16804
{ return; }
16726
if (Online.locale)
16727
{ I18n.applyFromProfile(Online.locale); }
16728
else if (Online.me)
16729
{ Online.setLocale(I18n.locale); }
16805
if (!Online.me)
16806
{ return; }
16807
I18n.applyPreferred({
16808
explicit: !!(Online.localeExplicit && Online.locale),
16809
locale: Online.locale,
16810
authLocale: Online.authLocale,
16811
syncExplicit: true
16812
});
16730
16813
}
16731
16814
16732
16815
/* ---------- t1247 leaderboard -------------------------------------- */
@@ -4160,6 +4160,7 @@ var I18n = {4160
],4160
],4161
DEFAULT: 'en',4161
DEFAULT: 'en',4162
STORAGE_KEY: 'meteors-locale',4162
STORAGE_KEY: 'meteors-locale',4163
EXPLICIT_KEY: 'meteors-locale-chosen',4163
COOKIE: 'meteors-locale',4164
COOKIE: 'meteors-locale',4164
locale: 'en',4165
locale: 'en',4165
_catalog: null,4166
_catalog: null,@@ -4196,6 +4197,48 @@ I18n.known = function (id)4196
return false;4197
return false;4197
};4198
};4198
4199
4200
/**4201
* Map a BCP 47 auth claim (zh-Hans) or a stored id to a Meteors locale.4202
* Unknown values return null.4203
*/4204
I18n.normalize = function (id)4205
{4206
if (id == null || id === '')4207
{ return null; }4208
var s = String(id).trim().toLowerCase().replace(/_/g, '-');4209
if (s === 'zh-hans' || s === 'zh-cn' || s === 'zh-sg' || s === 'zh-my')4210
{ return 'zh'; }4211
if (this.known(s))4212
{ return s; }4213
var primary = s.split('-')[0];4214
return this.known(primary) ? primary : null;4215
};4216
4217
I18n.hasExplicitChoice = function ()4218
{4219
try4220
{4221
if (typeof localStorage !== 'undefined')4222
{ return localStorage.getItem(this.EXPLICIT_KEY) === '1'; }4223
}4224
catch (e) { /* private mode */ }4225
return false;4226
};4227
4228
I18n.markExplicit = function (on)4229
{4230
try4231
{4232
if (typeof localStorage === 'undefined')4233
{ return; }4234
if (on === false)4235
{ localStorage.removeItem(this.EXPLICIT_KEY); }4236
else4237
{ localStorage.setItem(this.EXPLICIT_KEY, '1'); }4238
}4239
catch (e) { /* ignore */ }4240
};4241
4199
I18n.info = function (id)4242
I18n.info = function (id)4200
{4243
{4201
id = id || this.locale;4244
id = id || this.locale;@@ -4374,12 +4417,15 @@ I18n._writeStored = function (id)4374
I18n.setLocale = function (id, opts)4417
I18n.setLocale = function (id, opts)4375
{4418
{4376
opts = opts || {};4419
opts = opts || {};4377
if (!this.known(id))4420
id = this.normalize(id);4421
if (!id)4378
{ id = this.DEFAULT; }4422
{ id = this.DEFAULT; }4379
var changed = id !== this.locale;4423
var changed = id !== this.locale;4380
this.locale = id;4424
this.locale = id;4381
if (opts.persist !== false)4425
if (opts.persist !== false)4382
{ this._writeStored(id); }4426
{ this._writeStored(id); }4427
if (opts.explicit !== false && opts.persist !== false)4428
{ this.markExplicit(); }4383
if (typeof document !== 'undefined' && document.documentElement)4429
if (typeof document !== 'undefined' && document.documentElement)4384
{4430
{4385
document.documentElement.lang = this.info(id).htmlLang;4431
document.documentElement.lang = this.info(id).htmlLang;@@ -4563,8 +4609,35 @@ I18n.init = function ()4563
4609
4564
I18n.applyFromProfile = function (locale)4610
I18n.applyFromProfile = function (locale)4565
{4611
{4566
if (this.known(locale))4612
this.applyPreferred({ locale: locale, explicit: true });4567
{ this.setLocale(locale, { sync: false, persist: true }); }4613
};4614
4615
/**4616
* t1250: an explicit in-game choice always wins. Otherwise a logged-in4617
* player follows the auth OIDC locale (mapped, e.g. zh-Hans → zh).4618
* Guests are left to init()/localStorage.4619
*/4620
I18n.applyPreferred = function (opts)4621
{4622
opts = opts || {};4623
var chosen = this.normalize(opts.locale);4624
var auth = this.normalize(opts.authLocale);4625
var explicit = !!(opts.explicit && chosen) || this.hasExplicitChoice();4626
if (explicit)4627
{4628
var id = chosen || this.readStored();4629
if (this.known(id))4630
{4631
this.setLocale(id, { sync: false, persist: true, explicit: true });4632
if (opts.syncExplicit && typeof Online !== 'undefined' && Online.me && Online.setLocale4633
&& Online.locale !== id)4634
{ Online.setLocale(id); }4635
}4636
return id;4637
}4638
if (auth)4639
{ return this.setLocale(auth, { persist: false, sync: false, explicit: false }); }4640
return this.locale;4568
};4641
};4569
4642
4570
if (typeof module !== 'undefined' && module.exports)4643
if (typeof module !== 'undefined' && module.exports)@@ -9574,6 +9647,8 @@ var Online = {9574
me: null,9647
me: null,9575
lifetimePoints: 0,9648
lifetimePoints: 0,9576
locale: null,9649
locale: null,9650
localeExplicit: false,9651
authLocale: null,9577
blocks: [],9652
blocks: [],9578
planets: [],9653
planets: [],9579
lobby: null,9654
lobby: null,@@ -9635,6 +9710,10 @@ Online._apply = function (data)9635
{ this.lifetimePoints = data.lifetime_points; }9710
{ this.lifetimePoints = data.lifetime_points; }9636
if (data.locale !== undefined)9711
if (data.locale !== undefined)9637
{ this.locale = data.locale; }9712
{ this.locale = data.locale; }9713
if (data.locale_explicit !== undefined)9714
{ this.localeExplicit = !!data.locale_explicit; }9715
if (data.auth_locale !== undefined)9716
{ this.authLocale = data.auth_locale; }9638
if (data.last_planet !== undefined)9717
if (data.last_planet !== undefined)9639
{ this.lastPlanet = data.last_planet; }9718
{ this.lastPlanet = data.last_planet; }9640
if (data.blocks)9719
if (data.blocks)@@ -16723,10 +16802,14 @@ function applyProfileLocale ()16723
{16802
{16724
if (typeof I18n === 'undefined' || typeof Online === 'undefined')16803
if (typeof I18n === 'undefined' || typeof Online === 'undefined')16725
{ return; }16804
{ return; }16726
if (Online.locale)16805
if (!Online.me)16727
{ I18n.applyFromProfile(Online.locale); }16806
{ return; }16728
else if (Online.me)16807
I18n.applyPreferred({16729
{ Online.setLocale(I18n.locale); }16808
explicit: !!(Online.localeExplicit && Online.locale),16809
locale: Online.locale,16810
authLocale: Online.authLocale,16811
syncExplicit: true16812
});16730
}16813
}16731
16814
16732
/* ---------- t1247 leaderboard -------------------------------------- */16815
/* ---------- t1247 leaderboard -------------------------------------- */@@ -264,6 +264,6 @@
264
264
</div>
265
265
266
266
<script src="framework.js?v=24498ce42730"></script>
267
<script src="game.js?v=5064cd3132cb"></script>
267
<script src="game.js?v=107719dcf338"></script>
268
268
</body>
269
269
</html>
@@ -264,6 +264,6 @@264
</div>264
</div>265
265
266
<script src="framework.js?v=24498ce42730"></script>266
<script src="framework.js?v=24498ce42730"></script>267
<script src="game.js?v=5064cd3132cb"></script>267
<script src="game.js?v=107719dcf338"></script>268
</body>268
</body>269
</html>269
</html>@@ -1489,3 +1489,41 @@ labeltekst, zodat een ontbrekende sleutel nooit rauw in de UI verschijnt.
1489
1489
De ranglijstknop luistert ook op `pointerup` (zoals Spelen / Overleven).
1490
1490
1491
1491
Tests: `test/cache-bust.test.js`, `test/i18n.test.js` (t1256).
1492
1493
## t1250 — Taal van auth.timfalken.com als standaard
1494
1495
De OIDC-claim `locale` staat op `POST /oauth/token` (`user.locale`) en
1496
`GET /api/me` (`user.locale`). Het is een BCP 47-tag: `en`, `nl`,
1497
`de`, `fr`, `ja`, `zh-Hans`, `ko`, `pl`, `ru` of `es`. Intern slaat
1498
auth Chinees op als `zh`; Meteors mapt `zh-Hans` (en `zh-CN` e.d.)
1499
naar `zh`. Aan auth.timfalken.com is niets veranderd.
1500
1501
**Ingelogd.** Zolang je in Meteors zelf geen taal hebt gekozen, volgt
1502
het spel die auth-claim (gezet bij de callback, ververst bij `action=me`).
1503
Een keuze in de vlaggenkiezer wordt opgeslagen (`profiles.locale` plus
1504
`locale_explicit`, en `localStorage meteors-locale-chosen`) en wint
1505
altijd, ook als je later op auth.timfalken.com van taal wisselt.
1506
1507
**Gasten.** Ongewijzigd: `localStorage` / standaard Engels. Een
1508
bestaande `profiles.locale` zonder expliciete vlag telt niet als
1509
in-game keuze (de oude code schreef die soms automatisch).
1510
1511
Tests: `server/tests/run.php` (t1250), `test/i18n.test.js`.
1512
1513
## t1253 — Ranglijstnamen via GET /api/profiles
1514
1515
Auth heeft nu een publieke lookup: `GET /api/profiles?ids=1,2,3`
1516
geeft `{profiles:[{id,username,avatar_url}]}` (max 50 ids, 60
1517
verzoeken per minuut per IP, `Cache-Control` 60 s). `GET /api/users/{id}`
1518
is dezelfde velden voor één gebruiker. Geen token, geen e-mail of
1519
locale. Aan auth.timfalken.com is niets veranderd.
1520
1521
Meteors haalt bij de ranglijst (wereldwijd en vrienden) de auth-ids
1522
in batch op, bewaart ze ~10 minuten in `profiles_cache`
1523
(`Store::PROFILES_CACHE_TTL`) en schrijft echte namen/avatars terug
1524
op bestaande profielen (`rememberIdentities`). Zo zien ook gasten
1525
“lucia” in plaats van “3”. Faalt auth, dan volgt de bestaande keten:
1526
verse of verlopen cache, vriendenlijst, opgeslagen naam, anders het
1527
deel na `:` in het user-id.
1528
1529
Tests: `server/tests/run.php` (t1253), `test/leaderboard.test.js`.
@@ -1489,3 +1489,41 @@ labeltekst, zodat een ontbrekende sleutel nooit rauw in de UI verschijnt.1489
De ranglijstknop luistert ook op `pointerup` (zoals Spelen / Overleven).1489
De ranglijstknop luistert ook op `pointerup` (zoals Spelen / Overleven).1490
1490
1491
Tests: `test/cache-bust.test.js`, `test/i18n.test.js` (t1256).1491
Tests: `test/cache-bust.test.js`, `test/i18n.test.js` (t1256).1492
1493
## t1250 — Taal van auth.timfalken.com als standaard1494
1495
De OIDC-claim `locale` staat op `POST /oauth/token` (`user.locale`) en1496
`GET /api/me` (`user.locale`). Het is een BCP 47-tag: `en`, `nl`,1497
`de`, `fr`, `ja`, `zh-Hans`, `ko`, `pl`, `ru` of `es`. Intern slaat1498
auth Chinees op als `zh`; Meteors mapt `zh-Hans` (en `zh-CN` e.d.)1499
naar `zh`. Aan auth.timfalken.com is niets veranderd.1500
1501
**Ingelogd.** Zolang je in Meteors zelf geen taal hebt gekozen, volgt1502
het spel die auth-claim (gezet bij de callback, ververst bij `action=me`).1503
Een keuze in de vlaggenkiezer wordt opgeslagen (`profiles.locale` plus1504
`locale_explicit`, en `localStorage meteors-locale-chosen`) en wint1505
altijd, ook als je later op auth.timfalken.com van taal wisselt.1506
1507
**Gasten.** Ongewijzigd: `localStorage` / standaard Engels. Een1508
bestaande `profiles.locale` zonder expliciete vlag telt niet als1509
in-game keuze (de oude code schreef die soms automatisch).1510
1511
Tests: `server/tests/run.php` (t1250), `test/i18n.test.js`.1512
1513
## t1253 — Ranglijstnamen via GET /api/profiles1514
1515
Auth heeft nu een publieke lookup: `GET /api/profiles?ids=1,2,3`1516
geeft `{profiles:[{id,username,avatar_url}]}` (max 50 ids, 601517
verzoeken per minuut per IP, `Cache-Control` 60 s). `GET /api/users/{id}`1518
is dezelfde velden voor één gebruiker. Geen token, geen e-mail of1519
locale. Aan auth.timfalken.com is niets veranderd.1520
1521
Meteors haalt bij de ranglijst (wereldwijd en vrienden) de auth-ids1522
in batch op, bewaart ze ~10 minuten in `profiles_cache`1523
(`Store::PROFILES_CACHE_TTL`) en schrijft echte namen/avatars terug1524
op bestaande profielen (`rememberIdentities`). Zo zien ook gasten1525
“lucia” in plaats van “3”. Faalt auth, dan volgt de bestaande keten:1526
verse of verlopen cache, vriendenlijst, opgeslagen naam, anders het1527
deel na `:` in het user-id.1528
1529
Tests: `server/tests/run.php` (t1253), `test/leaderboard.test.js`.@@ -21,15 +21,19 @@ try {
21
21
$profile = [
22
22
'lifetime_points' => 0,
23
23
'locale' => null,
24
'locale_explicit' => false,
24
25
'last_planet' => null,
25
26
'blocks' => [],
26
27
'planets' => [],
27
28
];
29
$authLocale = null;
28
30
if ($user) {
29
31
$store = Store::open();
30
32
$store->touchProfile($user['id'], $user['name'], $user['avatar'] ?? null);
31
33
$view = $store->viewFor($user['id']);
32
34
$profile = $store->profilePayload($user['id']);
35
$token = $_SESSION['token'] ?? null;
36
$authLocale = refreshAuthLocale(is_string($token) ? $token : null);
33
37
}
34
38
jsonOut([
35
39
'ok' => true,
@@ -47,6 +51,8 @@ try {
47
51
'logout_url' => 'logout.php',
48
52
'lifetime_points' => $profile['lifetime_points'],
49
53
'locale' => $profile['locale'],
54
'locale_explicit' => !empty($profile['locale_explicit']),
55
'auth_locale' => $authLocale,
50
56
'last_planet' => $profile['last_planet'],
51
57
'blocks' => $profile['blocks'],
52
58
'planets' => $profile['planets'],
@@ -61,7 +67,6 @@ try {
61
67
$store = Store::open();
62
68
$viewer = $user['id'] ?? null;
63
69
$token = $_SESSION['token'] ?? null;
64
[$known, $friends, $friendsError] = leaderboardKnownIdentities($store, $user, $token);
65
70
if ($scope === 'friends') {
66
71
if (!$user) {
67
72
jsonOut([
@@ -72,6 +77,7 @@ try {
72
77
'me' => null,
73
78
]);
74
79
}
80
[$known, $friends, $friendsError] = leaderboardKnownIdentities($store, $user, $token);
75
81
if ($friendsError !== null && $friends === []) {
76
82
jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);
77
83
}
@@ -86,11 +92,13 @@ try {
86
92
'me' => $viewer,
87
93
]);
88
94
}
95
$players = $store->topPlayers(10, $viewer);
96
[$known] = leaderboardKnownIdentities($store, $user, $token, array_column($players, 'id'));
89
97
jsonOut([
90
98
'ok' => true,
91
99
'scope' => 'global',
92
100
'login_required' => false,
93
'players' => $store->applyIdentities($store->topPlayers(10, $viewer), $known),
101
'players' => $store->applyIdentities($players, $known),
94
102
'me' => $viewer,
95
103
]);
96
104
}
@@ -165,6 +173,8 @@ try {
165
173
'shot_flights' => $view['shot_flights'] ?? [],
166
174
'lifetime_points' => $profile['lifetime_points'],
167
175
'locale' => $profile['locale'],
176
'locale_explicit' => !empty($profile['locale_explicit']),
177
'auth_locale' => sessionAuthLocale(),
168
178
'last_planet' => $profile['last_planet'],
169
179
'blocks' => $profile['blocks'],
170
180
'planets' => $profile['planets'],
@@ -21,15 +21,19 @@ try {21
$profile = [21
$profile = [22
'lifetime_points' => 0,22
'lifetime_points' => 0,23
'locale' => null,23
'locale' => null,24
'locale_explicit' => false,24
'last_planet' => null,25
'last_planet' => null,25
'blocks' => [],26
'blocks' => [],26
'planets' => [],27
'planets' => [],27
];28
];29
$authLocale = null;28
if ($user) {30
if ($user) {29
$store = Store::open();31
$store = Store::open();30
$store->touchProfile($user['id'], $user['name'], $user['avatar'] ?? null);32
$store->touchProfile($user['id'], $user['name'], $user['avatar'] ?? null);31
$view = $store->viewFor($user['id']);33
$view = $store->viewFor($user['id']);32
$profile = $store->profilePayload($user['id']);34
$profile = $store->profilePayload($user['id']);35
$token = $_SESSION['token'] ?? null;36
$authLocale = refreshAuthLocale(is_string($token) ? $token : null);33
}37
}34
jsonOut([38
jsonOut([35
'ok' => true,39
'ok' => true,@@ -47,6 +51,8 @@ try {47
'logout_url' => 'logout.php',51
'logout_url' => 'logout.php',48
'lifetime_points' => $profile['lifetime_points'],52
'lifetime_points' => $profile['lifetime_points'],49
'locale' => $profile['locale'],53
'locale' => $profile['locale'],54
'locale_explicit' => !empty($profile['locale_explicit']),55
'auth_locale' => $authLocale,50
'last_planet' => $profile['last_planet'],56
'last_planet' => $profile['last_planet'],51
'blocks' => $profile['blocks'],57
'blocks' => $profile['blocks'],52
'planets' => $profile['planets'],58
'planets' => $profile['planets'],@@ -61,7 +67,6 @@ try {61
$store = Store::open();67
$store = Store::open();62
$viewer = $user['id'] ?? null;68
$viewer = $user['id'] ?? null;63
$token = $_SESSION['token'] ?? null;69
$token = $_SESSION['token'] ?? null;64
[$known, $friends, $friendsError] = leaderboardKnownIdentities($store, $user, $token);65
if ($scope === 'friends') {70
if ($scope === 'friends') {66
if (!$user) {71
if (!$user) {67
jsonOut([72
jsonOut([@@ -72,6 +77,7 @@ try {72
'me' => null,77
'me' => null,73
]);78
]);74
}79
}80
[$known, $friends, $friendsError] = leaderboardKnownIdentities($store, $user, $token);75
if ($friendsError !== null && $friends === []) {81
if ($friendsError !== null && $friends === []) {76
jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);82
jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);77
}83
}@@ -86,11 +92,13 @@ try {86
'me' => $viewer,92
'me' => $viewer,87
]);93
]);88
}94
}95
$players = $store->topPlayers(10, $viewer);96
[$known] = leaderboardKnownIdentities($store, $user, $token, array_column($players, 'id'));89
jsonOut([97
jsonOut([90
'ok' => true,98
'ok' => true,91
'scope' => 'global',99
'scope' => 'global',92
'login_required' => false,100
'login_required' => false,93
'players' => $store->applyIdentities($store->topPlayers(10, $viewer), $known),101
'players' => $store->applyIdentities($players, $known),94
'me' => $viewer,102
'me' => $viewer,95
]);103
]);96
}104
}@@ -165,6 +173,8 @@ try {165
'shot_flights' => $view['shot_flights'] ?? [],173
'shot_flights' => $view['shot_flights'] ?? [],166
'lifetime_points' => $profile['lifetime_points'],174
'lifetime_points' => $profile['lifetime_points'],167
'locale' => $profile['locale'],175
'locale' => $profile['locale'],176
'locale_explicit' => !empty($profile['locale_explicit']),177
'auth_locale' => sessionAuthLocale(),168
'last_planet' => $profile['last_planet'],178
'last_planet' => $profile['last_planet'],169
'blocks' => $profile['blocks'],179
'blocks' => $profile['blocks'],170
'planets' => $profile['planets'],180
'planets' => $profile['planets'],@@ -35,6 +35,8 @@ try {
35
35
loginUser($id, $name, $avatar);
36
36
$_SESSION['token'] = $token['access_token'];
37
37
$_SESSION['expires'] = time() + (int) $token['expires_in'];
38
// t1250: OIDC locale claim from /api/me, or from the token user payload.
39
storeAuthLocale(authLocaleFromPayload($me) ?? authLocaleFromPayload($token));
38
40
// t1193: back to the main menu unless the login started from Online.
39
41
header('Location: ' . baseUrl() . '/' . loginReturnPath($loginReturn));
40
42
} catch (Throwable $e) {
@@ -35,6 +35,8 @@ try {35
loginUser($id, $name, $avatar);35
loginUser($id, $name, $avatar);36
$_SESSION['token'] = $token['access_token'];36
$_SESSION['token'] = $token['access_token'];37
$_SESSION['expires'] = time() + (int) $token['expires_in'];37
$_SESSION['expires'] = time() + (int) $token['expires_in'];38
// t1250: OIDC locale claim from /api/me, or from the token user payload.39
storeAuthLocale(authLocaleFromPayload($me) ?? authLocaleFromPayload($token));38
// t1193: back to the main menu unless the login started from Online.40
// t1193: back to the main menu unless the login started from Online.39
header('Location: ' . baseUrl() . '/' . loginReturnPath($loginReturn));41
header('Location: ' . baseUrl() . '/' . loginReturnPath($loginReturn));40
} catch (Throwable $e) {42
} catch (Throwable $e) {@@ -124,7 +124,14 @@ CREATE TABLE IF NOT EXISTS friends_cache (
124
124
payload TEXT NOT NULL,
125
125
fetched INTEGER NOT NULL
126
126
);
127
CREATE TABLE IF NOT EXISTS profiles_cache (
128
user_id TEXT PRIMARY KEY,
129
name TEXT NOT NULL,
130
avatar TEXT,
131
fetched INTEGER NOT NULL
132
);
127
133
SQL);
134
$this->ensureColumn('profiles', 'locale_explicit', 'INTEGER NOT NULL DEFAULT 0');
128
135
}
129
136
130
137
private function ensureColumn(string $table, string $column, string $ddl): void
@@ -1123,27 +1130,97 @@ SQL);
1123
1130
]);
1124
1131
}
1125
1132
1133
/**
1134
* Cached public auth profiles (GET /api/profiles). Fresh hits only
1135
* unless $allowStale is set (auth unreachable).
1136
*
1137
* @param list<string> $userIds
1138
* @return array<string, array{id:string,name:string,avatar:?string}>
1139
*/
1140
public function readProfilesCache(array $userIds, ?int $now = null, bool $allowStale = false): array
1141
{
1142
$out = [];
1143
$now = $now ?? $this->now();
1144
foreach ($userIds as $id) {
1145
if (!is_string($id) || $id === '') {
1146
continue;
1147
}
1148
$stmt = $this->pdo->prepare('SELECT name, avatar, fetched FROM profiles_cache WHERE user_id = ?');
1149
$stmt->execute([$id]);
1150
$row = $stmt->fetch();
1151
if (!$row) {
1152
continue;
1153
}
1154
$fetched = (int) $row['fetched'];
1155
if (!$allowStale && ($now - $fetched) > self::PROFILES_CACHE_TTL) {
1156
continue;
1157
}
1158
$out[$id] = [
1159
'id' => $id,
1160
'name' => (string) $row['name'],
1161
'avatar' => isset($row['avatar']) && $row['avatar'] !== '' ? (string) $row['avatar'] : null,
1162
];
1163
}
1164
return $out;
1165
}
1166
1167
/** @param list<array{id:string,name:string,avatar:?string}> $identities */
1168
public function writeProfilesCache(array $identities, ?int $fetchedAt = null): void
1169
{
1170
$fetchedAt = $fetchedAt ?? $this->now();
1171
$stmt = $this->pdo->prepare(
1172
'INSERT INTO profiles_cache (user_id, name, avatar, fetched) VALUES (?,?,?,?)
1173
ON CONFLICT(user_id) DO UPDATE SET name = excluded.name, avatar = excluded.avatar, fetched = excluded.fetched'
1174
);
1175
foreach ($identities as $row) {
1176
if (!is_array($row) || !isset($row['id'], $row['name']) || !is_string($row['id']) || $row['id'] === '') {
1177
continue;
1178
}
1179
$name = trim((string) $row['name']);
1180
if ($name === '') {
1181
continue;
1182
}
1183
$avatar = $row['avatar'] ?? null;
1184
$stmt->execute([
1185
$row['id'],
1186
$name,
1187
is_string($avatar) && $avatar !== '' ? $avatar : null,
1188
$fetchedAt,
1189
]);
1190
}
1191
}
1192
1126
1193
public function locale(string $userId): ?string
1127
1194
{
1128
1195
$v = $this->ensureProfile($userId)['locale'] ?? null;
1129
1196
return is_string($v) && $v !== '' ? $v : null;
1130
1197
}
1131
1198
1199
public function localeExplicit(string $userId): bool
1200
{
1201
$row = $this->ensureProfile($userId);
1202
return (int) ($row['locale_explicit'] ?? 0) === 1;
1203
}
1204
1132
1205
/** Seconds to reuse a viewer's auth friends list before refetching. */
1133
1206
public const FRIENDS_CACHE_TTL = 600;
1134
1207
1208
/** Seconds to reuse a public auth profile (name/avatar) before refetching. */
1209
public const PROFILES_CACHE_TTL = 600;
1210
1135
1211
/** @var list<string> */
1136
1212
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
1137
1213
1138
1214
public function setLocale(string $userId, string $locale): string
1139
1215
{
1140
$locale = strtolower($locale);
1141
if (!in_array($locale, self::LOCALES, true)) {
1216
$locale = normalizeAuthLocale($locale);
1217
if ($locale === null || !in_array($locale, self::LOCALES, true)) {
1142
1218
throw new RuntimeException('Onbekende taal.');
1143
1219
}
1144
1220
$this->ensureProfile($userId);
1145
$this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
1146
->execute([$locale, $this->now(), $userId]);
1221
$this->pdo->prepare(
1222
'UPDATE profiles SET locale = ?, locale_explicit = 1, updated = ? WHERE user_id = ?'
1223
)->execute([$locale, $this->now(), $userId]);
1147
1224
return $locale;
1148
1225
}
1149
1226
@@ -1421,6 +1498,7 @@ SQL);
1421
1498
return [
1422
1499
'lifetime_points' => $points,
1423
1500
'locale' => $this->locale($userId),
1501
'locale_explicit' => $this->localeExplicit($userId),
1424
1502
'last_planet' => $this->lastPlanet($userId),
1425
1503
'blocks' => Blocks::present($points),
1426
1504
'planets' => $this->listCustomPlanets($userId),
@@ -124,7 +124,14 @@ CREATE TABLE IF NOT EXISTS friends_cache (124
payload TEXT NOT NULL,124
payload TEXT NOT NULL,125
fetched INTEGER NOT NULL125
fetched INTEGER NOT NULL126
);126
);127
CREATE TABLE IF NOT EXISTS profiles_cache (128
user_id TEXT PRIMARY KEY,129
name TEXT NOT NULL,130
avatar TEXT,131
fetched INTEGER NOT NULL132
);127
SQL);133
SQL);134
$this->ensureColumn('profiles', 'locale_explicit', 'INTEGER NOT NULL DEFAULT 0');128
}135
}129
136
130
private function ensureColumn(string $table, string $column, string $ddl): void137
private function ensureColumn(string $table, string $column, string $ddl): void@@ -1123,27 +1130,97 @@ SQL);1123
]);1130
]);1124
}1131
}1125
1132
1133
/**1134
* Cached public auth profiles (GET /api/profiles). Fresh hits only1135
* unless $allowStale is set (auth unreachable).1136
*1137
* @param list<string> $userIds1138
* @return array<string, array{id:string,name:string,avatar:?string}>1139
*/1140
public function readProfilesCache(array $userIds, ?int $now = null, bool $allowStale = false): array1141
{1142
$out = [];1143
$now = $now ?? $this->now();1144
foreach ($userIds as $id) {1145
if (!is_string($id) || $id === '') {1146
continue;1147
}1148
$stmt = $this->pdo->prepare('SELECT name, avatar, fetched FROM profiles_cache WHERE user_id = ?');1149
$stmt->execute([$id]);1150
$row = $stmt->fetch();1151
if (!$row) {1152
continue;1153
}1154
$fetched = (int) $row['fetched'];1155
if (!$allowStale && ($now - $fetched) > self::PROFILES_CACHE_TTL) {1156
continue;1157
}1158
$out[$id] = [1159
'id' => $id,1160
'name' => (string) $row['name'],1161
'avatar' => isset($row['avatar']) && $row['avatar'] !== '' ? (string) $row['avatar'] : null,1162
];1163
}1164
return $out;1165
}1166
1167
/** @param list<array{id:string,name:string,avatar:?string}> $identities */1168
public function writeProfilesCache(array $identities, ?int $fetchedAt = null): void1169
{1170
$fetchedAt = $fetchedAt ?? $this->now();1171
$stmt = $this->pdo->prepare(1172
'INSERT INTO profiles_cache (user_id, name, avatar, fetched) VALUES (?,?,?,?)1173
ON CONFLICT(user_id) DO UPDATE SET name = excluded.name, avatar = excluded.avatar, fetched = excluded.fetched'1174
);1175
foreach ($identities as $row) {1176
if (!is_array($row) || !isset($row['id'], $row['name']) || !is_string($row['id']) || $row['id'] === '') {1177
continue;1178
}1179
$name = trim((string) $row['name']);1180
if ($name === '') {1181
continue;1182
}1183
$avatar = $row['avatar'] ?? null;1184
$stmt->execute([1185
$row['id'],1186
$name,1187
is_string($avatar) && $avatar !== '' ? $avatar : null,1188
$fetchedAt,1189
]);1190
}1191
}1192
1126
public function locale(string $userId): ?string1193
public function locale(string $userId): ?string1127
{1194
{1128
$v = $this->ensureProfile($userId)['locale'] ?? null;1195
$v = $this->ensureProfile($userId)['locale'] ?? null;1129
return is_string($v) && $v !== '' ? $v : null;1196
return is_string($v) && $v !== '' ? $v : null;1130
}1197
}1131
1198
1199
public function localeExplicit(string $userId): bool1200
{1201
$row = $this->ensureProfile($userId);1202
return (int) ($row['locale_explicit'] ?? 0) === 1;1203
}1204
1132
/** Seconds to reuse a viewer's auth friends list before refetching. */1205
/** Seconds to reuse a viewer's auth friends list before refetching. */1133
public const FRIENDS_CACHE_TTL = 600;1206
public const FRIENDS_CACHE_TTL = 600;1134
1207
1208
/** Seconds to reuse a public auth profile (name/avatar) before refetching. */1209
public const PROFILES_CACHE_TTL = 600;1210
1135
/** @var list<string> */1211
/** @var list<string> */1136
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];1212
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];1137
1213
1138
public function setLocale(string $userId, string $locale): string1214
public function setLocale(string $userId, string $locale): string1139
{1215
{1140
$locale = strtolower($locale);1216
$locale = normalizeAuthLocale($locale);1141
if (!in_array($locale, self::LOCALES, true)) {1217
if ($locale === null || !in_array($locale, self::LOCALES, true)) {1142
throw new RuntimeException('Onbekende taal.');1218
throw new RuntimeException('Onbekende taal.');1143
}1219
}1144
$this->ensureProfile($userId);1220
$this->ensureProfile($userId);1145
$this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')1221
$this->pdo->prepare(1146
->execute([$locale, $this->now(), $userId]);1222
'UPDATE profiles SET locale = ?, locale_explicit = 1, updated = ? WHERE user_id = ?'1223
)->execute([$locale, $this->now(), $userId]);1147
return $locale;1224
return $locale;1148
}1225
}1149
1226
@@ -1421,6 +1498,7 @@ SQL);1421
return [1498
return [1422
'lifetime_points' => $points,1499
'lifetime_points' => $points,1423
'locale' => $this->locale($userId),1500
'locale' => $this->locale($userId),1501
'locale_explicit' => $this->localeExplicit($userId),1424
'last_planet' => $this->lastPlanet($userId),1502
'last_planet' => $this->lastPlanet($userId),1425
'blocks' => Blocks::present($points),1503
'blocks' => Blocks::present($points),1426
'planets' => $this->listCustomPlanets($userId),1504
'planets' => $this->listCustomPlanets($userId),@@ -201,6 +201,193 @@ function isPlaceholderName(string $userId, ?string $name): bool
201
201
return false;
202
202
}
203
203
204
/**
205
* Map an auth.timfalken.com OIDC locale claim (BCP 47, e.g. zh-Hans)
206
* to a Meteors locale id (zh). Unknown values become null.
207
*/
208
function normalizeAuthLocale($claim): ?string
209
{
210
if (!is_string($claim) || $claim === '') {
211
return null;
212
}
213
$id = strtolower(str_replace('_', '-', trim($claim)));
214
if ($id === 'zh-hans' || $id === 'zh-cn' || $id === 'zh-sg' || $id === 'zh-my') {
215
return 'zh';
216
}
217
$known = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
218
if (in_array($id, $known, true)) {
219
return $id;
220
}
221
$primary = explode('-', $id, 2)[0];
222
return in_array($primary, $known, true) ? $primary : null;
223
}
224
225
/** Locale claim from a token or /api/me payload (user.locale or locale). */
226
function authLocaleFromPayload($data): ?string
227
{
228
if (!is_array($data)) {
229
return null;
230
}
231
if (isset($data['user']) && is_array($data['user'])) {
232
$fromUser = normalizeAuthLocale($data['user']['locale'] ?? null);
233
if ($fromUser !== null) {
234
return $fromUser;
235
}
236
}
237
return normalizeAuthLocale($data['locale'] ?? null);
238
}
239
240
function storeAuthLocale(?string $claim): ?string
241
{
242
$id = normalizeAuthLocale($claim);
243
if ($id === null) {
244
unset($_SESSION['auth_locale']);
245
return null;
246
}
247
$_SESSION['auth_locale'] = $id;
248
return $id;
249
}
250
251
function sessionAuthLocale(): ?string
252
{
253
return normalizeAuthLocale($_SESSION['auth_locale'] ?? null);
254
}
255
256
/**
257
* Prefer the session value; when a bearer token is given, refresh from
258
* GET /api/me so a language change on auth.timfalken.com is picked up.
259
*/
260
function refreshAuthLocale(?string $token): ?string
261
{
262
$current = sessionAuthLocale();
263
if (!is_string($token) || $token === '') {
264
return $current;
265
}
266
try {
267
$fresh = authLocaleFromPayload(authRequest('/api/me', null, $token));
268
if ($fresh !== null) {
269
$_SESSION['auth_locale'] = $fresh;
270
return $fresh;
271
}
272
} catch (Throwable $e) {
273
// Keep the value from login / the last successful refresh.
274
}
275
return $current;
276
}
277
278
/** Numeric auth id from a Meteors user id like auth:3, or null. */
279
function authNumericId(string $userId): ?int
280
{
281
if (!preg_match('/^auth:([1-9][0-9]{0,17})$/', $userId, $m)) {
282
return null;
283
}
284
return (int) $m[1];
285
}
286
287
/**
288
* Parse GET /api/profiles from auth.timfalken.com.
289
*
290
* @return list<array{id:string,name:string,avatar:?string}>
291
*/
292
function parseAuthProfiles($data): array
293
{
294
if (!is_array($data) || !isset($data['profiles']) || !is_array($data['profiles'])) {
295
return [];
296
}
297
$out = [];
298
foreach ($data['profiles'] as $p) {
299
if (!is_array($p) || !isset($p['id'])) {
300
continue;
301
}
302
$raw = $p['id'];
303
$numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
304
if (!$numeric || (int) $raw < 1) {
305
continue;
306
}
307
$name = isset($p['username']) && is_string($p['username']) ? trim($p['username']) : '';
308
if ($name === '' || mb_strlen($name) > 64) {
309
continue;
310
}
311
$out[] = [
312
'id' => 'auth:' . (int) $raw,
313
'name' => $name,
314
'avatar' => authAvatarUrl($p),
315
];
316
}
317
return $out;
318
}
319
320
/** Max ids per GET /api/profiles request (auth limit). */
321
const AUTH_PROFILES_MAX_IDS = 50;
322
323
/**
324
* Public names/avatars for auth:* ids via GET /api/profiles, cached
325
* in Meteors storage for Store::PROFILES_CACHE_TTL seconds. On auth
326
* failure, a stale cache or an empty list is returned (callers keep
327
* existing fallbacks).
328
*
329
* @param list<string> $userIds
330
* @return array<string, array{id:string,name:string,avatar:?string}>
331
*/
332
function authGetJson(string $path, ?string $token = null): array
333
{
334
$hook = $GLOBALS['METEORS_AUTH_GET'] ?? null;
335
if (is_callable($hook)) {
336
return $hook($path, $token);
337
}
338
return authRequest($path, null, $token);
339
}
340
341
function fetchAuthProfiles(Store $store, array $userIds): array
342
{
343
$wanted = [];
344
foreach ($userIds as $id) {
345
if (!is_string($id)) {
346
continue;
347
}
348
$num = authNumericId($id);
349
if ($num !== null) {
350
$wanted['auth:' . $num] = $num;
351
}
352
}
353
if ($wanted === []) {
354
return [];
355
}
356
$ids = array_keys($wanted);
357
$known = $store->readProfilesCache($ids);
358
$missing = [];
359
foreach ($ids as $id) {
360
if (!isset($known[$id])) {
361
$missing[] = $wanted[$id];
362
}
363
}
364
if ($missing === []) {
365
return $known;
366
}
367
$missing = array_values(array_unique($missing));
368
try {
369
$fetched = [];
370
foreach (array_chunk($missing, AUTH_PROFILES_MAX_IDS) as $chunk) {
371
$path = '/api/profiles?ids=' . implode(',', $chunk);
372
foreach (parseAuthProfiles(authGetJson($path)) as $row) {
373
$fetched[] = $row;
374
$known[$row['id']] = $row;
375
}
376
}
377
if ($fetched !== []) {
378
$store->writeProfilesCache($fetched);
379
}
380
} catch (Throwable $e) {
381
$stale = $store->readProfilesCache($ids, null, true);
382
foreach ($stale as $id => $row) {
383
if (!isset($known[$id])) {
384
$known[$id] = $row;
385
}
386
}
387
}
388
return $known;
389
}
390
204
391
function authAvatarUrl(array $profile): ?string
205
392
{
206
393
foreach (['avatar_url', 'avatar', 'picture'] as $k) {
@@ -302,7 +489,7 @@ function fetchViewerFriends(Store $store, array $user, $token): array
302
489
*
303
490
* @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}
304
491
*/
305
function leaderboardKnownIdentities(Store $store, ?array $user, $token): array
492
function leaderboardKnownIdentities(Store $store, ?array $user, $token, array $playerIds = []): array
306
493
{
307
494
$known = [];
308
495
$friends = [];
@@ -319,6 +506,20 @@ function leaderboardKnownIdentities(Store $store, ?array $user, $token): array
319
506
$known[$f['id']] = $f;
320
507
}
321
508
}
509
}
510
$ids = $playerIds;
511
foreach ($friends as $f) {
512
if (isset($f['id']) && is_string($f['id'])) {
513
$ids[] = $f['id'];
514
}
515
}
516
if ($user && isset($user['id'])) {
517
$ids[] = (string) $user['id'];
518
}
519
foreach (fetchAuthProfiles($store, $ids) as $id => $ident) {
520
$known[$id] = $ident;
521
}
522
if ($known !== []) {
322
523
$store->rememberIdentities(array_values($known));
323
524
}
324
525
return [$known, $friends, $error];
@@ -201,6 +201,193 @@ function isPlaceholderName(string $userId, ?string $name): bool201
return false;201
return false;202
}202
}203
203
204
/**205
* Map an auth.timfalken.com OIDC locale claim (BCP 47, e.g. zh-Hans)206
* to a Meteors locale id (zh). Unknown values become null.207
*/208
function normalizeAuthLocale($claim): ?string209
{210
if (!is_string($claim) || $claim === '') {211
return null;212
}213
$id = strtolower(str_replace('_', '-', trim($claim)));214
if ($id === 'zh-hans' || $id === 'zh-cn' || $id === 'zh-sg' || $id === 'zh-my') {215
return 'zh';216
}217
$known = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];218
if (in_array($id, $known, true)) {219
return $id;220
}221
$primary = explode('-', $id, 2)[0];222
return in_array($primary, $known, true) ? $primary : null;223
}224
225
/** Locale claim from a token or /api/me payload (user.locale or locale). */226
function authLocaleFromPayload($data): ?string227
{228
if (!is_array($data)) {229
return null;230
}231
if (isset($data['user']) && is_array($data['user'])) {232
$fromUser = normalizeAuthLocale($data['user']['locale'] ?? null);233
if ($fromUser !== null) {234
return $fromUser;235
}236
}237
return normalizeAuthLocale($data['locale'] ?? null);238
}239
240
function storeAuthLocale(?string $claim): ?string241
{242
$id = normalizeAuthLocale($claim);243
if ($id === null) {244
unset($_SESSION['auth_locale']);245
return null;246
}247
$_SESSION['auth_locale'] = $id;248
return $id;249
}250
251
function sessionAuthLocale(): ?string252
{253
return normalizeAuthLocale($_SESSION['auth_locale'] ?? null);254
}255
256
/**257
* Prefer the session value; when a bearer token is given, refresh from258
* GET /api/me so a language change on auth.timfalken.com is picked up.259
*/260
function refreshAuthLocale(?string $token): ?string261
{262
$current = sessionAuthLocale();263
if (!is_string($token) || $token === '') {264
return $current;265
}266
try {267
$fresh = authLocaleFromPayload(authRequest('/api/me', null, $token));268
if ($fresh !== null) {269
$_SESSION['auth_locale'] = $fresh;270
return $fresh;271
}272
} catch (Throwable $e) {273
// Keep the value from login / the last successful refresh.274
}275
return $current;276
}277
278
/** Numeric auth id from a Meteors user id like auth:3, or null. */279
function authNumericId(string $userId): ?int280
{281
if (!preg_match('/^auth:([1-9][0-9]{0,17})$/', $userId, $m)) {282
return null;283
}284
return (int) $m[1];285
}286
287
/**288
* Parse GET /api/profiles from auth.timfalken.com.289
*290
* @return list<array{id:string,name:string,avatar:?string}>291
*/292
function parseAuthProfiles($data): array293
{294
if (!is_array($data) || !isset($data['profiles']) || !is_array($data['profiles'])) {295
return [];296
}297
$out = [];298
foreach ($data['profiles'] as $p) {299
if (!is_array($p) || !isset($p['id'])) {300
continue;301
}302
$raw = $p['id'];303
$numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));304
if (!$numeric || (int) $raw < 1) {305
continue;306
}307
$name = isset($p['username']) && is_string($p['username']) ? trim($p['username']) : '';308
if ($name === '' || mb_strlen($name) > 64) {309
continue;310
}311
$out[] = [312
'id' => 'auth:' . (int) $raw,313
'name' => $name,314
'avatar' => authAvatarUrl($p),315
];316
}317
return $out;318
}319
320
/** Max ids per GET /api/profiles request (auth limit). */321
const AUTH_PROFILES_MAX_IDS = 50;322
323
/**324
* Public names/avatars for auth:* ids via GET /api/profiles, cached325
* in Meteors storage for Store::PROFILES_CACHE_TTL seconds. On auth326
* failure, a stale cache or an empty list is returned (callers keep327
* existing fallbacks).328
*329
* @param list<string> $userIds330
* @return array<string, array{id:string,name:string,avatar:?string}>331
*/332
function authGetJson(string $path, ?string $token = null): array333
{334
$hook = $GLOBALS['METEORS_AUTH_GET'] ?? null;335
if (is_callable($hook)) {336
return $hook($path, $token);337
}338
return authRequest($path, null, $token);339
}340
341
function fetchAuthProfiles(Store $store, array $userIds): array342
{343
$wanted = [];344
foreach ($userIds as $id) {345
if (!is_string($id)) {346
continue;347
}348
$num = authNumericId($id);349
if ($num !== null) {350
$wanted['auth:' . $num] = $num;351
}352
}353
if ($wanted === []) {354
return [];355
}356
$ids = array_keys($wanted);357
$known = $store->readProfilesCache($ids);358
$missing = [];359
foreach ($ids as $id) {360
if (!isset($known[$id])) {361
$missing[] = $wanted[$id];362
}363
}364
if ($missing === []) {365
return $known;366
}367
$missing = array_values(array_unique($missing));368
try {369
$fetched = [];370
foreach (array_chunk($missing, AUTH_PROFILES_MAX_IDS) as $chunk) {371
$path = '/api/profiles?ids=' . implode(',', $chunk);372
foreach (parseAuthProfiles(authGetJson($path)) as $row) {373
$fetched[] = $row;374
$known[$row['id']] = $row;375
}376
}377
if ($fetched !== []) {378
$store->writeProfilesCache($fetched);379
}380
} catch (Throwable $e) {381
$stale = $store->readProfilesCache($ids, null, true);382
foreach ($stale as $id => $row) {383
if (!isset($known[$id])) {384
$known[$id] = $row;385
}386
}387
}388
return $known;389
}390
204
function authAvatarUrl(array $profile): ?string391
function authAvatarUrl(array $profile): ?string205
{392
{206
foreach (['avatar_url', 'avatar', 'picture'] as $k) {393
foreach (['avatar_url', 'avatar', 'picture'] as $k) {@@ -302,7 +489,7 @@ function fetchViewerFriends(Store $store, array $user, $token): array302
*489
*303
* @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}490
* @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}304
*/491
*/305
function leaderboardKnownIdentities(Store $store, ?array $user, $token): array492
function leaderboardKnownIdentities(Store $store, ?array $user, $token, array $playerIds = []): array306
{493
{307
$known = [];494
$known = [];308
$friends = [];495
$friends = [];@@ -319,6 +506,20 @@ function leaderboardKnownIdentities(Store $store, ?array $user, $token): array319
$known[$f['id']] = $f;506
$known[$f['id']] = $f;320
}507
}321
}508
}509
}510
$ids = $playerIds;511
foreach ($friends as $f) {512
if (isset($f['id']) && is_string($f['id'])) {513
$ids[] = $f['id'];514
}515
}516
if ($user && isset($user['id'])) {517
$ids[] = (string) $user['id'];518
}519
foreach (fetchAuthProfiles($store, $ids) as $id => $ident) {520
$known[$id] = $ident;521
}522
if ($known !== []) {322
$store->rememberIdentities(array_values($known));523
$store->rememberIdentities(array_values($known));323
}524
}324
return [$known, $friends, $error];525
return [$known, $friends, $error];@@ -715,6 +715,128 @@ expect(strpos($apiSrc, "action === 'leaderboard'") !== false, 'api.php has a lea
715
715
expect(strpos($apiSrc, 'leaderboardKnownIdentities(') !== false, 'leaderboard resolves names via cached auth friends');
716
716
$bootSrc = (string) file_get_contents(dirname(__DIR__) . '/lib/bootstrap.php');
717
717
expect(strpos($bootSrc, "authRequest('/api/friends'") !== false, 'friends are fetched from GET /api/friends on auth.timfalken.com');
718
expect(strpos($bootSrc, "/api/profiles") !== false, 'leaderboard names also come from public GET /api/profiles');
719
720
echo "Auth locale claim (t1250)\n";
721
expect(normalizeAuthLocale('zh-Hans') === 'zh', 'zh-Hans maps to zh');
722
expect(normalizeAuthLocale('zh-hans') === 'zh', 'zh-hans maps to zh');
723
expect(normalizeAuthLocale('zh_CN') === 'zh', 'zh_CN maps to zh');
724
expect(normalizeAuthLocale('nl') === 'nl', 'nl stays nl');
725
expect(normalizeAuthLocale('en-US') === 'en', 'en-US falls back to en');
726
expect(normalizeAuthLocale('xx') === null, 'unknown claim is null');
727
expect(normalizeAuthLocale('') === null, 'empty claim is null');
728
expect(authLocaleFromPayload(['user' => ['locale' => 'zh-Hans']]) === 'zh', '/api/me user.locale is read');
729
expect(authLocaleFromPayload(['locale' => 'de']) === 'de', 'top-level locale is read');
730
expect(authNumericId('auth:15') === 15, 'auth:15 → 15');
731
expect(authNumericId('local:test_user_1') === null, 'local testers are not auth ids');
732
733
$locUser = 'local:test_user_1';
734
$locStore = Store::open($tmp . '/locale-t1250');
735
expect($locStore->locale($locUser) === null, 'new profile has no stored locale');
736
expect($locStore->localeExplicit($locUser) === false, 'new profile is not an explicit in-game choice');
737
expect($locStore->setLocale($locUser, 'zh-Hans') === 'zh', 'setLocale accepts zh-Hans');
738
expect($locStore->locale($locUser) === 'zh' && $locStore->localeExplicit($locUser) === true, 'in-game set_locale marks the choice explicit');
739
$payload = $locStore->profilePayload($locUser);
740
expect(!empty($payload['locale_explicit']) && $payload['locale'] === 'zh', 'profilePayload exposes locale_explicit');
741
742
echo "Public auth profiles (t1253)\n";
743
$parsed = parseAuthProfiles([
744
'profiles' => [
745
['id' => 2, 'username' => 'daniqueaben', 'avatar_url' => null],
746
['id' => 3, 'username' => 'lucia'],
747
['id' => 15, 'username' => 'emma', 'avatar_url' => 'https://auth.timfalken.com/avatar/15?v=1'],
748
['id' => 'nope', 'username' => 'bad'],
749
['id' => 1, 'username' => ''],
750
'x',
751
],
752
]);
753
expect(count($parsed) === 3, 'parseAuthProfiles keeps valid rows (got ' . count($parsed) . ')');
754
expect($parsed[0]['id'] === 'auth:2' && $parsed[0]['name'] === 'daniqueaben', 'id 2 → auth:2 / daniqueaben');
755
expect($parsed[2]['avatar'] === 'https://auth.timfalken.com/avatar/15?v=1', 'avatar_url is kept');
756
757
$pr = Store::open($tmp . '/profiles-t1253');
758
$pr->testNow = 5000;
759
$pr->awardPoints('auth:2', 10, 't1253-a', 'solo');
760
$pr->awardPoints('auth:3', 20, 't1253-b', 'solo');
761
$pr->awardPoints('auth:15', 1, 't1253-c', 'solo');
762
$calls = [];
763
$GLOBALS['METEORS_AUTH_GET'] = function (string $path, $token = null) use (&$calls) {
764
$calls[] = $path;
765
if (!str_starts_with($path, '/api/profiles?ids=')) {
766
throw new RuntimeException('unexpected path ' . $path);
767
}
768
$q = substr($path, strlen('/api/profiles?ids='));
769
$ids = array_map('intval', explode(',', $q));
770
$names = [2 => 'daniqueaben', 3 => 'lucia', 15 => 'emma'];
771
$rows = [];
772
foreach ($ids as $id) {
773
if (isset($names[$id])) {
774
$rows[] = ['id' => $id, 'username' => $names[$id], 'avatar_url' => null];
775
}
776
}
777
return ['profiles' => $rows];
778
};
779
$got = fetchAuthProfiles($pr, ['auth:2', 'auth:3', 'auth:15', 'local:test_user_1']);
780
expect(isset($got['auth:2'], $got['auth:3'], $got['auth:15']), 'fetchAuthProfiles returns all auth ids');
781
expect($got['auth:3']['name'] === 'lucia' && $got['auth:2']['name'] === 'daniqueaben' && $got['auth:15']['name'] === 'emma', 'usernames from /api/profiles');
782
expect(count($calls) === 1, 'one batched /api/profiles request (got ' . count($calls) . ')');
783
expect(!str_contains($calls[0], 'local:'), 'local testers are not sent to auth');
784
$calls = [];
785
$again = fetchAuthProfiles($pr, ['auth:3']);
786
expect($again['auth:3']['name'] === 'lucia' && $calls === [], 'fresh profiles cache is reused');
787
$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL + 1;
788
$calls = [];
789
fetchAuthProfiles($pr, ['auth:3']);
790
expect(count($calls) === 1, 'stale profiles cache is refetched');
791
792
// Auth down: stale cache still fills names; no cache keeps fallbacks.
793
$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL * 3;
794
$GLOBALS['METEORS_AUTH_GET'] = function () {
795
throw new RuntimeException('auth down');
796
};
797
$stale = fetchAuthProfiles($pr, ['auth:3']);
798
expect($stale['auth:3']['name'] === 'lucia', 'stale profiles cache is used when auth is unreachable');
799
800
$emptyStore = Store::open($tmp . '/profiles-t1253-empty');
801
$emptyStore->testNow = 1;
802
$down = fetchAuthProfiles($emptyStore, ['auth:9']);
803
expect($down === [], 'no cache and auth down → empty (caller keeps fallbacks)');
804
805
$board = $pr->topPlayers(10, null);
806
$filled = $pr->applyIdentities($board, $got);
807
$names = [];
808
foreach ($filled as $row) {
809
$names[$row['id']] = $row['name'];
810
}
811
expect(($names['auth:3'] ?? '') === 'lucia', 'applyIdentities shows lucia instead of 3');
812
$pr->rememberIdentities(array_values($got));
813
$later = $pr->topPlayers(10, null);
814
$storedNames = [];
815
foreach ($later as $row) {
816
$storedNames[$row['id']] = $row['name'];
817
}
818
expect(($storedNames['auth:2'] ?? '') === 'daniqueaben', 'backfill stores daniqueaben for later guests');
819
expect(($storedNames['auth:15'] ?? '') === 'emma', 'backfill stores emma');
820
821
$many = [];
822
for ($i = 1; $i <= 51; $i++) {
823
$many[] = 'auth:' . $i;
824
}
825
$chunks = [];
826
$GLOBALS['METEORS_AUTH_GET'] = function (string $path) use (&$chunks) {
827
$chunks[] = $path;
828
return ['profiles' => []];
829
};
830
$fresh = Store::open($tmp . '/profiles-t1253-chunk');
831
fetchAuthProfiles($fresh, $many);
832
expect(count($chunks) === 2, 'more than 50 ids are split into two /api/profiles calls (got ' . count($chunks) . ')');
833
unset($GLOBALS['METEORS_AUTH_GET']);
834
835
$srcApi = (string) file_get_contents(dirname(__DIR__) . '/api.php');
836
expect(strpos($srcApi, 'auth_locale') !== false, 'me/poll expose auth_locale');
837
expect(strpos($srcApi, 'locale_explicit') !== false, 'me/poll expose locale_explicit');
838
$cbSrc = (string) file_get_contents(dirname(__DIR__) . '/callback.php');
839
expect(strpos($cbSrc, 'storeAuthLocale') !== false, 'callback stores the OIDC locale claim');
718
840
719
841
echo "\nConfig helpers\n";
720
842
@@ -715,6 +715,128 @@ expect(strpos($apiSrc, "action === 'leaderboard'") !== false, 'api.php has a lea715
expect(strpos($apiSrc, 'leaderboardKnownIdentities(') !== false, 'leaderboard resolves names via cached auth friends');715
expect(strpos($apiSrc, 'leaderboardKnownIdentities(') !== false, 'leaderboard resolves names via cached auth friends');716
$bootSrc = (string) file_get_contents(dirname(__DIR__) . '/lib/bootstrap.php');716
$bootSrc = (string) file_get_contents(dirname(__DIR__) . '/lib/bootstrap.php');717
expect(strpos($bootSrc, "authRequest('/api/friends'") !== false, 'friends are fetched from GET /api/friends on auth.timfalken.com');717
expect(strpos($bootSrc, "authRequest('/api/friends'") !== false, 'friends are fetched from GET /api/friends on auth.timfalken.com');718
expect(strpos($bootSrc, "/api/profiles") !== false, 'leaderboard names also come from public GET /api/profiles');719
720
echo "Auth locale claim (t1250)\n";721
expect(normalizeAuthLocale('zh-Hans') === 'zh', 'zh-Hans maps to zh');722
expect(normalizeAuthLocale('zh-hans') === 'zh', 'zh-hans maps to zh');723
expect(normalizeAuthLocale('zh_CN') === 'zh', 'zh_CN maps to zh');724
expect(normalizeAuthLocale('nl') === 'nl', 'nl stays nl');725
expect(normalizeAuthLocale('en-US') === 'en', 'en-US falls back to en');726
expect(normalizeAuthLocale('xx') === null, 'unknown claim is null');727
expect(normalizeAuthLocale('') === null, 'empty claim is null');728
expect(authLocaleFromPayload(['user' => ['locale' => 'zh-Hans']]) === 'zh', '/api/me user.locale is read');729
expect(authLocaleFromPayload(['locale' => 'de']) === 'de', 'top-level locale is read');730
expect(authNumericId('auth:15') === 15, 'auth:15 → 15');731
expect(authNumericId('local:test_user_1') === null, 'local testers are not auth ids');732
733
$locUser = 'local:test_user_1';734
$locStore = Store::open($tmp . '/locale-t1250');735
expect($locStore->locale($locUser) === null, 'new profile has no stored locale');736
expect($locStore->localeExplicit($locUser) === false, 'new profile is not an explicit in-game choice');737
expect($locStore->setLocale($locUser, 'zh-Hans') === 'zh', 'setLocale accepts zh-Hans');738
expect($locStore->locale($locUser) === 'zh' && $locStore->localeExplicit($locUser) === true, 'in-game set_locale marks the choice explicit');739
$payload = $locStore->profilePayload($locUser);740
expect(!empty($payload['locale_explicit']) && $payload['locale'] === 'zh', 'profilePayload exposes locale_explicit');741
742
echo "Public auth profiles (t1253)\n";743
$parsed = parseAuthProfiles([744
'profiles' => [745
['id' => 2, 'username' => 'daniqueaben', 'avatar_url' => null],746
['id' => 3, 'username' => 'lucia'],747
['id' => 15, 'username' => 'emma', 'avatar_url' => 'https://auth.timfalken.com/avatar/15?v=1'],748
['id' => 'nope', 'username' => 'bad'],749
['id' => 1, 'username' => ''],750
'x',751
],752
]);753
expect(count($parsed) === 3, 'parseAuthProfiles keeps valid rows (got ' . count($parsed) . ')');754
expect($parsed[0]['id'] === 'auth:2' && $parsed[0]['name'] === 'daniqueaben', 'id 2 → auth:2 / daniqueaben');755
expect($parsed[2]['avatar'] === 'https://auth.timfalken.com/avatar/15?v=1', 'avatar_url is kept');756
757
$pr = Store::open($tmp . '/profiles-t1253');758
$pr->testNow = 5000;759
$pr->awardPoints('auth:2', 10, 't1253-a', 'solo');760
$pr->awardPoints('auth:3', 20, 't1253-b', 'solo');761
$pr->awardPoints('auth:15', 1, 't1253-c', 'solo');762
$calls = [];763
$GLOBALS['METEORS_AUTH_GET'] = function (string $path, $token = null) use (&$calls) {764
$calls[] = $path;765
if (!str_starts_with($path, '/api/profiles?ids=')) {766
throw new RuntimeException('unexpected path ' . $path);767
}768
$q = substr($path, strlen('/api/profiles?ids='));769
$ids = array_map('intval', explode(',', $q));770
$names = [2 => 'daniqueaben', 3 => 'lucia', 15 => 'emma'];771
$rows = [];772
foreach ($ids as $id) {773
if (isset($names[$id])) {774
$rows[] = ['id' => $id, 'username' => $names[$id], 'avatar_url' => null];775
}776
}777
return ['profiles' => $rows];778
};779
$got = fetchAuthProfiles($pr, ['auth:2', 'auth:3', 'auth:15', 'local:test_user_1']);780
expect(isset($got['auth:2'], $got['auth:3'], $got['auth:15']), 'fetchAuthProfiles returns all auth ids');781
expect($got['auth:3']['name'] === 'lucia' && $got['auth:2']['name'] === 'daniqueaben' && $got['auth:15']['name'] === 'emma', 'usernames from /api/profiles');782
expect(count($calls) === 1, 'one batched /api/profiles request (got ' . count($calls) . ')');783
expect(!str_contains($calls[0], 'local:'), 'local testers are not sent to auth');784
$calls = [];785
$again = fetchAuthProfiles($pr, ['auth:3']);786
expect($again['auth:3']['name'] === 'lucia' && $calls === [], 'fresh profiles cache is reused');787
$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL + 1;788
$calls = [];789
fetchAuthProfiles($pr, ['auth:3']);790
expect(count($calls) === 1, 'stale profiles cache is refetched');791
792
// Auth down: stale cache still fills names; no cache keeps fallbacks.793
$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL * 3;794
$GLOBALS['METEORS_AUTH_GET'] = function () {795
throw new RuntimeException('auth down');796
};797
$stale = fetchAuthProfiles($pr, ['auth:3']);798
expect($stale['auth:3']['name'] === 'lucia', 'stale profiles cache is used when auth is unreachable');799
800
$emptyStore = Store::open($tmp . '/profiles-t1253-empty');801
$emptyStore->testNow = 1;802
$down = fetchAuthProfiles($emptyStore, ['auth:9']);803
expect($down === [], 'no cache and auth down → empty (caller keeps fallbacks)');804
805
$board = $pr->topPlayers(10, null);806
$filled = $pr->applyIdentities($board, $got);807
$names = [];808
foreach ($filled as $row) {809
$names[$row['id']] = $row['name'];810
}811
expect(($names['auth:3'] ?? '') === 'lucia', 'applyIdentities shows lucia instead of 3');812
$pr->rememberIdentities(array_values($got));813
$later = $pr->topPlayers(10, null);814
$storedNames = [];815
foreach ($later as $row) {816
$storedNames[$row['id']] = $row['name'];817
}818
expect(($storedNames['auth:2'] ?? '') === 'daniqueaben', 'backfill stores daniqueaben for later guests');819
expect(($storedNames['auth:15'] ?? '') === 'emma', 'backfill stores emma');820
821
$many = [];822
for ($i = 1; $i <= 51; $i++) {823
$many[] = 'auth:' . $i;824
}825
$chunks = [];826
$GLOBALS['METEORS_AUTH_GET'] = function (string $path) use (&$chunks) {827
$chunks[] = $path;828
return ['profiles' => []];829
};830
$fresh = Store::open($tmp . '/profiles-t1253-chunk');831
fetchAuthProfiles($fresh, $many);832
expect(count($chunks) === 2, 'more than 50 ids are split into two /api/profiles calls (got ' . count($chunks) . ')');833
unset($GLOBALS['METEORS_AUTH_GET']);834
835
$srcApi = (string) file_get_contents(dirname(__DIR__) . '/api.php');836
expect(strpos($srcApi, 'auth_locale') !== false, 'me/poll expose auth_locale');837
expect(strpos($srcApi, 'locale_explicit') !== false, 'me/poll expose locale_explicit');838
$cbSrc = (string) file_get_contents(dirname(__DIR__) . '/callback.php');839
expect(strpos($cbSrc, 'storeAuthLocale') !== false, 'callback stores the OIDC locale claim');718
840
719
echo "\nConfig helpers\n";841
echo "\nConfig helpers\n";720
842
@@ -21,6 +21,7 @@ var I18n = {
21
21
],
22
22
DEFAULT: 'en',
23
23
STORAGE_KEY: 'meteors-locale',
24
EXPLICIT_KEY: 'meteors-locale-chosen',
24
25
COOKIE: 'meteors-locale',
25
26
locale: 'en',
26
27
_catalog: null,
@@ -57,6 +58,48 @@ I18n.known = function (id)
57
58
return false;
58
59
};
59
60
61
/**
62
* Map a BCP 47 auth claim (zh-Hans) or a stored id to a Meteors locale.
63
* Unknown values return null.
64
*/
65
I18n.normalize = function (id)
66
{
67
if (id == null || id === '')
68
{ return null; }
69
var s = String(id).trim().toLowerCase().replace(/_/g, '-');
70
if (s === 'zh-hans' || s === 'zh-cn' || s === 'zh-sg' || s === 'zh-my')
71
{ return 'zh'; }
72
if (this.known(s))
73
{ return s; }
74
var primary = s.split('-')[0];
75
return this.known(primary) ? primary : null;
76
};
77
78
I18n.hasExplicitChoice = function ()
79
{
80
try
81
{
82
if (typeof localStorage !== 'undefined')
83
{ return localStorage.getItem(this.EXPLICIT_KEY) === '1'; }
84
}
85
catch (e) { /* private mode */ }
86
return false;
87
};
88
89
I18n.markExplicit = function (on)
90
{
91
try
92
{
93
if (typeof localStorage === 'undefined')
94
{ return; }
95
if (on === false)
96
{ localStorage.removeItem(this.EXPLICIT_KEY); }
97
else
98
{ localStorage.setItem(this.EXPLICIT_KEY, '1'); }
99
}
100
catch (e) { /* ignore */ }
101
};
102
60
103
I18n.info = function (id)
61
104
{
62
105
id = id || this.locale;
@@ -235,12 +278,15 @@ I18n._writeStored = function (id)
235
278
I18n.setLocale = function (id, opts)
236
279
{
237
280
opts = opts || {};
238
if (!this.known(id))
281
id = this.normalize(id);
282
if (!id)
239
283
{ id = this.DEFAULT; }
240
284
var changed = id !== this.locale;
241
285
this.locale = id;
242
286
if (opts.persist !== false)
243
287
{ this._writeStored(id); }
288
if (opts.explicit !== false && opts.persist !== false)
289
{ this.markExplicit(); }
244
290
if (typeof document !== 'undefined' && document.documentElement)
245
291
{
246
292
document.documentElement.lang = this.info(id).htmlLang;
@@ -424,8 +470,35 @@ I18n.init = function ()
424
470
425
471
I18n.applyFromProfile = function (locale)
426
472
{
427
if (this.known(locale))
428
{ this.setLocale(locale, { sync: false, persist: true }); }
473
this.applyPreferred({ locale: locale, explicit: true });
474
};
475
476
/**
477
* t1250: an explicit in-game choice always wins. Otherwise a logged-in
478
* player follows the auth OIDC locale (mapped, e.g. zh-Hans → zh).
479
* Guests are left to init()/localStorage.
480
*/
481
I18n.applyPreferred = function (opts)
482
{
483
opts = opts || {};
484
var chosen = this.normalize(opts.locale);
485
var auth = this.normalize(opts.authLocale);
486
var explicit = !!(opts.explicit && chosen) || this.hasExplicitChoice();
487
if (explicit)
488
{
489
var id = chosen || this.readStored();
490
if (this.known(id))
491
{
492
this.setLocale(id, { sync: false, persist: true, explicit: true });
493
if (opts.syncExplicit && typeof Online !== 'undefined' && Online.me && Online.setLocale
494
&& Online.locale !== id)
495
{ Online.setLocale(id); }
496
}
497
return id;
498
}
499
if (auth)
500
{ return this.setLocale(auth, { persist: false, sync: false, explicit: false }); }
501
return this.locale;
429
502
};
430
503
431
504
if (typeof module !== 'undefined' && module.exports)
@@ -21,6 +21,7 @@ var I18n = {21
],21
],22
DEFAULT: 'en',22
DEFAULT: 'en',23
STORAGE_KEY: 'meteors-locale',23
STORAGE_KEY: 'meteors-locale',24
EXPLICIT_KEY: 'meteors-locale-chosen',24
COOKIE: 'meteors-locale',25
COOKIE: 'meteors-locale',25
locale: 'en',26
locale: 'en',26
_catalog: null,27
_catalog: null,@@ -57,6 +58,48 @@ I18n.known = function (id)57
return false;58
return false;58
};59
};59
60
61
/**62
* Map a BCP 47 auth claim (zh-Hans) or a stored id to a Meteors locale.63
* Unknown values return null.64
*/65
I18n.normalize = function (id)66
{67
if (id == null || id === '')68
{ return null; }69
var s = String(id).trim().toLowerCase().replace(/_/g, '-');70
if (s === 'zh-hans' || s === 'zh-cn' || s === 'zh-sg' || s === 'zh-my')71
{ return 'zh'; }72
if (this.known(s))73
{ return s; }74
var primary = s.split('-')[0];75
return this.known(primary) ? primary : null;76
};77
78
I18n.hasExplicitChoice = function ()79
{80
try81
{82
if (typeof localStorage !== 'undefined')83
{ return localStorage.getItem(this.EXPLICIT_KEY) === '1'; }84
}85
catch (e) { /* private mode */ }86
return false;87
};88
89
I18n.markExplicit = function (on)90
{91
try92
{93
if (typeof localStorage === 'undefined')94
{ return; }95
if (on === false)96
{ localStorage.removeItem(this.EXPLICIT_KEY); }97
else98
{ localStorage.setItem(this.EXPLICIT_KEY, '1'); }99
}100
catch (e) { /* ignore */ }101
};102
60
I18n.info = function (id)103
I18n.info = function (id)61
{104
{62
id = id || this.locale;105
id = id || this.locale;@@ -235,12 +278,15 @@ I18n._writeStored = function (id)235
I18n.setLocale = function (id, opts)278
I18n.setLocale = function (id, opts)236
{279
{237
opts = opts || {};280
opts = opts || {};238
if (!this.known(id))281
id = this.normalize(id);282
if (!id)239
{ id = this.DEFAULT; }283
{ id = this.DEFAULT; }240
var changed = id !== this.locale;284
var changed = id !== this.locale;241
this.locale = id;285
this.locale = id;242
if (opts.persist !== false)286
if (opts.persist !== false)243
{ this._writeStored(id); }287
{ this._writeStored(id); }288
if (opts.explicit !== false && opts.persist !== false)289
{ this.markExplicit(); }244
if (typeof document !== 'undefined' && document.documentElement)290
if (typeof document !== 'undefined' && document.documentElement)245
{291
{246
document.documentElement.lang = this.info(id).htmlLang;292
document.documentElement.lang = this.info(id).htmlLang;@@ -424,8 +470,35 @@ I18n.init = function ()424
470
425
I18n.applyFromProfile = function (locale)471
I18n.applyFromProfile = function (locale)426
{472
{427
if (this.known(locale))473
this.applyPreferred({ locale: locale, explicit: true });428
{ this.setLocale(locale, { sync: false, persist: true }); }474
};475
476
/**477
* t1250: an explicit in-game choice always wins. Otherwise a logged-in478
* player follows the auth OIDC locale (mapped, e.g. zh-Hans → zh).479
* Guests are left to init()/localStorage.480
*/481
I18n.applyPreferred = function (opts)482
{483
opts = opts || {};484
var chosen = this.normalize(opts.locale);485
var auth = this.normalize(opts.authLocale);486
var explicit = !!(opts.explicit && chosen) || this.hasExplicitChoice();487
if (explicit)488
{489
var id = chosen || this.readStored();490
if (this.known(id))491
{492
this.setLocale(id, { sync: false, persist: true, explicit: true });493
if (opts.syncExplicit && typeof Online !== 'undefined' && Online.me && Online.setLocale494
&& Online.locale !== id)495
{ Online.setLocale(id); }496
}497
return id;498
}499
if (auth)500
{ return this.setLocale(auth, { persist: false, sync: false, explicit: false }); }501
return this.locale;429
};502
};430
503
431
if (typeof module !== 'undefined' && module.exports)504
if (typeof module !== 'undefined' && module.exports)@@ -2854,10 +2854,14 @@ function applyProfileLocale ()
2854
2854
{
2855
2855
if (typeof I18n === 'undefined' || typeof Online === 'undefined')
2856
2856
{ return; }
2857
if (Online.locale)
2858
{ I18n.applyFromProfile(Online.locale); }
2859
else if (Online.me)
2860
{ Online.setLocale(I18n.locale); }
2857
if (!Online.me)
2858
{ return; }
2859
I18n.applyPreferred({
2860
explicit: !!(Online.localeExplicit && Online.locale),
2861
locale: Online.locale,
2862
authLocale: Online.authLocale,
2863
syncExplicit: true
2864
});
2861
2865
}
2862
2866
2863
2867
/* ---------- t1247 leaderboard -------------------------------------- */
@@ -2854,10 +2854,14 @@ function applyProfileLocale ()2854
{2854
{2855
if (typeof I18n === 'undefined' || typeof Online === 'undefined')2855
if (typeof I18n === 'undefined' || typeof Online === 'undefined')2856
{ return; }2856
{ return; }2857
if (Online.locale)2857
if (!Online.me)2858
{ I18n.applyFromProfile(Online.locale); }2858
{ return; }2859
else if (Online.me)2859
I18n.applyPreferred({2860
{ Online.setLocale(I18n.locale); }2860
explicit: !!(Online.localeExplicit && Online.locale),2861
locale: Online.locale,2862
authLocale: Online.authLocale,2863
syncExplicit: true2864
});2861
}2865
}2862
2866
2863
/* ---------- t1247 leaderboard -------------------------------------- */2867
/* ---------- t1247 leaderboard -------------------------------------- */@@ -16,6 +16,8 @@ var Online = {
16
16
me: null,
17
17
lifetimePoints: 0,
18
18
locale: null,
19
localeExplicit: false,
20
authLocale: null,
19
21
blocks: [],
20
22
planets: [],
21
23
lobby: null,
@@ -77,6 +79,10 @@ Online._apply = function (data)
77
79
{ this.lifetimePoints = data.lifetime_points; }
78
80
if (data.locale !== undefined)
79
81
{ this.locale = data.locale; }
82
if (data.locale_explicit !== undefined)
83
{ this.localeExplicit = !!data.locale_explicit; }
84
if (data.auth_locale !== undefined)
85
{ this.authLocale = data.auth_locale; }
80
86
if (data.last_planet !== undefined)
81
87
{ this.lastPlanet = data.last_planet; }
82
88
if (data.blocks)
@@ -16,6 +16,8 @@ var Online = {16
me: null,16
me: null,17
lifetimePoints: 0,17
lifetimePoints: 0,18
locale: null,18
locale: null,19
localeExplicit: false,20
authLocale: null,19
blocks: [],21
blocks: [],20
planets: [],22
planets: [],21
lobby: null,23
lobby: null,@@ -77,6 +79,10 @@ Online._apply = function (data)77
{ this.lifetimePoints = data.lifetime_points; }79
{ this.lifetimePoints = data.lifetime_points; }78
if (data.locale !== undefined)80
if (data.locale !== undefined)79
{ this.locale = data.locale; }81
{ this.locale = data.locale; }82
if (data.locale_explicit !== undefined)83
{ this.localeExplicit = !!data.locale_explicit; }84
if (data.auth_locale !== undefined)85
{ this.authLocale = data.auth_locale; }80
if (data.last_planet !== undefined)86
if (data.last_planet !== undefined)81
{ this.lastPlanet = data.last_planet; }87
{ this.lastPlanet = data.last_planet; }82
if (data.blocks)88
if (data.blocks)@@ -188,3 +188,55 @@ describe('i18n fallback (t1256)', () =>
188
188
assert.equal(play.textContent, 'Play');
189
189
});
190
190
});
191
192
describe('auth locale default (t1250)', () =>
193
{
194
it('maps BCP 47 claims, including zh-Hans, to Meteors ids', () =>
195
{
196
assert.equal(I18n.normalize('zh-Hans'), 'zh');
197
assert.equal(I18n.normalize('zh-hans'), 'zh');
198
assert.equal(I18n.normalize('nl'), 'nl');
199
assert.equal(I18n.normalize('en-US'), 'en');
200
assert.equal(I18n.normalize('xx'), null);
201
assert.equal(I18n.normalize(''), null);
202
});
203
204
it('lets an explicit in-game choice win over the auth locale', () =>
205
{
206
const mem = {};
207
global.localStorage = {
208
getItem: (k) => (k in mem ? mem[k] : null),
209
setItem: (k, v) => { mem[k] = String(v); },
210
removeItem: (k) => { delete mem[k]; }
211
};
212
I18n._catalog = catalog;
213
I18n.markExplicit(false);
214
I18n.locale = 'en';
215
I18n.applyPreferred({ authLocale: 'nl', explicit: false });
216
assert.equal(I18n.locale, 'nl');
217
assert.equal(I18n.hasExplicitChoice(), false);
218
assert.equal(mem[I18n.STORAGE_KEY], undefined);
219
220
I18n.setLocale('de');
221
assert.equal(I18n.hasExplicitChoice(), true);
222
I18n.applyPreferred({ authLocale: 'fr', locale: 'de', explicit: true });
223
assert.equal(I18n.locale, 'de');
224
delete global.localStorage;
225
});
226
227
it('leaves a guest on the stored locale', () =>
228
{
229
const mem = { 'meteors-locale': 'es' };
230
global.localStorage = {
231
getItem: (k) => (k in mem ? mem[k] : null),
232
setItem: (k, v) => { mem[k] = String(v); },
233
removeItem: (k) => { delete mem[k]; }
234
};
235
I18n._catalog = catalog;
236
I18n.markExplicit(false);
237
I18n.locale = I18n.readStored();
238
assert.equal(I18n.locale, 'es');
239
// applyPreferred is only called when logged in; a guest keeps this.
240
delete global.localStorage;
241
});
242
});
@@ -188,3 +188,55 @@ describe('i18n fallback (t1256)', () =>188
assert.equal(play.textContent, 'Play');188
assert.equal(play.textContent, 'Play');189
});189
});190
});190
});191
192
describe('auth locale default (t1250)', () =>193
{194
it('maps BCP 47 claims, including zh-Hans, to Meteors ids', () =>195
{196
assert.equal(I18n.normalize('zh-Hans'), 'zh');197
assert.equal(I18n.normalize('zh-hans'), 'zh');198
assert.equal(I18n.normalize('nl'), 'nl');199
assert.equal(I18n.normalize('en-US'), 'en');200
assert.equal(I18n.normalize('xx'), null);201
assert.equal(I18n.normalize(''), null);202
});203
204
it('lets an explicit in-game choice win over the auth locale', () =>205
{206
const mem = {};207
global.localStorage = {208
getItem: (k) => (k in mem ? mem[k] : null),209
setItem: (k, v) => { mem[k] = String(v); },210
removeItem: (k) => { delete mem[k]; }211
};212
I18n._catalog = catalog;213
I18n.markExplicit(false);214
I18n.locale = 'en';215
I18n.applyPreferred({ authLocale: 'nl', explicit: false });216
assert.equal(I18n.locale, 'nl');217
assert.equal(I18n.hasExplicitChoice(), false);218
assert.equal(mem[I18n.STORAGE_KEY], undefined);219
220
I18n.setLocale('de');221
assert.equal(I18n.hasExplicitChoice(), true);222
I18n.applyPreferred({ authLocale: 'fr', locale: 'de', explicit: true });223
assert.equal(I18n.locale, 'de');224
delete global.localStorage;225
});226
227
it('leaves a guest on the stored locale', () =>228
{229
const mem = { 'meteors-locale': 'es' };230
global.localStorage = {231
getItem: (k) => (k in mem ? mem[k] : null),232
setItem: (k, v) => { mem[k] = String(v); },233
removeItem: (k) => { delete mem[k]; }234
};235
I18n._catalog = catalog;236
I18n.markExplicit(false);237
I18n.locale = I18n.readStored();238
assert.equal(I18n.locale, 'es');239
// applyPreferred is only called when logged in; a guest keeps this.240
delete global.localStorage;241
});242
});@@ -95,3 +95,13 @@ describe('leaderboard button (t1256)', () =>
95
95
assert.match(bind, /pointerType === 'touch'/);
96
96
});
97
97
});
98
99
describe('leaderboard public profiles (t1253)', () =>
100
{
101
it('resolves names via the public auth profiles API', () =>
102
{
103
assert.match(boot, /\/api\/profiles/);
104
assert.match(boot, /fetchAuthProfiles\(/);
105
assert.match(api, /leaderboardKnownIdentities\(/);
106
});
107
});
@@ -95,3 +95,13 @@ describe('leaderboard button (t1256)', () =>95
assert.match(bind, /pointerType === 'touch'/);95
assert.match(bind, /pointerType === 'touch'/);96
});96
});97
});97
});98
99
describe('leaderboard public profiles (t1253)', () =>100
{101
it('resolves names via the public auth profiles API', () =>102
{103
assert.match(boot, /\/api\/profiles/);104
assert.match(boot, /fetchAuthProfiles\(/);105
assert.match(api, /leaderboardKnownIdentities\(/);106
});107
});