GG.deals clone: CodeIgniter 4 + MongoDB game price tracker

- Full gg.deals-style UI: deal feed with filters, game pages with price
  history charts, rankings, vouchers, news, prepaids, subscriptions,
  bundles, franchises, wishlist, API docs
- Real data crawlers:
  * gg:crawl (Steam Store API + GOG Catalog + Epic free games)
  * gg:catalog (252K game slugs from gg.deals sitemaps)
  * gg:ggdeals (per-game prices via FlareSolverr session, JSON-LD parsing)
  * gg:seed / gg:crawl-covers (demo seed + Steam CDN cover art)
- 24/7 self-updating scheduler (scripts/scheduler_loop.php, lockfile-protected)
- Tailwind v4 dark/light theme, Alpine.js, Chart.js
This commit is contained in:
deepseek
2026-08-23 07:06:02 +00:00
commit fff7a4b9b9
146 changed files with 15691 additions and 0 deletions
+138
View File
@@ -0,0 +1,138 @@
#-------------------------
# Operating Specific Junk Files
#-------------------------
# OS X
.DS_Store
.AppleDouble
.LSOverride
# OS X Thumbnails
._*
# Windows image file caches
Thumbs.db
ehthumbs.db
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# Linux
*~
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
#-------------------------
# Environment Files
#-------------------------
# These should never be under version control,
# as it poses a security risk.
.env
.vagrant
Vagrantfile
#-------------------------
# Temporary Files
#-------------------------
/writable/cache/*
!/writable/cache/index.html
/writable/logs/*
!/writable/logs/index.html
/writable/session/*
!/writable/session/index.html
/writable/uploads/*
!/writable/uploads/index.html
/writable/debugbar/*
!/writable/debugbar/index.html
php_errors.log
#-------------------------
# User Guide Temp Files
#-------------------------
/user_guide_src/build/*
/user_guide_src/cilexer/build/*
/user_guide_src/cilexer/dist/*
/user_guide_src/cilexer/pycilexer.egg-info/*
#-------------------------
# Test Files
#-------------------------
/tests/coverage*
# Don't save phpunit under version control.
/phpunit
#-------------------------
# Composer
#-------------------------
vendor/
#-------------------------
# IDE / Development Files
#-------------------------
# Modules Testing
_modules/*
# phpenv local config
.php-version
# Jetbrains editors (PHPStorm, etc)
.idea/
*.iml
# NetBeans
/nbproject/
/build/
/nbbuild/
/dist/
/nbdist/
/nbactions.xml
/nb-configuration.xml
/.nb-gradle/
# Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
*.sublime-workspace
*.sublime-project
.phpintel
/api/
# Visual Studio Code
.vscode/
/results/
/phpunit.xml
# ---- Node / frontend build ----
node_modules/
package-lock.json
public/js/chart.umd.js
public/js/alpine.min.js
public/css/app.css
assets/node_modules/
# ---- Crawled assets (regenerable) ----
public/img/covers/
public/img/stores/
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2019 British Columbia Institute of Technology
Copyright (c) 2019-present CodeIgniter Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+107
View File
@@ -0,0 +1,107 @@
# GG.deals Clone
A demo clone of [gg.deals](https://gg.deals/) — PC game price comparison — built with:
- **CodeIgniter 4** (PHP 8.2) — MVC backend
- **MongoDB** — data store (`harness-mongo`, db: `ggdeals`)
- **Tailwind CSS v4** — styling (dark + light theme)
- **Alpine.js** — interactivity (tabs, filters, wishlist store, settings store, search dropdown)
- **Chart.js** — price history charts
The feature set was modeled after a **deep crawl of gg.deals itself**: the full sitemap tree (12 sitemap types, 5k+ URLs) plus Wayback Machine snapshots of every page type (homepage, deals, game, bundle, freebie, giveaway, franchise, game-points, API, rankings, vouchers, news).
## Features
### Homepage dashboard (gg.deals-style, 10 sections)
- Most Popular Games, New deals, Best deals, Historical lows, Ending Soon
- 🔥 Most Wanted, 🆕 New releases, 📅 Upcoming games
- 📰 News feed, 🎁 Prepaids
- Stats strip (games / deals / stores / all-time lows now)
### Deal feed & presets (`/deals/{preset}`)
- Preset tabs: Hot New Deals, New Deals, Historical Lows, Ending Soon, ≥75% off, ≥85% off
- Advanced filters: price tiers (Under $2$30), discount tiers (≥5090%), deal rating (🔥 Hot/Good/Fair), release year ranges, only all-time lows, only-from-wishlist, per-store checkboxes with real logos
- Sorts: Best deals, Deal rating, Biggest discount, Cheapest ever, New releases, Lowest price, Metascore, Title AZ, Oldest release, Ending soon
- Deal rows with 🔥 Hot / Good / Fair badges, ★ New HL flags, ⏳ ending-soon timers, wishlist hearts
### Game page (`/game/{slug}`)
- **Header price tabs**: Current Prices / Historical Low
- Price summary cards: Official Stores, Keyshops, Subscriptions, All-time low
- Deals tables (official stores & keyshops) with DRM, region locks, expiry, HL flags
- Chart.js price history (3M/6M/1Y/All) vs all-time low
- **Bundles with this game**, **Series & franchises**, **Similar games** sections
- About (dev/publisher/age rating), System Requirements, How Long to Beat
### Content & community pages
- **Bundle pages** (`/bundle/{slug}`) — games list, price, savings, store
- **News articles** (`/article|deal|freebie|giveaway/{slug}`) — categorized posts with claim/enter CTAs
- **Franchise pages** (`/franchise/{slug}`) — all games in a series
- **Rankings** — Most Wishlisted, Most Collected, Metacritic, Steam Reviews
- **Vouchers** — promo codes per store with copy-to-clipboard
- **Subscriptions** — Game Pass, PS Plus, EA Play, Ubisoft+ cards
- **Prepaids** — gift card groups with denominations
- **Games browser** (`/games/{genre}`) — same deal-feed layout (filter sidebar + row list + pagination) with genre chips on top, **Stores**, **Wishlist** (localStorage)
### Site features
- **Region & currency selector** (19 regions, 7 currencies, localStorage-persisted)
- **Keyshops toggle** (on/off)
- **Dark / Light theme toggle**
- **API page** + **Game Prices API** (`/api/prices?appid=`) with live demo tester
- **FAQ** (accordion) + **CD key activation tutorials** (Steam/GOG/Epic/Origin/Uplay/Keyshops)
- Live search suggestions
### Assets
- **Real cover art** — crawled from Steam CDN (`php spark gg:crawl-covers`)
- **Real store logos** — brand favicons in `public/img/stores/`
## Quick start
```bash
# 1. Configure .env (MONGO_URI / MONGO_DB)
cp env .env
# 2. Install PHP + frontend deps
composer install
npm install
# 3. Build CSS
npx @tailwindcss/cli -i assets/css/app.css -o public/css/app.css --minify
# 4. Seed the database (stores, 61 games, 549 deals, ~26k price points, vouchers, news, prepaids, subscriptions, bundles, franchises, covers)
php spark gg:seed
# 5. Crawl real cover art from Steam
php spark gg:crawl-covers
# 6. Serve
php spark serve --host 0.0.0.0 --port 8085
```
## Data model (MongoDB collections)
- `stores` — code, name, kind, colors, logo
- `games` — slug, title, base price, genres, platforms, scores, all-time low, best prices, developer/publisher, sys reqs, HLTB, age rating, description
- `deals` — per-store offers with cut %, HL flag, DRM, expiry
- `price_history` — 5-day cadence price points per store
- `vouchers` — promo codes per store
- `news` — categorized posts (deals/bundles/freebies/giveaways/subscriptions)
- `prepaids` — gift card groups
- `subscriptions` — game subscription services
- `bundles` — bundles with included game slugs
- `franchises` — franchise series
## Layout
```
app/
Commands/ SeedDatabase (gg:seed), CrawlCovers (gg:crawl-covers)
Controllers/ Home, Game, Games, Rankings, Vouchers, News, Prepaids,
Subscriptions, Bundle, Franchise, Wishlist, Stores, Pages, Api
Helpers/gg_helper.php money(), cut_class(), deal_rating(), qs_url(), time_ago()
Libraries/Mongo.php MongoDB client wrapper
Models/GameModel.php aggregation pipelines for feed/chart/dashboard/similar
Views/ layout, homepage, home, game, + 15 more page views, partials/
assets/css/app.css Tailwind v4 source (theme tokens + dark/light)
```
> Demo data only: prices are randomly generated, buy links point to search results.
+6
View File
@@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
+126
View File
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace App\Commands;
use App\Libraries\Mongo;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use MongoDB\BSON\UTCDateTime;
/**
* Crawls the full gg.deals game catalog from the public sitemap files.
*
* The sitemap XML files are NOT Cloudflare-protected, so they can be fetched
* directly. There are 526+ sitemap_games_N.xml files, each with ~990 game URLs.
*
* php spark gg:catalog → crawl all sitemap files into the catalog collection
* php spark gg:catalog --limit=5 → only first N files (for testing)
*/
class CrawlCatalog extends BaseCommand
{
protected $group = 'GGDeals';
protected $name = 'gg:catalog';
protected $description = 'Crawls the full gg.deals game catalog from public sitemaps.';
protected $usage = 'gg:catalog [--limit=N]';
private const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36';
public function run(array $params): void
{
CLI::write('GG.deals catalog crawler started — ' . date('Y-m-d H:i:s'), 'green');
$limit = null;
foreach ($params as $k => $v) {
if (is_string($k) && str_starts_with($k, 'limit=')) {
$limit = (int) substr($k, 6);
}
}
// resolve the sitemap index
$index = $this->fetch('https://gg.deals/sitemap.xml');
if ($index === null) {
CLI::error('Could not fetch sitemap index');
return;
}
preg_match_all('/sitemap_games_(\d+)\.xml/', $index, $m);
$files = array_map(static fn ($n) => (int) $n, $m[1]);
sort($files, SORT_NUMERIC);
CLI::write('Found ' . count($files) . ' game sitemap files.', 'yellow');
if ($limit !== null) {
$files = array_slice($files, 0, $limit);
CLI::write('Limit set: first ' . count($files) . ' files.', 'yellow');
}
$totalUrls = 0;
$totalInserted = 0;
$totalSkipped = 0;
foreach ($files as $i => $n) {
$url = "https://gg.deals/sitemap_games_{$n}.xml";
$xml = $this->fetch($url);
if ($xml === null) {
CLI::error(" sitemap {$n}: fetch failed");
usleep(500000);
continue;
}
preg_match_all('/<loc>(https:\/\/gg\.deals\/game\/([a-z0-9-]+)\/?)<\/loc>/', $xml, $matches);
$slugs = array_values(array_unique($matches[2]));
$totalUrls += count($slugs);
$docs = [];
foreach ($slugs as $slug) {
$docs[] = [
'slug' => $slug,
'url' => 'https://gg.deals/game/' . $slug . '/',
'crawled' => false,
'added_at' => new UTCDateTime(time() * 1000),
];
}
if ($docs !== []) {
try {
Mongo::collection('catalog')->insertMany($docs, ['ordered' => false]);
$totalInserted += count($docs);
} catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
// duplicate keys are expected on re-runs
$totalInserted += count($docs);
}
}
CLI::write(" [{$i}/" . count($files) . "] sitemap {$n}: " . count($slugs) . ' slugs (total ' . number_format($totalInserted) . ')');
usleep(300000);
}
CLI::write('');
CLI::write("Catalog crawl done: {$totalUrls} urls, {$totalInserted} inserted.", 'green');
CLI::write('Total catalog documents: ' . Mongo::collection('catalog')->countDocuments(), 'green');
}
private function fetch(string $url): ?string
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => self::UA,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HTTPHEADER => ['Accept: application/xml,text/xml,*/*'],
]);
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($code !== 200 || $body === false || $body === '') {
return null;
}
return $body;
}
}
+184
View File
@@ -0,0 +1,184 @@
<?php
declare(strict_types=1);
namespace App\Commands;
use App\Libraries\Mongo;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
/**
* Crawls real cover art from the Steam CDN and updates the games collection.
*
* Usage: php spark gg:crawl-covers
*
* Cover sources (in order of preference):
* 1. Steam store header (460x215) — https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/header.jpg
* 2. Steam capsule (616x353) — https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/capsule_616x353.jpg
* 3. Existing SVG placeholder (kept)
*/
class CrawlCovers extends BaseCommand
{
protected $group = 'GGDeals';
protected $name = 'gg:crawl-covers';
protected $description = 'Crawls real cover art from the Steam CDN and updates games.';
protected $usage = 'gg:crawl-covers';
/** slug => steam appid */
public const APP_IDS = [
'age-of-empires-iv' => 1466860,
'alan-wake-2' => 2379780,
'balan-wonderworld' => 1336480,
'baldurs-gate-3' => 1086940,
'cities-skylines-ii' => 949230,
'control' => 870780,
'counter-strike-2' => 730,
'cuphead' => 268910,
'cyberpunk-2077' => 1091500,
'dark-souls-iii' => 374320,
'dead-cells' => 588650,
'death-stranding' => 1190460,
'deep-rock-galactic' => 548430,
'diablo-iv' => 2344520,
'disco-elysium' => 632470,
'dishonored-2' => 403640,
'divinity-original-sin-2' => 435150,
'doom-eternal' => 782330,
'ea-sports-fc-24' => 2195250,
'efootball-2024' => 2349380,
'elden-ring' => 1245620,
'enshrouded' => 1203620,
'factorio' => 427520,
'forza-horizon-5' => 1551360,
'god-of-war' => 1593500,
'grand-theft-auto-v' => 271590,
'hades-ii' => 1145350,
'helldivers-2' => 553850,
'hogwarts-legacy' => 990080,
'hollow-knight' => 367520,
'horizon-forbidden-west' => 2420110,
'it-takes-two' => 1426210,
'kingdom-come-deliverance' => 379430,
'lethal-company' => 1966720,
'manor-lords' => 1363080,
'marvels-spider-man-2' => 2651290,
'marvels-spider-man-remastered' => 1817070,
'metro-exodus' => 412020,
'microsoft-flight-simulator' => 1250410,
'monster-hunter-rise' => 1446780,
'nier-automata' => 524220,
'ori-and-the-will-of-the-wisps' => 1057090,
'outer-wilds' => 753640,
'palworld' => 1623730,
'persona-5-royal' => 1687950,
'ready-or-not' => 1144200,
'red-dead-redemption-2' => 1174180,
'resident-evil-4' => 2050650,
'rimworld' => 294100,
'sekiro-shadows-die-twice' => 814380,
'slay-the-spire' => 646570,
'sonic-frontiers' => 1237320,
'stardew-valley' => 413150,
'starfield' => 1716740,
'street-fighter-6' => 1364780,
'terraria' => 105600,
'the-last-of-us-part-i' => 1888930,
'the-witcher-3-wild-hunt' => 292030,
'total-war-warhammer-iii' => 1142710,
'valheim' => 892970,
'warhammer-40000-darktide' => 1361210,
];
private const CDN = 'https://cdn.cloudflare.steamstatic.com/steam/apps/%d/';
private const OUT_DIR = WRITEPATH . '../public/img/covers/';
private const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36';
public function run(array $params): void
{
$games = Mongo::collection('games')->find()->toArray();
if (! is_dir(self::OUT_DIR)) {
mkdir(self::OUT_DIR, 0777, true);
}
$ok = 0;
$fail = [];
$skipped = 0;
foreach ($games as $game) {
$slug = $game['slug'];
$appid = self::APP_IDS[$slug] ?? null;
if ($appid === null) {
$skipped++;
continue;
}
$filename = $slug . '.jpg';
$dest = self::OUT_DIR . $filename;
$downloaded = $this->download(
sprintf(self::CDN, $appid) . 'header.jpg',
$dest
);
if (! $downloaded) {
// try the capsule variant as a fallback
$downloaded = $this->download(
sprintf(self::CDN, $appid) . 'capsule_616x353.jpg',
$dest
);
}
if ($downloaded) {
Mongo::collection('games')->updateOne(
['slug' => $slug],
['$set' => ['cover' => ['file' => '/img/covers/' . $filename, 'from' => '#000000', 'to' => '#000000']]]
);
$ok++;
CLI::write(' ✓ ' . $slug . ' (' . $appid . ')', 'green');
} else {
$fail[] = $slug;
CLI::write(' ✗ ' . $slug . ' (' . $appid . ')', 'red');
}
usleep(120000); // be gentle with the CDN
}
CLI::write('');
CLI::write(sprintf('Downloaded %d covers, skipped %d (no appid), failed %d.', $ok, $skipped, count($fail)), 'cyan');
if ($fail !== []) {
CLI::write('Failed: ' . implode(', ', $fail), 'yellow');
}
}
private function download(string $url, string $dest): bool
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 20,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => self::UA,
CURLOPT_SSL_VERIFYPEER => true,
]);
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
if ($code !== 200 || $body === false || strlen($body) < 1000) {
return false;
}
// ensure it's an image
if (! str_starts_with($type, 'image/')) {
return false;
}
return file_put_contents($dest, $body) !== false;
}
}
+661
View File
@@ -0,0 +1,661 @@
<?php
declare(strict_types=1);
namespace App\Commands;
use App\Libraries\Mongo;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use MongoDB\BSON\UTCDateTime;
/**
* Crawls real game data & deals from public sources.
*
* php spark gg:crawl → all sources (steam, gog, epic)
* php spark gg:crawl steam → Steam only
* php spark gg:crawl gog → GOG only
* php spark gg:crawl epic → Epic free games only
*
* Sources:
* - Steam Store API (featured categories + app details, cc=us)
* - GOG Catalog API (top rated products + prices)
* - Epic Store free games promotions API
*/
class CrawlGames extends BaseCommand
{
protected $group = 'GGDeals';
protected $name = 'gg:crawl';
protected $description = 'Crawls real game & deal data from Steam, GOG and Epic.';
protected $usage = 'gg:crawl [steam|gog|epic]';
private const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36';
private const STEAM_FEATURED = 'https://store.steampowered.com/api/featuredcategories/?cc=us&l=en';
private const STEAM_APP_DETAILS = 'https://store.steampowered.com/api/appdetails/?cc=us&l=en&appids=%d&filters=basic,price_overview,genres,release_date,metacritic,developers,publishers,categories';
private const STEAM_SEARCH = 'https://store.steampowered.com/search/results/?query&start=%d&count=100&dynamic_data=&sort_by=_ASC&cc=us&l=en&category1=998&infinite=1';
private const GOG_CATALOG = 'https://catalog.gog.com/v1/catalog?limit=%d&order=desc:totalRating&productType=in:game&query=like:*';
private const EPIC_FREE = 'https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US';
public function run(array $params): void
{
$target = strtolower($params[0] ?? 'all');
CLI::write('GG.deals crawler started — ' . date('Y-m-d H:i:s'), 'green');
if ($target === 'all' || $target === 'steam') {
$this->crawlSteam();
}
if ($target === 'all' || $target === 'gog') {
$this->crawlGog();
}
if ($target === 'all' || $target === 'epic') {
$this->crawlEpic();
}
if ($target === 'all' || $target === 'finalize' || in_array($target, ['steam', 'gog', 'epic'], true)) {
$this->finalizeGames();
$this->recordPriceHistory();
}
CLI::write('Crawler finished — ' . date('Y-m-d H:i:s'), 'green');
}
/**
* Records today's cheapest price per game/store-kind into price_history,
* so the charts grow real data over time.
*/
private function recordPriceHistory(): void
{
CLI::write('-- Recording price history --', 'cyan');
$todayStart = (new \DateTime('today'))->getTimestamp();
$now = time();
$inserted = 0;
$deals = Mongo::collection('deals')->find()->toArray();
$byGame = [];
foreach ($deals as $d) {
$byGame[$d['game_slug']][$d['kind']][] = (float) $d['price'];
}
foreach ($byGame as $slug => $kinds) {
foreach (['official', 'keyshop'] as $kind) {
if (empty($kinds[$kind])) {
continue;
}
$min = min($kinds[$kind]);
// only insert one point per game+kind+day
$existing = Mongo::collection('price_history')->findOne([
'game_slug' => $slug,
'kind' => $kind,
'ts' => ['$gte' => new UTCDateTime($todayStart * 1000)],
]);
if ($existing !== null) {
continue;
}
Mongo::collection('price_history')->insertOne([
'game_slug' => $slug,
'store_code' => 'aggregate',
'kind' => $kind,
'ts' => new UTCDateTime($now * 1000),
'price' => round($min, 2),
]);
$inserted++;
}
}
CLI::write("Recorded {$inserted} price history points.", 'green');
}
/**
* Recomputes per-game aggregate fields (best prices, active deal counts,
* all-time low) from the deals collection — keeps views working even when
* a game has no official/keyshop store deals.
*/
private function finalizeGames(): void
{
CLI::write('-- Finalizing game aggregates --', 'cyan');
$deals = Mongo::collection('deals')->find()->toArray();
$byGame = [];
foreach ($deals as $d) {
$slug = $d['game_slug'];
$byGame[$slug][] = $d;
}
$updated = 0;
$now = time();
foreach ($byGame as $slug => $gameDeals) {
$official = array_values(array_filter($gameDeals, static fn ($d) => $d['kind'] === 'official'));
$keyshop = array_values(array_filter($gameDeals, static fn ($d) => $d['kind'] === 'keyshop'));
usort($official, static fn ($a, $b) => $a['price'] <=> $b['price']);
usort($keyshop, static fn ($a, $b) => $a['price'] <=> $b['price']);
usort($gameDeals, static fn ($a, $b) => $a['price'] <=> $b['price']);
$bestOfficial = $official[0] ?? null;
$bestKeyshop = $keyshop[0] ?? null;
$cheapest = $gameDeals[0] ?? null;
$existing = Mongo::collection('games')->findOne(['slug' => $slug]);
if ($existing === null) {
continue;
}
// all-time low: keep the historical minimum, seed from current cheapest if none
$hl = $existing['all_time_low'] ?? null;
if ($cheapest !== null && ($hl === null || (float) $cheapest['price'] < (float) $hl['price'])) {
$hl = [
'price' => (float) $cheapest['price'],
'store' => $cheapest['store_code'],
'kind' => $cheapest['kind'],
'date' => new UTCDateTime($now * 1000),
];
}
$set = [
'best_official' => [
'price' => $bestOfficial ? (float) $bestOfficial['price'] : 0.0,
'store' => $bestOfficial ? $bestOfficial['store_code'] : '',
'cut' => $bestOfficial ? (int) $bestOfficial['cut'] : 0,
],
'best_keyshop' => [
'price' => $bestKeyshop ? (float) $bestKeyshop['price'] : 0.0,
'store' => $bestKeyshop ? $bestKeyshop['store_code'] : '',
'cut' => $bestKeyshop ? (int) $bestKeyshop['cut'] : 0,
],
'active_deals' => count($gameDeals),
'all_time_low' => $hl,
'trending' => $existing['trending'] ?? mt_rand(30, 90),
];
Mongo::collection('games')->updateOne(['slug' => $slug], ['$set' => $set]);
$updated++;
}
CLI::write("Finalized {$updated} games with aggregates.", 'green');
}
// ------------------------------------------------------------------ Steam
private function crawlSteam(): void
{
CLI::write('-- Steam --', 'cyan');
$data = $this->fetchJson(self::STEAM_FEATURED);
if ($data === null) {
CLI::error('Steam featured fetch failed');
return;
}
$appIds = [];
$featured = [];
foreach (['specials', 'top_sellers', 'new_releases', 'coming_soon'] as $cat) {
foreach ($data[$cat]['items'] ?? [] as $item) {
$appIds[$item['id']] = true;
$featured[$item['id']] = [
'category' => $cat,
'discount_percent' => (int) ($item['discount_percent'] ?? 0),
'final_price' => (int) ($item['final_price'] ?? 0),
'original_price' => (int) ($item['original_price'] ?? 0),
];
}
}
// also add our existing appids so we refresh their details
foreach (\App\Commands\CrawlCovers::APP_IDS as $slug => $appid) {
$appIds[$appid] = true;
}
// crawl Steam search catalog (games only) — several pages of 50
$searchPages = (int) env('GG_CRAWL_STEAM_PAGES', '4');
foreach ($this->steamSearchAppIds($searchPages) as $appid) {
$appIds[$appid] = true;
}
CLI::write('Found ' . count($appIds) . ' Steam apps to fetch details for.', 'yellow');
$gamesInserted = 0;
$gamesUpdated = 0;
$dealsInserted = 0;
$dealsUpdated = 0;
foreach (array_keys($appIds) as $i => $appid) {
$details = $this->fetchJson(sprintf(self::STEAM_APP_DETAILS, (int) $appid));
if ($details === null || empty($details[(string) $appid]['success'])) {
continue;
}
$g = $details[(string) $appid]['data'] ?? null;
if ($g === null || empty($g['name'])) {
continue;
}
$slug = url_title($g['name'], '-', true);
if ($slug === '') {
continue;
}
$priceOverview = $g['price_overview'] ?? [];
$priceUsd = isset($priceOverview['final']) ? (float) $priceOverview['final'] / 100 : null;
$baseUsd = isset($priceOverview['initial']) ? (float) $priceOverview['initial'] / 100 : null;
$cut = (int) ($priceOverview['discount_percent'] ?? 0);
$genres = array_map(static fn ($x) => $x['description'], $g['genres'] ?? []);
$platforms = ['steam'];
foreach ($g['platforms'] ?? [] as $plat => $supported) {
if ($supported) {
$platforms[] = $plat;
}
}
$now = time();
$cover = $this->steamCoverUrl((int) $appid);
$existing = Mongo::collection('games')->findOne(['slug' => $slug]);
$oldBase = $existing ? (float) $existing['base_price'] : ($baseUsd ?? 0);
$doc = [
'slug' => $slug,
'title' => $g['name'],
'steam_appid' => (int) $appid,
'base_price' => $baseUsd ?? $oldBase,
'genres' => array_values(array_unique(array_filter($genres))),
'platforms' => array_values(array_unique($platforms)),
'score' => (int) ($g['metacritic']['score'] ?? 0),
'rating_pct' => (int) ($g['metacritic']['score'] ?? 0),
'release_date' => $this->parseDate($g['release_date']['date'] ?? null),
'developer' => ($g['developers'][0] ?? null) ?: 'Unknown',
'publisher' => ($g['publishers'][0] ?? null) ?: 'Unknown',
'cover' => ['file' => $cover, 'from' => '#1b2838', 'to' => '#171d25'],
'description' => $g['short_description'] ?? '',
'age_rating' => 'Steam',
'last_crawled' => new UTCDateTime($now * 1000),
'source' => 'steam',
];
// preserve existing all_time_low / best prices if present
if ($existing) {
foreach (['all_time_low', 'best_official', 'best_keyshop', 'active_deals', 'trending'] as $f) {
if (isset($existing[$f])) {
$doc[$f] = $existing[$f];
}
}
}
$result = Mongo::collection('games')->updateOne(
['slug' => $slug],
['$set' => $doc],
['upsert' => true]
);
if ($result->getUpsertedCount() > 0) {
$gamesInserted++;
} else {
$gamesUpdated++;
}
// ---- deal (official store = Steam)
if ($priceUsd !== null && $baseUsd !== null && $baseUsd > 0) {
$hlPrice = $existing['all_time_low']['price'] ?? null;
$dealDoc = [
'game_slug' => $slug,
'title' => $g['name'],
'store_code' => 'steam',
'kind' => 'official',
'price' => round($priceUsd, 2),
'regular' => round($baseUsd, 2),
'cut' => max(0, min(95, $cut)),
'historical_low' => $hlPrice !== null && $priceUsd <= $hlPrice + 0.01,
'drm' => 'Steam key',
'regional' => false,
'expiry' => null,
'url' => 'https://store.steampowered.com/app/' . (int) $appid . '/',
'last_crawled' => new UTCDateTime($now * 1000),
'source' => 'steam',
];
$dResult = Mongo::collection('deals')->updateOne(
['game_slug' => $slug, 'store_code' => 'steam'],
['$set' => $dealDoc],
['upsert' => true]
);
if ($dResult->getUpsertedCount() > 0) {
$dealsInserted++;
} else {
$dealsUpdated++;
}
}
if ($i % 25 === 0) {
CLI::write(" ... {$i}/" . count($appIds));
}
usleep(200000); // rate limit ~5 req/s
}
CLI::write("Steam done: {$gamesInserted} games inserted, {$gamesUpdated} updated, {$dealsInserted} deals inserted, {$dealsUpdated} deals updated.", 'green');
}
private function steamCoverUrl(int $appid): string
{
return "https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/{$appid}/header.jpg";
}
/**
* Collects app IDs from the Steam store search pages (category1=998 → games).
*/
private function steamSearchAppIds(int $pages): array
{
$ids = [];
for ($page = 0; $page < $pages; $page++) {
$url = sprintf(self::STEAM_SEARCH, $page * 100);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => self::UA,
CURLOPT_SSL_VERIFYPEER => true,
]);
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($code !== 200 || $body === false) {
continue;
}
// results_html is JSON-escaped: data-ds-appid=\"123456\"
if (preg_match_all('/data-ds-appid=\\\\"(\d{3,9})\\\\"/', $body, $m)
|| preg_match_all('/data-ds-appid="(\d{3,9})"/', $body, $m)) {
foreach ($m[1] as $appid) {
$ids[(int) $appid] = true;
}
}
CLI::write(" search page {$page}: " . count($ids) . ' unique ids so far');
usleep(300000);
}
return array_keys($ids);
}
// ------------------------------------------------------------------ GOG
private function crawlGog(): void
{
CLI::write('-- GOG --', 'cyan');
$limit = 48;
$pages = (int) env('GG_CRAWL_GOG_PAGES', '6');
$inserted = 0;
$updated = 0;
$dealsInserted = 0;
$now = time();
for ($page = 0; $page < $pages; $page++) {
$url = sprintf(self::GOG_CATALOG, $limit) . '&page=' . $page . '&pageSize=' . $limit;
$data = $this->fetchJson($url);
if ($data === null || empty($data['products'])) {
CLI::write(" GOG page {$page}: no products, stopping.");
break;
}
CLI::write(" GOG page {$page}: " . count($data['products']) . ' products');
foreach ($data['products'] as $p) {
$title = $p['title'] ?? null;
if ($title === null) {
continue;
}
$slug = url_title($title, '-', true);
if ($slug === '') {
continue;
}
$price = $p['price'] ?? [];
$baseUsd = isset($price['baseMoney']['amount']) ? (float) $price['baseMoney']['amount'] : null;
$finalUsd = isset($price['finalMoney']['amount']) ? (float) $price['finalMoney']['amount'] : null;
$cut = (int) rtrim((string) ($price['discount'] ?? '0%'), '%');
$genres = array_map(static fn ($x) => $x['name'], $p['genres'] ?? []);
$existing = Mongo::collection('games')->findOne(['slug' => $slug]);
$doc = [
'slug' => $slug,
'title' => $title,
'base_price' => $baseUsd ?? 0,
'genres' => array_values(array_unique(array_filter($genres))),
'platforms' => ['gog'],
'score' => (int) ($p['reviewsRating'] ?? 0),
'rating_pct' => (int) ($p['reviewsRating'] ?? 0),
'release_date' => $this->parseDate($p['releaseDate'] ?? null, 'Y.m.d'),
'developer' => ($p['developers'][0] ?? null) ?: 'Unknown',
'publisher' => ($p['publishers'][0] ?? null) ?: 'Unknown',
'cover' => ['file' => $p['coverHorizontal'] ?? '', 'from' => '#862a52', 'to' => '#4b1530'],
'description' => $p['description'] ?? '',
'last_crawled' => new UTCDateTime($now * 1000),
'source' => 'gog',
];
if ($existing) {
foreach (['all_time_low', 'best_official', 'best_keyshop', 'active_deals', 'trending'] as $f) {
if (isset($existing[$f])) {
$doc[$f] = $existing[$f];
}
}
}
$r = Mongo::collection('games')->updateOne(['slug' => $slug], ['$set' => $doc], ['upsert' => true]);
if ($r->getUpsertedCount() > 0) {
$inserted++;
} else {
$updated++;
}
if ($finalUsd !== null && $baseUsd !== null && $baseUsd > 0) {
$hlPrice = $existing['all_time_low']['price'] ?? null;
Mongo::collection('deals')->updateOne(
['game_slug' => $slug, 'store_code' => 'gog'],
['$set' => [
'game_slug' => $slug,
'title' => $title,
'store_code' => 'gog',
'kind' => 'official',
'price' => round($finalUsd, 2),
'regular' => round($baseUsd, 2),
'cut' => max(0, min(95, $cut)),
'historical_low' => $hlPrice !== null && $finalUsd <= $hlPrice + 0.01,
'drm' => 'DRM-free',
'regional' => false,
'expiry' => null,
'url' => $p['storeLink'] ?? 'https://www.gog.com/',
'last_crawled' => new UTCDateTime($now * 1000),
'source' => 'gog',
]],
['upsert' => true]
);
$dealsInserted++;
}
usleep(100000);
}
}
CLI::write("GOG done: {$inserted} inserted, {$updated} updated, {$dealsInserted} deals.", 'green');
}
// ------------------------------------------------------------------ Epic
private function crawlEpic(): void
{
CLI::write('-- Epic free games --', 'cyan');
$data = $this->fetchJson(self::EPIC_FREE);
if ($data === null) {
CLI::error('Epic free fetch failed');
return;
}
$elements = $data['data']['Catalog']['searchStore']['elements'] ?? [];
$now = time();
$inserted = 0;
$dealsInserted = 0;
foreach ($elements as $e) {
$title = $e['title'] ?? null;
if ($title === null) {
continue;
}
$slug = url_title($title, '-', true);
if ($slug === '') {
continue;
}
$price = $e['price']['totalPrice']['fmtPrice'] ?? [];
$orig = (float) str_replace(['$', ','], '', (string) ($price['originalPrice'] ?? '0'));
$final = (float) str_replace(['$', ','], '', (string) ($price['discountPrice'] ?? '0'));
$promos = $e['promotions'] ?? [];
$active = $promos['promotionalOffers'][0]['promotionalOffers'] ?? [];
$upcoming = $promos['upcomingPromotionalOffers'][0]['promotionalOffers'] ?? [];
$isFree = $final <= 0 || $active !== [] || $upcoming !== [];
$existing = Mongo::collection('games')->findOne(['slug' => $slug]);
$doc = [
'slug' => $slug,
'title' => $title,
'base_price' => $orig,
'genres' => [],
'platforms' => ['epic'],
'score' => 0,
'rating_pct' => 0,
'release_date' => new UTCDateTime($now * 1000),
'developer' => ($e['developer'] ?? 'Unknown') ?: 'Unknown',
'publisher' => ($e['publisher'] ?? 'Unknown') ?: 'Unknown',
'cover' => ['file' => $e['keyImages'][0]['url'] ?? '', 'from' => '#2b2b2b', 'to' => '#1a1a1a'],
'description' => $e['description'] ?? '',
'last_crawled' => new UTCDateTime($now * 1000),
'source' => 'epic',
];
if ($existing) {
foreach (['all_time_low', 'best_official', 'best_keyshop', 'active_deals', 'trending'] as $f) {
if (isset($existing[$f])) {
$doc[$f] = $existing[$f];
}
}
}
$r = Mongo::collection('games')->updateOne(['slug' => $slug], ['$set' => $doc], ['upsert' => true]);
if ($r->getUpsertedCount() > 0) {
$inserted++;
}
if ($final >= 0 && $orig > 0) {
$expiry = null;
foreach (array_merge($active, $upcoming) as $o) {
if (! empty($o['endDate'])) {
$expiry = new UTCDateTime(strtotime($o['endDate']) * 1000);
break;
}
}
Mongo::collection('deals')->updateOne(
['game_slug' => $slug, 'store_code' => 'epic'],
['$set' => [
'game_slug' => $slug,
'title' => $title,
'store_code' => 'epic',
'kind' => 'official',
'price' => round($final, 2),
'regular' => round($orig, 2),
'cut' => $isFree ? 100 : max(0, min(95, (int) round((1 - $final / $orig) * 100))),
'historical_low' => $isFree,
'drm' => 'Epic key',
'regional' => false,
'expiry' => $expiry,
'url' => 'https://store.epicgames.com/p/' . ($e['productSlug'] ?? $slug),
'last_crawled' => new UTCDateTime($now * 1000),
'source' => 'epic',
]],
['upsert' => true]
);
$dealsInserted++;
// free game → news freebie post (only when free and not already posted)
if ($isFree && $existing === null) {
$newsSlug = 'freebie-' . $slug;
if (Mongo::collection('news')->findOne(['slug' => $newsSlug]) === null) {
Mongo::collection('news')->insertOne([
'title' => $title . ' is FREE to keep on Epic Games Store',
'slug' => $newsSlug,
'category' => 'freebies',
'body' => "You can claim {$title} for free on the Epic Games Store right now — it's yours to keep forever once claimed. Head over to the store, sign in and hit the claim button before the offer expires.",
'game_slug' => $slug,
'date' => new UTCDateTime($now * 1000),
]);
}
}
}
usleep(150000);
}
CLI::write("Epic done: {$inserted} games inserted, {$dealsInserted} deals.", 'green');
}
// ------------------------------------------------------------------ helpers
private function fetchJson(string $url): ?array
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => self::UA,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($code !== 200 || $body === false) {
CLI::error("Fetch failed ({$code}): {$url}");
return null;
}
$json = json_decode($body, true);
if (! is_array($json)) {
CLI::error('Invalid JSON: ' . substr($body, 0, 100));
return null;
}
return $json;
}
private function parseDate(?string $date, string $format = 'd M, Y'): ?UTCDateTime
{
if ($date === null || $date === '' || str_contains($date, 'Coming soon')) {
return null;
}
$ts = \DateTime::createFromFormat($format, $date);
if ($ts === false) {
try {
$ts = new \DateTime($date);
} catch (\Exception) {
return null;
}
}
return new UTCDateTime($ts->getTimestamp() * 1000);
}
}
+329
View File
@@ -0,0 +1,329 @@
<?php
declare(strict_types=1);
namespace App\Commands;
use App\Libraries\Mongo;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use MongoDB\BSON\UTCDateTime;
/**
* Crawls detailed game data from gg.deals via a persistent FlareSolverr session.
*
* A FlareSolverr container must be reachable (default host "flaresolverr", port 80).
* The session is created once and reused, so the Cloudflare challenge is only
* solved on the first request — subsequent requests are fast.
*
* php spark gg:ggdeals → crawl details for all games we already have
* php spark gg:ggdeals --limit=50 → only the first 50 matched games (testing)
* php spark gg:ggdeals --slug=elden-ring → a single game by slug
*/
class CrawlGgdeals extends BaseCommand
{
protected $group = 'GGDeals';
protected $name = 'gg:ggdeals';
protected $description = 'Crawls detailed prices/deals from gg.deals via FlareSolverr session.';
protected $usage = 'gg:ggdeals [--limit=N] [--slug=X]';
private const FS_URL = 'http://flaresolverr:80/v1';
private const SESSION = 'ggdeals-crawler';
private const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36';
public function run(array $params): void
{
$limit = null;
$slug = null;
$batch = null;
foreach ($params as $k => $v) {
if (is_string($k) && str_starts_with($k, 'limit=')) {
$limit = (int) substr($k, 6);
}
if (is_string($k) && str_starts_with($k, 'slug=')) {
$slug = substr($k, 5);
}
if (is_string($k) && str_starts_with($k, 'batch=')) {
$batch = (int) substr($k, 6);
}
}
CLI::write('GG.deals detailed crawler started — ' . date('Y-m-d H:i:s'), 'green');
// ensure session exists
$this->fsRequest(['cmd' => 'sessions.create', 'session' => self::SESSION]);
CLI::write('FlareSolverr session ready: ' . self::SESSION, 'green');
// ---- pick games to crawl ----
$games = [];
if ($slug !== null) {
// single game
$g = Mongo::collection('games')->findOne(['slug' => $slug]);
if ($g !== null) {
$games[] = $g;
}
} elseif ($batch !== null) {
// expand from catalog: next N slugs not yet detailed
CLI::write("Batch mode: expanding {$batch} games from catalog…", 'yellow');
$slugs = Mongo::collection('catalog')
->find(['crawled' => false], ['projection' => ['slug' => 1], 'sort' => ['_id' => 1], 'limit' => $batch])
->toArray();
foreach ($slugs as $c) {
$cslug = $c['slug'];
$existing = Mongo::collection('games')->findOne(['slug' => $cslug]);
if ($existing !== null) {
// already detailed; mark catalog crawled and skip
Mongo::collection('catalog')->updateOne(['slug' => $cslug], ['$set' => ['crawled' => true]]);
continue;
}
$games[] = ['slug' => $cslug, 'title' => $cslug];
}
} else {
// refresh all games we already have
$filter = [];
$query = Mongo::collection('games')->find($filter, ['sort' => ['trending' => -1]]);
if ($limit !== null) {
$query = Mongo::collection('games')->find($filter, ['sort' => ['trending' => -1], 'limit' => $limit]);
}
$games = $query->toArray();
}
CLI::write('Games to crawl: ' . count($games), 'yellow');
$updated = 0;
$failed = 0;
foreach ($games as $i => $game) {
$gslug = $game['slug'];
$url = 'https://gg.deals/game/' . $gslug . '/';
$result = $this->fsRequest([
'cmd' => 'request.get',
'url' => $url,
'session' => self::SESSION,
'maxTimeout' => 30000,
'disableMedia'=> true,
]);
$html = $result['solution']['response'] ?? null;
if ($html === null || $html === '' || str_contains($html, 'Just a moment')) {
CLI::error(" [{$i}] {$gslug}: failed (challenge or empty)");
$failed++;
usleep(1000000);
continue;
}
$parsed = $this->parseGamePage($html, $gslug, $game);
if ($parsed !== null) {
$this->applyToDb($gslug, $parsed);
$updated++;
CLI::write(" [{$i}] {$gslug}: saved (best \${$parsed['best_price']})");
} else {
$failed++;
}
// mark catalog as processed regardless (so we don't retry endlessly)
Mongo::collection('catalog')->updateOne(
['slug' => $gslug],
['$set' => ['crawled' => true, 'crawled_at' => new UTCDateTime(time() * 1000)]],
['upsert' => true]
);
usleep(400000);
}
// destroy session when done
$this->fsRequest(['cmd' => 'sessions.destroy', 'session' => self::SESSION]);
CLI::write("Done: {$updated} updated, {$failed} failed.", 'green');
}
/**
* Parse a gg.deals game page using its JSON-LD structured data.
* Returns best price + all offers from the AggregateOffer block.
*/
private function parseGamePage(string $html, string $slug, array $existing): ?array
{
// extract JSON-LD blocks
if (! preg_match_all('/<script type="application\/ld\+json">(.*?)<\/script>/s', $html, $m)) {
return null;
}
$product = null;
foreach ($m[1] as $block) {
$j = json_decode(trim($block), true);
if (is_array($j) && ($j['@type'] ?? '') === 'Product' && isset($j['offers'])) {
$product = $j;
break;
}
}
if ($product === null) {
return null;
}
$offers = $product['offers'] ?? [];
$bestPrice = (float) ($offers['lowPrice'] ?? 0);
if ($bestPrice <= 0) {
return null;
}
$offerList = [];
foreach ($offers['offers'] ?? [] as $o) {
$price = (float) ($o['price'] ?? 0);
if ($price <= 0) {
continue;
}
$seller = $o['seller']['name'] ?? 'Unknown';
$offerList[] = [
'price' => $price,
'seller' => $seller,
'expiry' => isset($o['priceValidUntil'])
? (strtotime($o['priceValidUntil']) ?: null)
: null,
];
}
return [
'slug' => $slug,
'title' => $product['name'] ?? $slug,
'best_price' => $bestPrice,
'high_price' => (float) ($offers['highPrice'] ?? $bestPrice),
'offer_count'=> (int) ($offers['offerCount'] ?? count($offerList)),
'offers' => $offerList,
'crawled_at' => new UTCDateTime(time() * 1000),
];
}
private function applyToDb(string $slug, array $parsed): void
{
$now = time();
$existing = Mongo::collection('games')->findOne(['slug' => $slug]);
$title = $parsed['title'] ?? ($existing['title'] ?? $slug);
// update the game doc with the gg.deals lowest price (upsert for new games)
$set = [
'last_gg_crawled' => $parsed['crawled_at'],
'gg_best_price' => $parsed['best_price'],
'title' => $title,
'slug' => $slug,
'source' => 'ggdeals',
];
if ($existing === null) {
$set['genres'] = [];
$set['platforms'] = ['pc'];
$set['score'] = 0;
$set['rating_pct'] = 0;
$set['trending'] = 50;
$set['cover'] = ['file' => '', 'from' => '#1b2838', 'to' => '#171d25'];
$set['description'] = '';
}
if (! isset($existing['base_price']) || (float) $existing['base_price'] <= 0) {
$set['base_price'] = $parsed['high_price'];
}
// all-time low: keep the minimum of existing and gg.deals lowest
$currentHl = $existing['all_time_low']['price'] ?? null;
if ($currentHl === null || $parsed['best_price'] < (float) $currentHl) {
$set['all_time_low'] = [
'price' => $parsed['best_price'],
'store' => 'gg.deals',
'kind' => 'keyshop',
'date' => new UTCDateTime($now * 1000),
];
}
Mongo::collection('games')->updateOne(['slug' => $slug], ['$set' => $set], ['upsert' => true]);
// store each offer as a deal (upsert by game+store)
foreach ($parsed['offers'] as $o) {
$storeCode = $this->storeCode($o['seller']);
$expiry = $o['expiry'] !== null ? new UTCDateTime($o['expiry'] * 1000) : null;
Mongo::collection('deals')->updateOne(
['game_slug' => $slug, 'store_code' => $storeCode, 'source' => 'ggdeals'],
['$set' => [
'game_slug' => $slug,
'title' => $title,
'store_code' => $storeCode,
'kind' => 'keyshop',
'price' => round($o['price'], 2),
'regular' => round($parsed['high_price'], 2),
'cut' => $parsed['high_price'] > 0 ? (int) round((1 - $o['price'] / $parsed['high_price']) * 100) : 0,
'historical_low' => $o['price'] <= $parsed['best_price'] + 0.01,
'drm' => 'GG.deals key',
'regional' => false,
'expiry' => $expiry,
'url' => 'https://gg.deals/game/' . $slug . '/',
'last_crawled' => new UTCDateTime($now * 1000),
'source' => 'ggdeals',
]],
['upsert' => true]
);
}
}
/**
* Map a gg.deals seller name to a store code (best-effort).
*/
private function storeCode(string $seller): string
{
$map = [
'steam' => 'steam', 'gog' => 'gog', 'gog.com' => 'gog',
'epic' => 'epic', 'fanatical' => 'fanatical',
'humble' => 'humble', 'green man gaming' => 'gmg', 'gmg' => 'gmg',
'eneba' => 'eneba', 'kinguin' => 'kinguin', 'g2a' => 'g2a',
'gamivo' => 'gamivo', 'cdkeys' => 'cdkeys', 'hrk game' => 'hrk',
'instant gaming' => 'instantgaming', 'gamebillet' => 'gamebillet',
'gamersgate' => 'gamersgate', 'gamesplanet' => 'gamesplanet',
'k4g.com' => 'k4g', 'difmark' => 'difmark', 'driffle' => 'driffle',
];
$key = strtolower(trim($seller));
foreach ($map as $k => $code) {
if (str_contains($key, $k)) {
return $code;
}
}
return 'gg_' . url_title($seller, '_', true);
}
/**
* Send a command to the FlareSolverr API.
*/
private function fsRequest(array $payload): ?array
{
$ch = curl_init(self::FS_URL);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 90,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_SSL_VERIFYPEER => false,
]);
$body = curl_exec($ch);
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($code !== 200 || $body === false) {
CLI::error('FlareSolverr request failed: ' . $code);
return null;
}
$json = json_decode($body, true);
if (! is_array($json)) {
return null;
}
if (($json['status'] ?? '') === 'error') {
CLI::error('FlareSolverr error: ' . ($json['message'] ?? 'unknown'));
return null;
}
return $json;
}
}
+677
View File
@@ -0,0 +1,677 @@
<?php
declare(strict_types=1);
namespace App\Commands;
use App\Libraries\Mongo;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use MongoDB\BSON\UTCDateTime;
/**
* Seeds the gg.deals clone database.
*/
class SeedDatabase extends BaseCommand
{
protected $group = 'GGDeals';
protected $name = 'gg:seed';
protected $description = 'Seeds stores, games, deals, price history and generates cover art.';
protected $usage = 'gg:seed';
private const COVERS_DIR = WRITEPATH . '../public/img/covers';
/** ------------------------------------------------------------------ */
private array $stores = [
// code, name, kind, color (badge bg), text color
['steam', 'Steam', 'official', '#173d5e', '#c9d9e8'],
['gog', 'GOG.com', 'official', '#862a52', '#f3d7e3'],
['epic', 'Epic Games Store', 'official', '#2b2b2b', '#e8e8e8'],
['humble', 'Humble Store', 'official', '#a52a2a', '#ffe3e3'],
['fanatical', 'Fanatical', 'official', '#b34700', '#ffe6cc'],
['gmg', 'GreenMan Gaming', 'official', '#7a1533', '#ffd9e6'],
['gamesplanet', 'Gamesplanet', 'official', '#8a6d00', '#fff3c4'],
['wingamestore', 'WinGameStore', 'official', '#14532d', '#d3f8e0'],
['gamersgate', 'GamersGate', 'official', '#0c4a6e', '#cdeaff'],
['indiegala', 'IndieGala', 'official', '#4c1d95', '#e4d9ff'],
['2game', '2game', 'official', '#166534', '#dcfce7'],
['eneba', 'Eneba', 'keyshop', '#0e7490', '#cffafe'],
['kinguin', 'Kinguin', 'keyshop', '#9f1239', '#ffe4e6'],
['g2a', 'G2A', 'keyshop', '#9a3412', '#ffedd5'],
['cdkeys', 'CDKeys.com', 'keyshop', '#b45309', '#fef3c7'],
['instantgaming', 'Instant Gaming', 'keyshop', '#075985', '#e0f2fe'],
['hrk', 'HRK Game', 'keyshop', '#1e293b', '#e2e8f0'],
['gamivo', 'Gamivo', 'keyshop', '#3f6212', '#ecfccb'],
['driffle', 'Driffle', 'keyshop', '#5b21b6', '#ede9fe'],
['difmark', 'Difmark', 'keyshop', '#155e75', '#e0f2fe'],
];
/** title, base price, release year, genres, platforms, score, rating % */
private array $games = [
['Elden Ring', 59.99, 2022, ['Action RPG', 'Souls-like', 'Open World'], ['steam', 'epic'], 96, 92],
['Cyberpunk 2077', 59.99, 2020, ['RPG', 'Open World', 'Sci-fi'], ['steam', 'epic', 'gog'], 86, 78],
['Red Dead Redemption 2', 59.99, 2019, ['Action', 'Open World', 'Western'], ['steam', 'epic', 'gog'], 93, 89],
['Grand Theft Auto V', 29.99, 2015, ['Action', 'Open World', 'Crime'], ['steam', 'epic'], 96, 84],
['The Witcher 3: Wild Hunt', 39.99, 2015, ['RPG', 'Open World', 'Fantasy'], ['steam', 'epic', 'gog'], 92, 96],
["Baldur's Gate 3", 59.99, 2023, ['RPG', 'Turn-based', 'Fantasy'], ['steam', 'gog'], 96, 94],
['Hogwarts Legacy', 59.99, 2023, ['RPG', 'Open World', 'Fantasy'], ['steam', 'epic'], 84, 81],
['Starfield', 69.99, 2023, ['RPG', 'Sci-fi', 'Open World'], ['steam'], 83, 72],
['Alan Wake 2', 59.99, 2023, ['Horror', 'Action', 'Story Rich'], ['epic'], 89, 90],
['Resident Evil 4', 59.99, 2023, ['Horror', 'Action', 'Remake'], ['steam'], 93, 97],
['Street Fighter 6', 59.99, 2023, ['Fighting', 'Esports'], ['steam'], 92, 88],
['Diablo IV', 69.99, 2023, ['ARPG', 'Dark Fantasy', 'Online'], ['steam', 'gog'], 88, 74],
['EA Sports FC 24', 69.99, 2023, ['Sports', 'Football'], ['steam', 'epic'], 76, 51],
['Cities: Skylines II', 49.99, 2023, ['Simulation', 'City Builder', 'Strategy'], ['steam'], 73, 65],
['Total War: WARHAMMER III', 59.99, 2022, ['Strategy', 'Turn-based', 'Fantasy'], ['steam', 'epic'], 86, 82],
['God of War', 49.99, 2022, ['Action', 'Adventure', 'Mythology'], ['steam', 'epic'], 94, 96],
["Marvel's Spider-Man Remastered", 59.99, 2022, ['Action', 'Adventure', 'Superhero'], ['steam'], 88, 95],
["Marvel's Spider-Man 2", 59.99, 2024, ['Action', 'Adventure', 'Superhero'], ['steam', 'epic'], 86, 91],
['The Last of Us Part I', 59.99, 2023, ['Action', 'Adventure', 'Post-apocalyptic'], ['steam'], 88, 84],
['Horizon Forbidden West', 59.99, 2024, ['RPG', 'Open World', 'Sci-fi'], ['steam', 'epic'], 88, 89],
['Forza Horizon 5', 59.99, 2021, ['Racing', 'Open World', 'Sports'], ['steam'], 92, 88],
['Microsoft Flight Simulator', 59.99, 2021, ['Simulation', 'Flight', 'Realistic'], ['steam'], 91, 79],
['Age of Empires IV', 59.99, 2021, ['Strategy', 'RTS', 'Historical'], ['steam'], 87, 83],
['It Takes Two', 39.99, 2021, ['Co-op', 'Platformer', 'Adventure'], ['steam', 'epic', 'gog'], 89, 95],
['Sonic Frontiers', 59.99, 2022, ['Platformer', 'Action', 'Open World'], ['steam'], 75, 82],
['Persona 5 Royal', 59.99, 2022, ['JRPG', 'Turn-based', 'Anime'], ['steam'], 94, 97],
['Monster Hunter Rise', 39.99, 2022, ['Action RPG', 'Co-op', 'Hunting'], ['steam'], 87, 90],
['Palworld', 29.99, 2024, ['Survival', 'Crafting', 'Creature Collector'], ['steam', 'epic'], 78, 85],
['Helldivers 2', 39.99, 2024, ['Co-op', 'Shooter', 'Sci-fi'], ['steam'], 82, 79],
['Enshrouded', 29.99, 2024, ['Survival', 'Crafting', 'Voxel'], ['steam'], 80, 86],
['Manor Lords', 39.99, 2024, ['Strategy', 'City Builder', 'Medieval'], ['steam', 'gog'], 83, 88],
['Hades II', 29.99, 2024, ['Roguelike', 'Action', 'Mythology'], ['steam'], 90, 96],
['Counter-Strike 2', 14.99, 2023, ['Shooter', 'Esports', 'Multiplayer'], ['steam'], 83, 87],
['Valheim', 19.99, 2021, ['Survival', 'Crafting', 'Co-op'], ['steam'], 90, 94],
['Terraria', 9.99, 2011, ['Sandbox', 'Survival', 'Crafting'], ['steam', 'gog'], 83, 97],
['Stardew Valley', 14.99, 2016, ['Farming Sim', 'RPG', 'Pixel Graphics'], ['steam', 'gog'], 89, 98],
['Factorio', 35.00, 2020, ['Simulation', 'Automation', 'Sandbox'], ['steam', 'gog'], 90, 97],
['RimWorld', 34.99, 2016, ['Simulation', 'Colony Sim', 'Strategy'], ['steam'], 92, 97],
['Slay the Spire', 24.99, 2019, ['Roguelike', 'Deckbuilder', 'Card Game'], ['steam', 'gog'], 89, 96],
['Deep Rock Galactic', 29.99, 2020, ['Co-op', 'Shooter', 'Mining'], ['steam', 'epic'], 85, 97],
['Hollow Knight', 14.99, 2017, ['Metroidvania', 'Platformer', 'Indie'], ['steam', 'gog'], 90, 97],
['Dead Cells', 24.99, 2018, ['Roguelike', 'Metroidvania', 'Action'], ['steam', 'gog', 'epic'], 89, 95],
['Cuphead', 19.99, 2017, ['Platformer', 'Run & Gun', 'Cartoony'], ['steam', 'gog'], 88, 95],
['Ori and the Will of the Wisps', 29.99, 2020, ['Metroidvania', 'Platformer', 'Story Rich'], ['steam'], 90, 93],
['Sekiro: Shadows Die Twice', 59.99, 2019, ['Action', 'Souls-like', 'Stealth'], ['steam', 'epic'], 90, 90],
['Dark Souls III', 59.99, 2016, ['Action RPG', 'Souls-like', 'Dark Fantasy'], ['steam'], 89, 88],
['Dishonored 2', 39.99, 2016, ['Stealth', 'Action', 'Immersive Sim'], ['steam'], 86, 91],
['DOOM Eternal', 59.99, 2020, ['Shooter', 'Action', 'FPS'], ['steam', 'gog'], 88, 93],
['Metro Exodus', 39.99, 2019, ['Shooter', 'Post-apocalyptic', 'Story Rich'], ['steam', 'epic', 'gog'], 85, 88],
['Kingdom Come: Deliverance', 29.99, 2018, ['RPG', 'Open World', 'Historical'], ['steam', 'gog', 'epic'], 88, 88],
['NieR: Automata', 39.99, 2017, ['Action RPG', 'Anime', 'Story Rich'], ['steam'], 88, 91],
['Death Stranding', 59.99, 2020, ['Adventure', 'Open World', 'Sci-fi'], ['steam', 'epic'], 86, 89],
['Control', 39.99, 2019, ['Action', 'Adventure', 'Supernatural'], ['steam', 'epic', 'gog'], 85, 86],
['Outer Wilds', 24.99, 2019, ['Adventure', 'Exploration', 'Puzzle'], ['steam', 'epic'], 85, 92],
['Disco Elysium', 39.99, 2019, ['RPG', 'Detective', 'Story Rich'], ['steam', 'gog'], 91, 94],
['Divinity: Original Sin 2', 44.99, 2017, ['RPG', 'Turn-based', 'Fantasy'], ['steam', 'gog'], 93, 95],
['Warhammer 40,000: Darktide', 39.99, 2022, ['Co-op', 'Shooter', 'Action'], ['steam'], 74, 68],
['Ready or Not', 49.99, 2023, ['Shooter', 'Tactical', 'Co-op'], ['steam'], 80, 89],
['Lethal Company', 9.99, 2023, ['Horror', 'Co-op', 'Survival'], ['steam'], 84, 92],
['Balan Wonderworld', 39.99, 2021, ['Platformer', 'Adventure', 'Fantasy'], ['steam'], 55, 62],
['eFootball 2024', 39.99, 2023, ['Sports', 'Football', 'Free to Play'], ['steam'], 60, 44],
];
private array $palettes = [
['#4338ca', '#7c3aed'], ['#0f766e', '#14b8a6'], ['#b91c1c', '#f97316'],
['#065f46', '#84cc16'], ['#1e3a8a', '#3b82f6'], ['#831843', '#ec4899'],
['#713f12', '#facc15'], ['#155e75', '#22d3ee'], ['#3f1d38', '#a78bfa'],
['#134e4a', '#2dd4bf'], ['#450a0a', '#ef4444'], ['#312e81', '#818cf8'],
['#14532d', '#4ade80'], ['#581c87', '#c084fc'], ['#7c2d12', '#fb923c'],
['#1e293b', '#64748b'], ['#0c4a6e', '#38bdf8'], ['#701a75', '#f0abfc'],
['#365314', '#a3e635'], ['#7f1d1d', '#fca5a5'],
];
public function run(array $params): void
{
mt_srand(424242);
$db = Mongo::db();
$db->drop();
// ------------------------------------------------------------------ stores
$stores = [];
foreach ($this->stores as [$code, $name, $kind, $color, $text]) {
$stores[$code] = [
'code' => $code,
'name' => $name,
'kind' => $kind,
'color' => $color,
'textcolor' => $text,
'logo' => '/img/stores/' . $code . '.png',
];
}
$db->selectCollection('stores')->insertMany(array_values($stores));
CLI::write('Inserted ' . count($stores) . ' stores.', 'green');
if (! is_dir(self::COVERS_DIR)) {
mkdir(self::COVERS_DIR, 0777, true);
}
// ------------------------------------------------------------------ games + deals + history
$officialCodes = array_keys(array_filter($stores, static fn ($s) => $s['kind'] === 'official'));
$keyshopCodes = array_keys(array_filter($stores, static fn ($s) => $s['kind'] === 'keyshop'));
$gamesBatch = [];
$dealsBatch = [];
$historyBatch = [];
$now = time();
foreach ($this->games as $i => [$title, $base, $year, $genres, $platforms, $score, $rating]) {
$slug = url_title($title, '-', true);
// all-time low: 25% - 60% of base
$hlFactor = 0.25 + (mt_rand(0, 35) / 100);
$hlPrice = round($base * $hlFactor, 2);
$hlPrice = $this->prettyPrice($hlPrice);
// historical low store + date (3-18 months ago)
$hlStoreCode = $this->pick(array_merge($officialCodes, $keyshopCodes));
$hlDaysAgo = mt_rand(90, 540);
$hlDate = $now - $hlDaysAgo * 86400;
// ---- official deals
$nOfficial = mt_rand(2, 5);
$officialStores = $this->pickN($officialCodes, $nOfficial);
// best current official price: between HL and 85% of base
$bestOfficial = round($hlPrice * (1 + mt_rand(0, 60) / 100), 2);
$bestOfficial = min($bestOfficial, round($base * 0.85, 2));
$bestOfficial = $this->prettyPrice($bestOfficial);
$officialDeals = [];
foreach ($officialStores as $j => $sc) {
$price = $j === 0
? $bestOfficial
: $this->prettyPrice(round($bestOfficial * (1 + mt_rand(5, 45) / 100), 2));
$price = min($price, $this->prettyPrice(round($base * 0.95, 2)));
$cut = round((1 - $price / $base) * 100);
$officialDeals[] = $this->dealDoc($slug, $sc, 'official', $price, $base, $cut, $hlPrice, $platforms, $title);
}
// ---- keyshop deals (usually cheaper, more stores)
$nKey = mt_rand(3, 8);
$keyStores = $this->pickN($keyshopCodes, $nKey);
$bestKey = $this->prettyPrice(round(max($hlPrice * (0.88 + mt_rand(0, 20) / 1000), 1.5), 2));
$bestKey = min($bestKey, $bestOfficial);
$keyshopDeals = [];
foreach ($keyStores as $j => $sc) {
$price = $j === 0
? $bestKey
: $this->prettyPrice(round($bestKey + mt_rand(0, 300) / 100, 2));
$cut = round((1 - $price / $base) * 100);
$keyshopDeals[] = $this->dealDoc($slug, $sc, 'keyshop', $price, $base, $cut, $hlPrice, $platforms, $title);
}
$dealsBatch = array_merge($dealsBatch, $officialDeals, $keyshopDeals);
// ---- price history: 2 official + 2 keyshop stores, point every 5 days for ~540 days
$histStores = array_merge(
$this->pickN($officialCodes, 2),
$this->pickN($keyshopCodes, 2)
);
foreach ($histStores as $sc) {
$kind = $stores[$sc]['kind'];
// this store's floor: make one store hit the all-time low
$floor = ($sc === $hlStoreCode) ? $hlPrice : $this->prettyPrice(round($hlPrice * (1.05 + mt_rand(0, 50) / 100), 2));
for ($d = 540; $d >= 0; $d -= 5) {
$ts = $now - $d * 86400;
// sales pattern: occasional dips (sales every ~2-4 months)
$inSale = (mt_rand(1, 72) <= 7);
if ($kind === 'keyshop') {
// keyshops are consistently low & noisy
$price = round($hlPrice * (1.0 + mt_rand(0, 90) / 100), 2);
} elseif ($inSale) {
$price = round($floor * (1 + mt_rand(0, 25) / 100), 2);
} else {
$price = round($base * (0.95 + mt_rand(0, 8) / 100), 2);
}
if ($price < $floor && $sc !== $hlStoreCode) {
$price = $floor;
}
$historyBatch[] = [
'game_slug' => $slug,
'store_code' => $sc,
'kind' => $kind,
'ts' => new UTCDateTime($ts * 1000),
'price' => round($price, 2),
];
}
}
$bestDealAll = $this->minDeal(array_merge($officialDeals, $keyshopDeals));
$activeDeals = count($officialDeals) + count($keyshopDeals);
$trending = mt_rand(35, 100) + $bestDealAll['cut'] * 2;
$palette = $this->palettes[$i % count($this->palettes)];
$coverFile = '/img/covers/' . $slug . '.svg';
$this->writeCover($slug, $title, $palette);
$gamesBatch[] = [
'slug' => $slug,
'title' => $title,
'base_price' => $base,
'genres' => $genres,
'platforms' => $platforms,
'score' => $score,
'rating_pct' => $rating,
'release_date' => new UTCDateTime(mktime(0, 0, 0, mt_rand(1, 12), mt_rand(1, 28), $year) * 1000),
'all_time_low' => [
'price' => $hlPrice,
'store' => $hlStoreCode,
'kind' => $stores[$hlStoreCode]['kind'],
'date' => new UTCDateTime($hlDate * 1000),
],
'best_official' => [
'price' => $officialDeals[0]['price'],
'store' => $officialDeals[0]['store_code'],
'cut' => $officialDeals[0]['cut'],
],
'best_keyshop' => [
'price' => $keyshopDeals[0]['price'],
'store' => $keyshopDeals[0]['store_code'],
'cut' => $keyshopDeals[0]['cut'],
],
'active_deals' => $activeDeals,
'trending' => $trending,
'cover' => ['file' => $coverFile, 'from' => $palette[0], 'to' => $palette[1]],
'developer' => $this->pick(['Studio Nova', 'Pixel Forge', 'Iron Tower Games', 'Blue Moon Interactive', 'Red Circuit', 'Crystal Works', 'Dark Harbor Studio', 'Ember Games']),
'publisher' => $this->pick(['Nova Publishing', 'PixelWorks', 'Global Games', 'East Coast Interactive', 'Stellar Publishing', 'Iron Crown']),
'length' => ['main' => mt_rand(6, 60), 'completion' => mt_rand(15, 150), 'perfect' => mt_rand(25, 250)],
'age_rating' => $this->pick(['E (Everyone)', 'E10+', 'T (Teen)', 'M (Mature 17+)']),
'description' => $this->makeDescription($title, $genres),
'sys_reqs' => [
'os' => $this->pick(['Windows 10 64-bit', 'Windows 11 64-bit']),
'cpu' => $this->pick(['Intel Core i5-8400', 'AMD Ryzen 5 2600', 'Intel Core i7-9700K', 'AMD Ryzen 7 3700X']),
'ram' => $this->pick(['8 GB', '16 GB']),
'gpu' => $this->pick(['NVIDIA GTX 1060', 'AMD RX 580', 'NVIDIA RTX 2060', 'NVIDIA RTX 3060']),
'storage' => mt_rand(15, 120) . ' GB',
],
];
}
$db->selectCollection('games')->insertMany($gamesBatch);
CLI::write('Inserted ' . count($gamesBatch) . ' games.', 'green');
// deals in chunks
foreach (array_chunk($dealsBatch, 500) as $chunk) {
$db->selectCollection('deals')->insertMany($chunk);
}
CLI::write('Inserted ' . count($dealsBatch) . ' deals.', 'green');
foreach (array_chunk($historyBatch, 1000) as $chunk) {
$db->selectCollection('price_history')->insertMany($chunk);
}
CLI::write('Inserted ' . count($historyBatch) . ' price history points.', 'green');
// ------------------------------------------------------------------ vouchers / news / prepaids
$this->seedVouchers($db);
$this->seedNews($db);
$this->seedPrepaids($db);
$this->seedSubscriptions($db);
$this->seedBundles($db);
$this->seedFranchises($db);
// ------------------------------------------------------------------ indexes
Mongo::collection('games')->createIndex(['slug' => 1], ['unique' => true]);
Mongo::collection('games')->createIndex(['trending' => -1]);
Mongo::collection('deals')->createIndex(['game_slug' => 1, 'price' => 1]);
Mongo::collection('deals')->createIndex(['store_code' => 1]);
Mongo::collection('price_history')->createIndex(['game_slug' => 1, 'kind' => 1, 'ts' => 1]);
CLI::write('Indexes created.', 'green');
CLI::write('Done. Generated covers in public/img/covers.', 'green');
}
private function seedVouchers($db): void
{
$vouchers = [
// store_code, title, code, discount, min_spend, valid_until(days), description
['eneba', '10% off sitewide', '10GGFEB', 10, 0, 30, '10% off your entire order at Eneba.'],
['eneba', '12% off select keys', '12GGDEAL', 12, 20, 21, 'Save 12% on orders over $20.'],
['kinguin', '14% off Kinguin', '14GGDEAL', 14, 0, 14, '14% discount on all Kinguin orders.'],
['kinguin', '5% off weekend sale', 'KQ5WEEK', 5, 10, 10, '5% off any purchase over $10.'],
['g2a', 'GG.deals exclusive', 'GG20FEB', 20, 0, 7, 'Exclusive 20% off for GG.deals visitors.'],
['g2a', '8% off G2A', 'GG8FEB', 8, 0, 14, '8% off sitewide at G2A.'],
['gamivo', 'GAMIVO promo', 'GAMIVO', 5, 0, 21, '5% off at GAMIVO marketplace.'],
['fanatical', 'Bundle discount', 'FAN10', 10, 25, 30, '10% off bundles over $25.'],
['gmg', 'Green Man Gaming', 'RATDEAL', 12, 0, 10, '12% off select Green Man Gaming titles.'],
['gamesplanet', 'Gamesplanet code', 'GSPLANET', 7, 0, 21, '7% off all Gamesplanet purchases.'],
['gamersgate', 'GamersGate welcome', 'GATE5', 5, 0, 30, '5% off your first GamersGate order.'],
['2game', '2Game special', '2GAME10', 10, 0, 14, '10% off at 2Game.'],
['wingamestore','WinGameStore', 'WGS15', 15, 30, 21, '15% off orders over $30.'],
['driffle', 'Driffle coupon', 'DRIFF10', 10, 0, 10, '10% off Driffle digital goods.'],
['cdkeys', 'CDKeys weekly', 'CDKEYS5', 5, 0, 7, '5% off CDKeys.com.'],
['instantgaming','Instant Gaming', 'IG4', 4, 0, 30, '4% off Instant Gaming orders.'],
];
$docs = [];
foreach ($vouchers as [$store, $title, $code, $discount, $minSpend, $days, $desc]) {
$docs[] = [
'store' => $store,
'title' => $title,
'code' => $code,
'discount' => $discount,
'min_spend' => $minSpend,
'active' => true,
'expires' => new UTCDateTime((time() + $days * 86400) * 1000),
'created' => new UTCDateTime((time() - mt_rand(1, 20) * 86400) * 1000),
'description'=> $desc,
];
}
$db->selectCollection('vouchers')->insertMany($docs);
CLI::write('Inserted ' . count($docs) . ' vouchers.', 'green');
}
private function seedNews($db): void
{
$templates = [
'deals' => ['title' => 'Weekend Sale: up to %d%% off top games across all stores', 'body' => 'This weekend, %d games have dropped to their historical lows. From AAA blockbusters to indie gems, now is the perfect time to grab that game you have been eyeing. Check the deals page for the full list.'],
'bundles' => ['title' => 'New bundle: get %d games for under $%d', 'body' => 'A fresh bundle just landed on the storefront. Pick up %d hand-picked titles for a fraction of their combined value. As always, we break down whether the bundle is actually worth it.'],
'freebies' => ['title' => '%s is FREE to keep on %s', 'body' => 'You can claim %s for free right now — and it is yours to keep forever once claimed. Head over to %s, sign in and hit the install button before the offer expires.'],
'giveaways' => ['title' => 'Giveaway: win a copy of %s', 'body' => 'We are giving away a copy of %s to one lucky winner. Enter via the community page — a random winner will be picked at the end of the week. Good luck!'],
'subscriptions' => ['title' => 'New titles added to %s this month', 'body' => 'A fresh wave of games just hit the subscription service. Here is everything new and our quick verdicts on what is worth your time this month.'],
];
$cats = array_keys($templates);
$docs = [];
for ($i = 0; $i < 24; $i++) {
$cat = $cats[$i % count($cats)];
$t = $templates[$cat];
$game = $this->games[array_rand($this->games)];
$store = ['Steam', 'GOG', 'Epic Games Store', 'Amazon', 'Humble Store'][array_rand(['Steam', 'GOG', 'Epic Games Store', 'Amazon', 'Humble Store'])];
$title = sprintf($t['title'], mt_rand(30, 90), mt_rand(5, 20), $game[0], $store, $game[0]);
$body = sprintf($t['body'], mt_rand(30, 90), mt_rand(5, 20), $game[0], $store);
$docs[] = [
'title' => $title,
'slug' => url_title($title, '-', true) . '-' . ($i + 1),
'category' => $cat,
'body' => $body,
'game_slug'=> $game[1] ?? null,
'date' => new UTCDateTime((time() - $i * mt_rand(1, 3) * 86400) * 1000),
];
}
$db->selectCollection('news')->insertMany($docs);
CLI::write('Inserted ' . count($docs) . ' news posts.', 'green');
}
private function seedPrepaids($db): void
{
$groups = [
['Steam Gift Cards', 'steam', [5, 10, 20, 50, 100]],
['PlayStation Gift Cards','playstation', [10, 25, 50, 100]],
['Xbox Gift Cards', 'xbox', [10, 25, 50, 100]],
['Nintendo eShop Cards', 'nintendo', [10, 25, 50, 75]],
['Roblox Gift Cards', 'roblox', [10, 25, 50]],
['Amazon Gift Cards', 'amazon', [10, 25, 50, 100]],
['Razer Gold', 'razer', [10, 25, 50]],
['Google Play Cards', 'googleplay',[10, 25, 50]],
];
$docs = [];
foreach ($groups as [$name, $code, $denoms]) {
$offers = [];
foreach ($denoms as $d) {
$offers[] = [
'denomination' => $d,
'price' => round($d * (0.92 + mt_rand(0, 10) / 100), 2),
'store' => $this->pick(['eneba', 'kinguin', 'g2a', 'cdkeys', 'instantgaming']),
];
}
$docs[] = [
'name' => $name,
'code' => $code,
'color' => $this->palettes[array_rand($this->palettes)],
'offers' => $offers,
];
}
$db->selectCollection('prepaids')->insertMany($docs);
CLI::write('Inserted ' . count($docs) . ' prepaid groups.', 'green');
}
private function seedSubscriptions($db): void
{
$subs = [
['Xbox Game Pass Ultimate', 'gamepass', 14.99, 'PC + console + cloud gaming, 500+ games'],
['PC Game Pass', 'gamepass', 9.99, 'Hundreds of PC games included'],
['PlayStation Plus Essential', 'psplus', 9.99, 'Online multiplayer + monthly games'],
['PlayStation Plus Extra', 'psplus', 14.99,'All Essential benefits + catalog'],
['PlayStation Plus Premium', 'psplus', 17.99,'All Extra benefits + classic catalog'],
['EA Play', 'eaplay', 5.99, 'EA games library + trials'],
['Ubisoft+ Classics', 'ubisoft', 7.99, 'Classic Ubisoft games catalog'],
['Nintendo Switch Online', 'nso', 3.99, 'Online play + retro library'],
];
$docs = [];
foreach ($subs as [$name, $brand, $price, $desc]) {
$docs[] = [
'name' => $name,
'brand' => $brand,
'price' => $price,
'period' => $this->pick(['1 Month', '3 Months', '12 Months']),
'desc' => $desc,
'store' => $this->pick(['eneba', 'kinguin', 'g2a', 'instantgaming', 'cdkeys']),
];
}
$db->selectCollection('subscriptions')->insertMany($docs);
CLI::write('Inserted ' . count($docs) . ' subscriptions.', 'green');
}
private function seedBundles($db): void
{
$validSlugs = [];
foreach ($this->games as $g) {
$validSlugs[url_title($g[0], '-', true)] = $g[2]; // slug => base price
}
$docs = [];
for ($i = 0; $i < 10; $i++) {
$slugs = array_keys($validSlugs);
$gameSlugs = $this->pickN($slugs, mt_rand(3, 8));
$baseTotal = 0;
foreach ($gameSlugs as $slug) {
$baseTotal += $validSlugs[$slug];
}
$bundlePrice = round($baseTotal * (0.08 + mt_rand(0, 15) / 100), 2);
$name = $this->pick(['Ultimate', 'Mega', 'Fan', 'Classic', 'Indie', 'Strategy', 'RPG', 'Action']) . ' Bundle #' . ($i + 1);
$docs[] = [
'slug' => url_title($name, '-', true) . '-' . ($i + 1),
'title' => $name,
'game_count' => count($gameSlugs),
'games' => $gameSlugs,
'price' => $bundlePrice,
'regular' => round($baseTotal, 2),
'store' => $this->pick(['humble', 'fanatical', 'gmg', 'indiegala', '2game']),
'active' => true,
'expires' => new UTCDateTime((time() + mt_rand(3, 21) * 86400) * 1000),
'desc' => 'Get ' . count($gameSlugs) . ' hand-picked games for a fraction of their combined value. Pay what you want from $' . number_format($bundlePrice, 2) . '.',
];
}
$db->selectCollection('bundles')->insertMany($docs);
CLI::write('Inserted ' . count($docs) . ' bundles.', 'green');
}
private function seedFranchises($db): void
{
$franchises = [
['resident-evil', 'Resident Evil', ['resident-evil-4']],
['dark-souls', 'Dark Souls', ['dark-souls-iii', 'elden-ring', 'sekiro-shadows-die-twice']],
['witcher', 'The Witcher', ['the-witcher-3-wild-hunt']],
['cyberpunk', 'Cyberpunk', ['cyberpunk-2077']],
['spider-man', 'Marvel\'s Spider-Man', ['marvels-spider-man-remastered', 'marvels-spider-man-2']],
['doom', 'DOOM', ['doom-eternal']],
['red-dead', 'Red Dead', ['red-dead-redemption-2', 'grand-theft-auto-v']],
['age-of-empires', 'Age of Empires', ['age-of-empires-iv']],
['total-war', 'Total War', ['total-war-warhammer-iii']],
['metro', 'Metro', ['metro-exodus']],
['diablo', 'Diablo', ['diablo-iv']],
['starfield', 'Starfield', ['starfield']],
['fallout', 'Fallout', ['starfield', 'the-last-of-us-part-i']],
['fps', 'First-Person Shooters', ['counter-strike-2', 'doom-eternal', 'deep-rock-galactic', 'helldivers-2', 'metro-exodus', 'warhammer-40000-darktide']],
['rpg', 'RPG Classics', ['elden-ring', 'baldurs-gate-3', 'the-witcher-3-wild-hunt', 'cyberpunk-2077', 'disco-elysium', 'divinity-original-sin-2', 'persona-5-royal']],
['strategy', 'Strategy', ['age-of-empires-iv', 'total-war-warhammer-iii', 'cities-skylines-ii', 'factorio', 'rimworld', 'slay-the-spire', 'civilization']],
['co-op', 'Co-op & Multiplayer', ['it-takes-two', 'deep-rock-galactic', 'helldivers-2', 'lethal-company', 'valheim', 'terraria', 'counter-strike-2']],
['indie', 'Indie Gems', ['hollow-knight', 'dead-cells', 'cuphead', 'stardew-valley', 'terraria', 'slay-the-spire', 'outer-wilds', 'lethal-company', 'hades-ii']],
['souls', 'Souls-like', ['elden-ring', 'sekiro-shadows-die-twice', 'dark-souls-iii']],
];
$docs = [];
$validSlugs = [];
foreach ($this->games as $g) {
$validSlugs[url_title($g[0], '-', true)] = true;
}
foreach ($franchises as [$slug, $name, $gameSlugs]) {
$matched = array_values(array_filter($gameSlugs, fn ($s) => isset($validSlugs[$s])));
if ($matched !== []) {
$docs[] = [
'slug' => $slug,
'name' => $name,
'games' => $matched,
];
}
}
$db->selectCollection('franchises')->insertMany($docs);
CLI::write('Inserted ' . count($docs) . ' franchises.', 'green');
}
// ---------------------------------------------------------------------- helpers
private function dealDoc(string $slug, string $store, string $kind, float $price, float $base, int|float $cut, float $hlPrice, array $platforms, string $title): array
{
$drm = match ($platforms[0] ?? 'steam') {
'gog' => 'DRM-free',
'epic' => 'Epic key',
default => 'Steam key',
};
return [
'game_slug' => $slug,
'title' => $title,
'store_code' => $store,
'kind' => $kind,
'price' => round($price, 2),
'regular' => $base,
'cut' => (int) max(0, min(95, $cut)),
'historical_low' => round($price, 2) <= round($hlPrice + 0.01, 2),
'drm' => $drm,
'regional' => $kind === 'keyshop' && mt_rand(1, 10) <= 3,
'expiry' => mt_rand(1, 10) <= 4 ? new UTCDateTime((time() + mt_rand(1, 7) * 86400) * 1000) : null,
'url' => 'https://www.google.com/search?q=' . rawurlencode("buy {$title} {$store}"),
];
}
private function pick(array $items)
{
return $items[array_rand($items)];
}
private function makeDescription(string $title, array $genres): string
{
$openers = [
"Step into the world of {$title}, a game that blends",
"{$title} invites you to experience",
"In {$title}, every choice matters as you explore",
"Prepare yourself for {$title}, an unforgettable journey through",
"{$title} delivers a rich experience combining",
];
$mid = implode(', ', array_slice($genres, 0, 3));
$closers = [
"With stunning visuals, a compelling soundtrack and deep gameplay mechanics, {$title} is a must-play for fans of {$mid}.",
"Whether you are a veteran or newcomer, {$title} offers hours of engaging content with its polished {$mid} systems.",
"Critically praised for its {$mid} design, {$title} pushes the genre forward with bold ideas and tight execution.",
"From its atmospheric world to its refined combat, {$title} is the definitive {$mid} experience of its generation.",
];
return $this->pick($openers) . ' ' . $this->pick($closers);
}
private function pickN(array $items, int $n): array
{
shuffle($items);
return array_slice($items, 0, min($n, count($items)));
}
private function minDeal(array $deals): array
{
usort($deals, static fn ($a, $b) => $a['price'] <=> $b['price']);
return $deals[0];
}
private function prettyPrice(float $p): float
{
if ($p >= 20 && mt_rand(0, 1) === 1) {
return (float) (floor($p) + 0.99);
}
return round($p, 2);
}
private function writeCover(string $slug, string $title, array $palette): void
{
$words = preg_split('/\s+/', $title) ?: [];
$initials = '';
foreach ($words as $w) {
if ($w === '' || ! ctype_alpha($w[0])) {
continue;
}
$initials .= strtoupper($w[0]);
if (strlen($initials) >= 2) {
break;
}
}
if ($initials === '') {
$initials = strtoupper(substr($slug, 0, 2));
}
[$c1, $c2] = $palette;
$pattern = crc32($slug) % 5;
$shapes = match ($pattern) {
0 => '<circle cx="400" cy="40" r="90" fill="#ffffff" opacity="0.10"/>'
. '<circle cx="330" cy="180" r="55" fill="#ffffff" opacity="0.08"/>'
. '<circle cx="445" cy="150" r="30" fill="#ffffff" opacity="0.12"/>',
1 => '<g opacity="0.10" fill="#ffffff">'
. '<polygon points="0,225 120,80 260,225"/>'
. '<polygon points="180,225 320,110 460,225"/>'
. '<circle cx="390" cy="60" r="34" opacity="0.7"/>'
. '</g>',
2 => '<g opacity="0.09" stroke="#ffffff" stroke-width="2">'
. str_repeat('<line x1="0" y1="225" x2="480" y2="0" transform="translate(0,0)"/>'
. '<line x1="60" y1="225" x2="480" y2="30"/>'
. '<line x1="120" y1="225" x2="480" y2="60"/>'
. '<line x1="180" y1="225" x2="480" y2="90"/>'
. '<line x1="240" y1="225" x2="480" y2="120"/>', 1)
. '</g>',
3 => '<g fill="#ffffff" opacity="0.10">'
. '<rect x="40" y="30" width="26" height="26" rx="6"/>'
. '<rect x="110" y="140" width="16" height="16" rx="4"/>'
. '<rect x="360" y="60" width="30" height="30" rx="8"/>'
. '<rect x="420" y="170" width="14" height="14" rx="3"/>'
. '<rect x="250" y="180" width="20" height="20" rx="5"/>'
. '</g>',
default => '<polygon points="0,0 480,0 480,90 240,225 0,90" fill="#000000" opacity="0.18"/>'
. '<polygon points="240,0 480,0 480,225" fill="#ffffff" opacity="0.07"/>',
};
$svg = <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="480" height="225" viewBox="0 0 480 225">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="{$c1}"/>
<stop offset="1" stop-color="{$c2}"/>
</linearGradient>
<radialGradient id="v" cx="0.5" cy="0.35" r="0.9">
<stop offset="0.5" stop-color="#000000" stop-opacity="0"/>
<stop offset="1" stop-color="#000000" stop-opacity="0.4"/>
</radialGradient>
</defs>
<rect width="480" height="225" fill="url(#g)"/>
{$shapes}
<rect width="480" height="225" fill="url(#v)"/>
<text x="462" y="212" text-anchor="end" font-family="Arial, Helvetica, sans-serif" font-size="86" font-weight="800" fill="#ffffff" opacity="0.16">{$initials}</text>
</svg>
SVG;
file_put_contents(self::COVERS_DIR . '/' . $slug . '.svg', $svg);
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
/**
* The goal of this file is to allow developers a location
* where they can overwrite core procedural functions and
* replace them with their own. This file is loaded during
* the bootstrap process and is called during the framework's
* execution.
*
* This can be looked at as a `master helper` file that is
* loaded early on, and may also contain additional functions
* that you'd like to use throughout your entire application
*
* @see: https://codeigniter.com/user_guide/extending/common.html
*/
+232
View File
@@ -0,0 +1,232 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* E.g., http://example.com/
*
* This property auto-detects the scheme/host from the incoming request so
* the app keeps working behind dynamic tunnel URLs (e.g. trycloudflare).
* Set app.baseURL in .env to force a fixed URL instead.
*/
public string $baseURL;
public function __construct()
{
parent::__construct();
$forced = (string) env('app.baseURL', '');
if ($forced !== '') {
$this->baseURL = $forced;
return;
}
if (is_cli()) {
$this->baseURL = 'http://localhost:8080/';
return;
}
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$scheme = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https'
? 'https'
: 'http';
$this->baseURL = $scheme . '://' . $host . '/';
}
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
* If you want to accept multiple Hostnames, set this.
*
* E.g.,
* When your site URL ($baseURL) is 'http://example.com/', and your site
* also accepts 'http://media.example.com/' and 'http://accounts.example.com/':
* ['media.example.com', 'accounts.example.com']
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically, this will be your `index.php` file, unless you've renamed it to
* something else. If you have configured your web server to remove this file
* from your site URIs, set this variable to an empty string.
*/
public string $indexPage = 'index.php';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which server global should be used to retrieve the
* URI string. The default setting of 'REQUEST_URI' works for most servers.
* If your links do not seem to work, try one of the other delicious flavors:
*
* 'REQUEST_URI': Uses $_SERVER['REQUEST_URI']
* 'QUERY_STRING': Uses $_SERVER['QUERY_STRING']
* 'PATH_INFO': Uses $_SERVER['PATH_INFO']
*
* WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
public string $uriProtocol = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.
|
| By default, only these are allowed: `a-z 0-9~%.:_-`
|
| Set an empty string to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be used as: '/\A[<permittedURIChars>]+\z/iu'
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
public string $permittedURIChars = 'a-z 0-9~%.:_\-';
/**
* --------------------------------------------------------------------------
* Default Locale
* --------------------------------------------------------------------------
*
* The Locale roughly represents the language and location that your visitor
* is viewing the site from. It affects the language strings and other
* strings (like currency markers, numbers, etc), that your program
* should run under for this request.
*/
public string $defaultLocale = 'en';
/**
* --------------------------------------------------------------------------
* Negotiate Locale
* --------------------------------------------------------------------------
*
* If true, the current Request object will automatically determine the
* language to use based on the value of the Accept-Language header.
*
* If false, no automatic detection will be performed.
*/
public bool $negotiateLocale = false;
/**
* --------------------------------------------------------------------------
* Supported Locales
* --------------------------------------------------------------------------
*
* If $negotiateLocale is true, this array lists the locales supported
* by the application in descending order of priority. If no match is
* found, the first locale will be used.
*
* IncomingRequest::setLocale() also uses this list.
*
* @var list<string>
*/
public array $supportedLocales = ['en'];
/**
* --------------------------------------------------------------------------
* Application Timezone
* --------------------------------------------------------------------------
*
* The default timezone that will be used in your application to display
* dates with the date helper, and can be retrieved through app_timezone()
*
* @see https://www.php.net/manual/en/timezones.php for list of timezones
* supported by PHP.
*/
public string $appTimezone = 'UTC';
/**
* --------------------------------------------------------------------------
* Default Character Set
* --------------------------------------------------------------------------
*
* This determines which character set is used by default in various methods
* that require a character set to be provided.
*
* @see http://php.net/htmlspecialchars for a list of supported charsets.
*/
public string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* Force Global Secure Requests
* --------------------------------------------------------------------------
*
* If true, this will force every request made to this application to be
* made via a secure connection (HTTPS). If the incoming request is not
* secure, the user will be redirected to a secure version of the page
* and the HTTP Strict Transport Security (HSTS) header will be set.
*/
public bool $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
* Reverse Proxy IPs
* --------------------------------------------------------------------------
*
* If your server is behind a reverse proxy, you must whitelist the proxy
* IP addresses from which CodeIgniter should trust headers such as
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
* Content Security Policy
* --------------------------------------------------------------------------
*
* Enables the Response's Content Secure Policy to restrict the sources that
* can be used for images, scripts, CSS files, audio, video, etc. If enabled,
* the Response object will populate default values for the policy from the
* `ContentSecurityPolicy.php` file. Controllers can always add to those
* restrictions at run time.
*
* For a better understanding of CSP, see these documents:
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*/
public bool $CSPEnabled = false;
}
+92
View File
@@ -0,0 +1,92 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTOLOADER CONFIGURATION
* -------------------------------------------------------------------
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*
* NOTE: If you use an identical key in $psr4 or $classmap, then
* the values in this file will overwrite the framework's values.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Autoload extends AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The 'Config' (APPPATH . 'Config') and 'CodeIgniter' (SYSTEMPATH) are
* already mapped for you.
*
* You may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH,
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* Prototype:
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var list<string>
*/
public $helpers = ['gg'];
}
+34
View File
@@ -0,0 +1,34 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. This will control whether Kint is loaded, and a few other
| items. It can always be used within your own application too.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);
+25
View File
@@ -0,0 +1,25 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| Don't show ANY in production environments. Instead, let the system catch
| it and display a generic error message.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL & ~E_DEPRECATED);
// If you want to suppress more types of errors.
// error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
ini_set('display_errors', '0');
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', false);
+38
View File
@@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CURLRequest Share Connection Options
* --------------------------------------------------------------------------
*
* Share connection options between requests.
*
* @var list<int>
*
* @see https://www.php.net/manual/en/curl.constants.php#constant.curl-lock-data-connect
*/
public array $shareConnectionOptions = [
CURL_LOCK_DATA_CONNECT,
CURL_LOCK_DATA_DNS,
];
/**
* --------------------------------------------------------------------------
* CURLRequest Share Options
* --------------------------------------------------------------------------
*
* Whether share options between requests or not.
*
* If true, all the options won't be reset between requests.
* It may cause an error request with unnecessary headers.
*/
public bool $shareOptions = false;
}
+198
View File
@@ -0,0 +1,198 @@
<?php
namespace Config;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Handlers\ApcuHandler;
use CodeIgniter\Cache\Handlers\DummyHandler;
use CodeIgniter\Cache\Handlers\FileHandler;
use CodeIgniter\Cache\Handlers\MemcachedHandler;
use CodeIgniter\Cache\Handlers\PredisHandler;
use CodeIgniter\Cache\Handlers\RedisHandler;
use CodeIgniter\Cache\Handlers\WincacheHandler;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Primary Handler
* --------------------------------------------------------------------------
*
* The name of the preferred handler that should be used. If for some reason
* it is not available, the $backupHandler will be used in its place.
*/
public string $handler = 'file';
/**
* --------------------------------------------------------------------------
* Backup Handler
* --------------------------------------------------------------------------
*
* The name of the handler that will be used in case the first one is
* unreachable. Often, 'file' is used here since the filesystem is
* always available, though that's not always practical for the app.
*/
public string $backupHandler = 'dummy';
/**
* --------------------------------------------------------------------------
* Key Prefix
* --------------------------------------------------------------------------
*
* This string is added to all cache item names to help avoid collisions
* if you run multiple applications with the same cache engine.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Default TTL
* --------------------------------------------------------------------------
*
* The default number of seconds to save items when none is specified.
*
* WARNING: This is not used by framework handlers where 60 seconds is
* hard-coded, but may be useful to projects and modules. This will replace
* the hard-coded value in a future release.
*/
public int $ttl = 60;
/**
* --------------------------------------------------------------------------
* Reserved Characters
* --------------------------------------------------------------------------
*
* A string of reserved characters that will not be allowed in keys or tags.
* Strings that violate this restriction will cause handlers to throw.
* Default: {}()/\@:
*
* NOTE: The default set is required for PSR-6 compliance.
*/
public string $reservedCharacters = '{}()/\@:';
/**
* --------------------------------------------------------------------------
* File settings
* --------------------------------------------------------------------------
*
* Your file storage preferences can be specified below, if you are using
* the File driver.
*
* @var array{storePath?: string, mode?: int}
*/
public array $file = [
'storePath' => WRITEPATH . 'cache/',
'mode' => 0640,
];
/**
* -------------------------------------------------------------------------
* Memcached settings
* -------------------------------------------------------------------------
*
* Your Memcached servers can be specified below, if you are using
* the Memcached drivers.
*
* @see https://codeigniter.com/user_guide/libraries/caching.html#memcached
*
* @var array{host?: string, port?: int, weight?: int, raw?: bool}
*/
public array $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
/**
* -------------------------------------------------------------------------
* Redis settings
* -------------------------------------------------------------------------
*
* Your Redis server can be specified below, if you are using
* the Redis or Predis drivers.
*
* @var array{
* host?: string,
* password?: string|null,
* port?: int,
* timeout?: int,
* async?: bool,
* persistent?: bool,
* database?: int
* }
*/
public array $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'async' => false, // specific to Predis and ignored by the native Redis extension
'persistent' => false,
'database' => 0,
];
/**
* --------------------------------------------------------------------------
* Available Cache Handlers
* --------------------------------------------------------------------------
*
* This is an array of cache engine alias' and class names. Only engines
* that are listed here are allowed to be used.
*
* @var array<string, class-string<CacheInterface>>
*/
public array $validHandlers = [
'apcu' => ApcuHandler::class,
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,
'predis' => PredisHandler::class,
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Include Query String
* --------------------------------------------------------------------------
*
* Whether to take the URL query string into consideration when generating
* output cache files. Valid options are:
*
* false = Disabled
* true = Enabled, take all query parameters into account.
* Please be aware that this may result in numerous cache
* files generated for the same page over and over again.
* ['q'] = Enabled, but only take into account the specified list
* of query parameters.
*
* @var bool|list<string>
*/
public $cacheQueryString = false;
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Status Codes
* --------------------------------------------------------------------------
*
* HTTP status codes that are allowed to be cached. Only responses with
* these status codes will be cached by the PageCache filter.
*
* Default: [] - Cache all status codes (backward compatible)
*
* Recommended: [200] - Only cache successful responses
*
* You can also use status codes like:
* [200, 404, 410] - Cache successful responses and specific error codes
* [200, 201, 202, 203, 204] - All 2xx successful responses
*
* WARNING: Using [] may cache temporary error pages (404, 500, etc).
* Consider restricting to [200] for production applications to avoid
* caching errors that should be temporary.
*
* @var list<int>
*/
public array $cacheStatusCodes = [];
}
+79
View File
@@ -0,0 +1,79 @@
<?php
/*
| --------------------------------------------------------------------
| App Namespace
| --------------------------------------------------------------------
|
| This defines the default Namespace that is used throughout
| CodeIgniter to refer to the Application directory. Change
| this constant to change the namespace that all application
| classes should use.
|
| NOTE: changing this will require manually modifying the
| existing namespaces of App\* namespaced-classes.
*/
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
| --------------------------------------------------------------------------
| Composer Path
| --------------------------------------------------------------------------
|
| The path that Composer's autoload file is expected to live. By default,
| the vendor folder is in the Root directory, but you can customize that here.
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
|
| Provide simple ways to work with the myriad of PHP functions that
| require information to be in seconds.
*/
defined('SECOND') || define('SECOND', 1);
defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
| Exit Status Codes
| --------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code
+216
View File
@@ -0,0 +1,216 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Stores the default settings for the ContentSecurityPolicy, if you
* choose to use it. The values here will be read in and set as defaults
* for the site. If needed, they can be overridden on a page-by-page basis.
*
* Suggested reference for explanations:
*
* @see https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*/
class ContentSecurityPolicy extends BaseConfig
{
// -------------------------------------------------------------------------
// Broadbrush CSP management
// -------------------------------------------------------------------------
/**
* Default CSP report context
*/
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*/
public ?string $reportURI = null;
/**
* Specifies a reporting endpoint to which violation reports ought to be sent.
*/
public ?string $reportTo = null;
/**
* Instructs user agents to rewrite URL schemes, changing
* HTTP to HTTPS. This directive is for websites with
* large numbers of old URLs that need to be rewritten.
*/
public bool $upgradeInsecureRequests = false;
// -------------------------------------------------------------------------
// CSP DIRECTIVES SETTINGS
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to `'self'` if not overridden
*
* @var list<string>|string|null
*/
public $defaultSrc;
/**
* Lists allowed scripts' URLs.
*
* @var list<string>|string
*/
public $scriptSrc = 'self';
/**
* Specifies valid sources for JavaScript <script> elements.
*
* @var list<string>|string
*/
public array|string $scriptSrcElem = 'self';
/**
* Specifies valid sources for JavaScript inline event
* handlers and JavaScript URLs.
*
* @var list<string>|string
*/
public array|string $scriptSrcAttr = 'self';
/**
* Lists allowed stylesheets' URLs.
*
* @var list<string>|string
*/
public $styleSrc = 'self';
/**
* Specifies valid sources for stylesheets <link> elements.
*
* @var list<string>|string
*/
public array|string $styleSrcElem = 'self';
/**
* Specifies valid sources for stylesheets inline
* style attributes and `<style>` elements.
*
* @var list<string>|string
*/
public array|string $styleSrcAttr = 'self';
/**
* Defines the origins from which images can be loaded.
*
* @var list<string>|string
*/
public $imageSrc = 'self';
/**
* Restricts the URLs that can appear in a page's `<base>` element.
*
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $baseURI;
/**
* Lists the URLs for workers and embedded frame contents
*
* @var list<string>|string
*/
public $childSrc = 'self';
/**
* Limits the origins that you can connect to (via XHR,
* WebSockets, and EventSource).
*
* @var list<string>|string
*/
public $connectSrc = 'self';
/**
* Specifies the origins that can serve web fonts.
*
* @var list<string>|string
*/
public $fontSrc;
/**
* Lists valid endpoints for submission from `<form>` tags.
*
* @var list<string>|string
*/
public $formAction = 'self';
/**
* Specifies the sources that can embed the current page.
* This directive applies to `<frame>`, `<iframe>`, `<embed>`,
* and `<applet>` tags. This directive can't be used in
* `<meta>` tags and applies only to non-HTML resources.
*
* @var list<string>|string|null
*/
public $frameAncestors;
/**
* The frame-src directive restricts the URLs which may
* be loaded into nested browsing contexts.
*
* @var list<string>|string|null
*/
public $frameSrc;
/**
* Restricts the origins allowed to deliver video and audio.
*
* @var list<string>|string|null
*/
public $mediaSrc;
/**
* Allows control over Flash and other plugins.
*
* @var list<string>|string
*/
public $objectSrc = 'self';
/**
* @var list<string>|string|null
*/
public $manifestSrc;
/**
* @var list<string>|string
*/
public array|string $workerSrc = [];
/**
* Limits the kinds of plugins a page may invoke.
*
* @var list<string>|string|null
*/
public $pluginTypes;
/**
* List of actions allowed.
*
* @var list<string>|string|null
*/
public $sandbox;
/**
* Nonce placeholder for style tags.
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce placeholder for script tags.
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically?
*/
public bool $autoNonce = true;
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use DateTimeInterface;
class Cookie extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Expires Timestamp
* --------------------------------------------------------------------------
*
* Default expires timestamp for cookies. Setting this to `0` will mean the
* cookie will not have the `Expires` attribute and will behave as a session
* cookie.
*
* @var DateTimeInterface|int|string
*/
public $expires = 0;
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*/
public string $path = '/';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*/
public string $domain = '';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*/
public bool $secure = false;
/**
* --------------------------------------------------------------------------
* Cookie HTTPOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*/
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
* Cookie SameSite
* --------------------------------------------------------------------------
*
* Configure cookie SameSite setting. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Alternatively, you can use the constant names:
* - `Cookie::SAMESITE_NONE`
* - `Cookie::SAMESITE_LAX`
* - `Cookie::SAMESITE_STRICT`
*
* Defaults to `Lax` for compatibility with modern browsers. Setting `''`
* (empty string) means default SameSite attribute set by browsers (`Lax`)
* will be set on cookies. If set to `None`, `$secure` must also be set.
*
* @var ''|'Lax'|'None'|'Strict'
*/
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
* Cookie Raw
* --------------------------------------------------------------------------
*
* This flag allows setting a "raw" cookie, i.e., its name and value are
* not URL encoded using `rawurlencode()`.
*
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
public bool $raw = false;
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Cross-Origin Resource Sharing (CORS) Configuration
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/
class Cors extends BaseConfig
{
/**
* The default CORS configuration.
*
* @var array{
* allowedOrigins: list<string>,
* allowedOriginsPatterns: list<string>,
* supportsCredentials: bool,
* allowedHeaders: list<string>,
* exposedHeaders: list<string>,
* allowedMethods: list<string>,
* maxAge: int,
* }
*/
public array $default = [
/**
* Origins for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* E.g.:
* - ['http://localhost:8080']
* - ['https://www.example.com']
*/
'allowedOrigins' => [],
/**
* Origin regex patterns for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* NOTE: A pattern specified here is part of a regular expression. It will
* be actually `#\A<pattern>\z#`.
*
* E.g.:
* - ['https://\w+\.example\.com']
*/
'allowedOriginsPatterns' => [],
/**
* Weather to send the `Access-Control-Allow-Credentials` header.
*
* The Access-Control-Allow-Credentials response header tells browsers whether
* the server allows cross-origin HTTP requests to include credentials.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
*/
'supportsCredentials' => false,
/**
* Set headers to allow.
*
* The Access-Control-Allow-Headers response header is used in response to
* a preflight request which includes the Access-Control-Request-Headers to
* indicate which HTTP headers can be used during the actual request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
*/
'allowedHeaders' => [],
/**
* Set headers to expose.
*
* The Access-Control-Expose-Headers response header allows a server to
* indicate which response headers should be made available to scripts running
* in the browser, in response to a cross-origin request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
*/
'exposedHeaders' => [],
/**
* Set methods to allow.
*
* The Access-Control-Allow-Methods response header specifies one or more
* methods allowed when accessing a resource in response to a preflight
* request.
*
* E.g.:
* - ['GET', 'POST', 'PUT', 'DELETE']
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
*/
'allowedMethods' => [],
/**
* Set how many seconds the results of a preflight request can be cached.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
*/
'maxAge' => 7200,
];
}
+204
View File
@@ -0,0 +1,204 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
/**
* Database Configuration
*/
class Database extends Config
{
/**
* The directory that holds the Migrations and Seeds directories.
*/
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to use if no other is specified.
*/
public string $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array<string, mixed>
*/
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
'foundRows' => false,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
// /**
// * Sample database connection for SQLite3.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'database' => 'database.db',
// 'DBDriver' => 'SQLite3',
// 'DBPrefix' => '',
// 'DBDebug' => true,
// 'swapPre' => '',
// 'failover' => [],
// 'foreignKeys' => true,
// 'busyTimeout' => 1000,
// 'synchronous' => null,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for Postgre.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'public',
// 'DBDriver' => 'Postgre',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'failover' => [],
// 'port' => 5432,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for SQLSRV.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'dbo',
// 'DBDriver' => 'SQLSRV',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'encrypt' => false,
// 'failover' => [],
// 'port' => 1433,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for OCI8.
// *
// * You may need the following environment variables:
// * NLS_LANG = 'AMERICAN_AMERICA.UTF8'
// * NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => 'localhost:1521/FREEPDB1',
// 'username' => 'root',
// 'password' => 'root',
// 'DBDriver' => 'OCI8',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'AL32UTF8',
// 'swapPre' => '',
// 'failover' => [],
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
/**
* This database connection is used when running PHPUnit database tests.
*
* @var array<string, mixed>
*/
public array $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => true,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
'synchronous' => null,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
public function __construct()
{
parent::__construct();
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Config;
class DocTypes
{
/**
* List of valid document types.
*
* @var array<string, string>
*/
public array $list = [
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">',
];
/**
* Whether to remove the solidus (`/`) character for void HTML elements (e.g. `<input>`)
* for HTML5 compatibility.
*
* Set to:
* `true` - to be HTML5 compatible
* `false` - to be XHTML compatible
*/
public bool $html5 = true;
}
+126
View File
@@ -0,0 +1,126 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '';
public string $fromName = '';
public string $recipients = '';
/**
* The "user agent"
*/
public string $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*/
public string $protocol = 'mail';
/**
* The server path to Sendmail.
*/
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Hostname
*/
public string $SMTPHost = '';
/**
* Which SMTP authentication method to use: login, plain
*/
public string $SMTPAuthMethod = 'login';
/**
* SMTP Username
*/
public string $SMTPUser = '';
/**
* SMTP Password
*/
public string $SMTPPass = '';
/**
* SMTP Port
*/
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*/
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption.
*
* @var string '', 'tls' or 'ssl'. 'tls' will issue a STARTTLS command
* to the server. 'ssl' means implicit SSL. Connection on port
* 465 should set this to ''.
*/
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*/
public bool $wordWrap = true;
/**
* Character count to wrap at
*/
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*/
public string $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*/
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*/
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*/
public int $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*/
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*/
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*/
public bool $DSN = false;
}
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Encryption configuration.
*
* These are the settings used for encryption, if you don't pass a parameter
* array to the encrypter for creation/initialization.
*/
class Encryption extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Encryption Key Starter
* --------------------------------------------------------------------------
*
* If you use the Encryption class you must set an encryption key (seed).
* You need to ensure it is long enough for the cipher and mode you plan to use.
* See the user guide for more info.
*/
public string $key = '';
/**
* --------------------------------------------------------------------------
* Previous Encryption Keys
* --------------------------------------------------------------------------
*
* When rotating encryption keys, add old keys here to maintain ability
* to decrypt data encrypted with previous keys. Encryption always uses
* the current $key. Decryption tries current key first, then falls back
* to previous keys if decryption fails.
*
* In .env file, use comma-separated string:
* encryption.previousKeys = hex2bin:9be8c64fcea509867...,hex2bin:3f5a1d8e9c2b7a4f6...
*
* @var list<string>|string
*/
public array|string $previousKeys = '';
/**
* --------------------------------------------------------------------------
* Encryption Driver to Use
* --------------------------------------------------------------------------
*
* One of the supported encryption drivers.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
* SodiumHandler's Padding Length in Bytes
* --------------------------------------------------------------------------
*
* This is the number of bytes that will be padded to the plaintext message
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*/
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
* Encryption digest
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*/
public string $digest = 'SHA512';
/**
* Whether the cipher-text should be raw. If set to false, then it will be base64 encoded.
* This setting is only used by OpenSSLHandler.
*
* Set to false for CI3 Encryption compatibility.
*/
public bool $rawData = true;
/**
* Encryption key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'encryption' for CI3 Encryption compatibility.
*/
public string $encryptKeyInfo = '';
/**
* Authentication key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'authentication' for CI3 Encryption compatibility.
*/
public string $authKeyInfo = '';
/**
* Cipher to use.
* This setting is only used by OpenSSLHandler.
*
* Set to 'AES-128-CBC' to decrypt encrypted data that encrypted
* by CI3 Encryption default configuration.
*/
public string $cipher = 'AES-256-CTR';
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
Events::on('pre_system', static function (): void {
if (ENVIRONMENT !== 'testing') {
$value = ini_get('zlib.output_compression');
if (filter_var($value, FILTER_VALIDATE_BOOLEAN) || (int) $value > 0) {
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
service('toolbar')->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
service('routes')->get('__hot-reload', static function (): void {
(new HotReloader())->run();
});
}
}
});
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
/**
* Setup how the exception handler works.
*/
class Exceptions extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* LOG EXCEPTIONS?
* --------------------------------------------------------------------------
* If true, then exceptions will be logged
* through Services::Log.
*
* Default: true
*/
public bool $log = true;
/**
* --------------------------------------------------------------------------
* DO NOT LOG STATUS CODES
* --------------------------------------------------------------------------
* Any status codes here will NOT be logged if logging is turned on.
* By default, only 404 (Page Not Found) exceptions are ignored.
*
* @var list<int>
*/
public array $ignoreCodes = [404];
/**
* --------------------------------------------------------------------------
* Error Views Path
* --------------------------------------------------------------------------
* This is the path to the directory that contains the 'cli' and 'html'
* directories that hold the views used to generate errors.
*
* Default: APPPATH.'Views/errors'
*/
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
* HIDE FROM DEBUG TRACE
* --------------------------------------------------------------------------
* Any data that you would like to hide from the debug trace.
* In order to specify 2 levels, use "/" to separate.
* ex. ['server', 'setup/password', 'secret_token']
*
* @var list<string>
*/
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* WHETHER TO THROW AN EXCEPTION ON DEPRECATED ERRORS
* --------------------------------------------------------------------------
* If set to `true`, DEPRECATED errors are only logged and no exceptions are
* thrown. This option also works for user deprecations.
*/
public bool $logDeprecations = true;
/**
* --------------------------------------------------------------------------
* LOG LEVEL THRESHOLD FOR DEPRECATIONS
* --------------------------------------------------------------------------
* If `$logDeprecations` is set to `true`, this sets the log level
* to which the deprecation will be logged. This should be one of the log
* levels recognized by PSR-3.
*
* The related `Config\Logger::$threshold` should be adjusted, if needed,
* to capture logging the deprecations.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
/*
* DEFINE THE HANDLERS USED
* --------------------------------------------------------------------------
* Given the HTTP status code, returns exception handler that
* should be used to deal with this error. By default, it will run CodeIgniter's
* default handler and display the error information in the expected format
* for CLI, HTTP, or AJAX requests, as determined by is_cli() and the expected
* response format.
*
* Custom handlers can be returned if you want to handle one or more specific
* error codes yourself like:
*
* if (in_array($statusCode, [400, 404, 500])) {
* return new \App\Libraries\MyExceptionHandler();
* }
* if ($exception instanceOf PageNotFoundException) {
* return new \App\Libraries\MyExceptionHandler();
* }
*/
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Use improved new auto routing instead of the legacy version.
*/
public bool $autoRoutesImproved = true;
/**
* Use filter execution order in 4.4 or before.
*/
public bool $oldFilterOrder = false;
/**
* The behavior of `limit(0)` in Query Builder.
*
* If true, `limit(0)` returns all records. (the behavior of 4.4.x or before in version 4.x.)
* If false, `limit(0)` returns no records. (the behavior of 3.1.9 or later in version 3.x.)
*/
public bool $limitZeroAsAll = true;
/**
* Use strict location negotiation.
*
* By default, the locale is selected based on a loose comparison of the language code (ISO 639-1)
* Enabling strict comparison will also consider the region code (ISO 3166-1 alpha-2).
*/
public bool $strictLocaleNegotiation = false;
}
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace Config;
use CodeIgniter\Config\Filters as BaseFilters;
use CodeIgniter\Filters\Cors;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\ForceHTTPS;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\PageCache;
use CodeIgniter\Filters\PerformanceMetrics;
use CodeIgniter\Filters\SecureHeaders;
class Filters extends BaseFilters
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, class-string|list<class-string>>
*
* [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
];
/**
* List of special required filters.
*
* The filters listed here are special. They are applied before and after
* other kinds of filters, and always applied even if a route does not exist.
*
* Filters set by default provide framework functionality. If removed,
* those functions will no longer work.
*
* @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps', // Force Global Secure Requests
'pagecache', // Web Page Caching
],
'after' => [
'pagecache', // Web Page Caching
'performance', // Performance Metrics
'toolbar', // Debug Toolbar
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array{
* before: array<string, array{except: list<string>|string}>|list<string>,
* after: array<string, array{except: list<string>|string}>|list<string>
* }
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'POST' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [];
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Available Response Formats
* --------------------------------------------------------------------------
*
* When you perform content negotiation with the request, these are the
* available formats that your application supports. This is currently
* only used with the API\ResponseTrait. A valid Formatter must exist
* for the specified format.
*
* These formats are only checked when the data passed to the respond()
* method is an array.
*
* @var list<string>
*/
public array $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
];
/**
* --------------------------------------------------------------------------
* Formatters
* --------------------------------------------------------------------------
*
* Lists the class to use to format responses with of a particular type.
* For each mime type, list the class that should be used. Formatters
* can be retrieved through the getFormatter() method.
*
* @var array<string, string>
*/
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
* --------------------------------------------------------------------------
* Formatters Options
* --------------------------------------------------------------------------
*
* Additional Options to adjust default formatters behaviour.
* For each mime type, list the additional options that should be used.
*
* @var array<string, int>
*/
public array $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,
];
/**
* --------------------------------------------------------------------------
* Maximum depth for JSON encoding.
* --------------------------------------------------------------------------
*
* This value determines how deep the JSON encoder will traverse nested structures.
*/
public int $jsonEncodeDepth = 512;
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Generators extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Generator Commands' Views
* --------------------------------------------------------------------------
*
* This array defines the mapping of generator commands to the view files
* they are using. If you need to customize them for your own, copy these
* view files in your own folder and indicate the location here.
*
* You will notice that the views have special placeholders enclosed in
* curly braces `{...}`. These placeholders are used internally by the
* generator commands in processing replacements, thus you are warned
* not to delete them or modify the names. If you will do so, you may
* end up disrupting the scaffolding process and throw errors.
*
* YOU HAVE BEEN WARNED!
*
* @var array<string, array<string, string>|string>
*/
public array $views = [
'make:cell' => [
'class' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
],
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
'make:entity' => 'CodeIgniter\Commands\Generators\Views\entity.tpl.php',
'make:filter' => 'CodeIgniter\Commands\Generators\Views\filter.tpl.php',
'make:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
'make:model' => 'CodeIgniter\Commands\Generators\Views\model.tpl.php',
'make:seeder' => 'CodeIgniter\Commands\Generators\Views\seeder.tpl.php',
'make:validation' => 'CodeIgniter\Commands\Generators\Views\validation.tpl.php',
'session:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
];
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*/
public bool $hidden = true;
/**
* Honeypot Label Content
*/
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*/
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*/
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* If you enabled CSP, you can remove `style="display:none"`.
*/
public string $container = '<div style="display:none">{template}</div>';
/**
* The id attribute for Honeypot container tag
*
* Used when CSP is enabled.
*/
public string $containerId = 'hpc';
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace Config;
class Hostnames
{
// List of known two-part TLDs for subdomain extraction
public const TWO_PART_TLDS = [
'co.uk', 'org.uk', 'gov.uk', 'ac.uk', 'sch.uk', 'ltd.uk', 'plc.uk',
'com.au', 'net.au', 'org.au', 'edu.au', 'gov.au', 'asn.au', 'id.au',
'co.jp', 'ac.jp', 'go.jp', 'or.jp', 'ne.jp', 'gr.jp',
'co.nz', 'org.nz', 'govt.nz', 'ac.nz', 'net.nz', 'geek.nz', 'maori.nz', 'school.nz',
'co.in', 'net.in', 'org.in', 'ind.in', 'ac.in', 'gov.in', 'res.in',
'com.cn', 'net.cn', 'org.cn', 'gov.cn', 'edu.cn',
'com.sg', 'net.sg', 'org.sg', 'gov.sg', 'edu.sg', 'per.sg',
'co.za', 'org.za', 'gov.za', 'ac.za', 'net.za',
'co.kr', 'or.kr', 'go.kr', 'ac.kr', 'ne.kr', 'pe.kr',
'co.th', 'or.th', 'go.th', 'ac.th', 'net.th', 'in.th',
'com.my', 'net.my', 'org.my', 'edu.my', 'gov.my', 'mil.my', 'name.my',
'com.mx', 'org.mx', 'net.mx', 'edu.mx', 'gob.mx',
'com.br', 'net.br', 'org.br', 'gov.br', 'edu.br', 'art.br', 'eng.br',
'co.il', 'org.il', 'ac.il', 'gov.il', 'net.il', 'muni.il',
'co.id', 'or.id', 'ac.id', 'go.id', 'net.id', 'web.id', 'my.id',
'com.hk', 'edu.hk', 'gov.hk', 'idv.hk', 'net.hk', 'org.hk',
'com.tw', 'net.tw', 'org.tw', 'edu.tw', 'gov.tw', 'idv.tw',
'com.sa', 'net.sa', 'org.sa', 'gov.sa', 'edu.sa', 'sch.sa', 'med.sa',
'co.ae', 'net.ae', 'org.ae', 'gov.ae', 'ac.ae', 'sch.ae',
'com.tr', 'net.tr', 'org.tr', 'gov.tr', 'edu.tr', 'av.tr', 'gen.tr',
'co.ke', 'or.ke', 'go.ke', 'ac.ke', 'sc.ke', 'me.ke', 'mobi.ke', 'info.ke',
'com.ng', 'org.ng', 'gov.ng', 'edu.ng', 'net.ng', 'sch.ng', 'name.ng',
'com.pk', 'net.pk', 'org.pk', 'gov.pk', 'edu.pk', 'fam.pk',
'com.eg', 'edu.eg', 'gov.eg', 'org.eg', 'net.eg',
'com.cy', 'net.cy', 'org.cy', 'gov.cy', 'ac.cy',
'com.lk', 'org.lk', 'edu.lk', 'gov.lk', 'net.lk', 'int.lk',
'com.bd', 'net.bd', 'org.bd', 'ac.bd', 'gov.bd', 'mil.bd',
'com.ar', 'net.ar', 'org.ar', 'gov.ar', 'edu.ar', 'mil.ar',
'gob.cl', 'com.pl', 'net.pl', 'org.pl', 'gov.pl', 'edu.pl',
'co.ir', 'ac.ir', 'org.ir', 'id.ir', 'gov.ir', 'sch.ir', 'net.ir',
];
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Images\Handlers\GDHandler;
use CodeIgniter\Images\Handlers\ImageMagickHandler;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*/
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*
* @deprecated 4.7.0 No longer used.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Config;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
* Kint
* --------------------------------------------------------------------------
*
* We use Kint's `RichRenderer` and `CLIRenderer`. This area contains options
* that you can set to customize how Kint works for you.
*
* @see https://kint-php.github.io/kint/ for details on these settings.
*/
class Kint
{
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}
+151
View File
@@ -0,0 +1,151 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
use CodeIgniter\Log\Handlers\HandlerInterface;
class Logger extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Error Logging Threshold
* --------------------------------------------------------------------------
*
* You can enable error logging by setting a threshold over zero. The
* threshold determines what gets logged. Any values below or equal to the
* threshold will be logged.
*
* Threshold options are:
*
* - 0 = Disables logging, Error logging TURNED OFF
* - 1 = Emergency Messages - System is unusable
* - 2 = Alert Messages - Action Must Be Taken Immediately
* - 3 = Critical Messages - Application component unavailable, unexpected exception.
* - 4 = Runtime Errors - Don't need immediate action, but should be monitored.
* - 5 = Warnings - Exceptional occurrences that are not errors.
* - 6 = Notices - Normal but significant events.
* - 7 = Info - Interesting events, like user logging in, etc.
* - 8 = Debug - Detailed debug information.
* - 9 = All Messages
*
* You can also pass an array with threshold levels to show individual error types
*
* array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages
*
* For a live site you'll usually enable Critical or higher (3) to be logged otherwise
* your log files will fill up very fast.
*
* @var int|list<int>
*/
public $threshold = (ENVIRONMENT === 'production') ? 4 : 9;
/**
* --------------------------------------------------------------------------
* Date Format for Logs
* --------------------------------------------------------------------------
*
* Each item that is logged has an associated date. You can use PHP date
* codes to set your own date formatting
*/
public string $dateFormat = 'Y-m-d H:i:s';
/**
* --------------------------------------------------------------------------
* Log Handlers
* --------------------------------------------------------------------------
*
* The logging system supports multiple actions to be taken when something
* is logged. This is done by allowing for multiple Handlers, special classes
* designed to write the log to their chosen destinations, whether that is
* a file on the getServer, a cloud-based service, or even taking actions such
* as emailing the dev team.
*
* Each handler is defined by the class name used for that handler, and it
* MUST implement the `CodeIgniter\Log\Handlers\HandlerInterface` interface.
*
* The value of each key is an array of configuration items that are sent
* to the constructor of each handler. The only required configuration item
* is the 'handles' element, which must be an array of integer log levels.
* This is most easily handled by using the constants defined in the
* `Psr\Log\LogLevel` class.
*
* Handlers are executed in the order defined in this array, starting with
* the handler on top and continuing down.
*
* @var array<class-string<HandlerInterface>, array<string, int|list<string>|string>>
*/
public array $handlers = [
/*
* --------------------------------------------------------------------
* File Handler
* --------------------------------------------------------------------
*/
FileHandler::class => [
// The log levels that this handler will handle.
'handles' => [
'critical',
'alert',
'emergency',
'debug',
'error',
'info',
'notice',
'warning',
],
/*
* The default filename extension for log files.
* An extension of 'php' allows for protecting the log files via basic
* scripting, when they are to be stored under a publicly accessible directory.
*
* NOTE: Leaving it blank will default to 'log'.
*/
'fileExtension' => '',
/*
* The file system permissions to be applied on newly created log files.
*
* IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
* integer notation (i.e. 0700, 0644, etc.)
*/
'filePermissions' => 0644,
/*
* Logging Directory Path
*
* By default, logs are written to WRITEPATH . 'logs/'
* Specify a different destination here, if desired.
*/
'path' => '',
],
/*
* The ChromeLoggerHandler requires the use of the Chrome web browser
* and the ChromeLogger extension. Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ],
/*
* The ErrorlogHandler writes the logs to PHP's native `error_log()` function.
* Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /* The log levels this handler can handle. */
// 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
//
// /*
// * The message type where the error should go. Can be 0 or 4, or use the
// * class constants: `ErrorlogHandler::TYPE_OS` (0) or `ErrorlogHandler::TYPE_SAPI` (4)
// */
// 'messageType' => 0,
// ],
];
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Migrations extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Enable/Disable Migrations
* --------------------------------------------------------------------------
*
* Migrations are enabled by default.
*
* You should enable migrations whenever you intend to do a schema migration
* and disable it back when you're done.
*/
public bool $enabled = true;
/**
* --------------------------------------------------------------------------
* Migrations Table
* --------------------------------------------------------------------------
*
* This is the name of the table that will store the current migrations state.
* When migrations runs it will store in a database table which migration
* files have already been run.
*/
public string $table = 'migrations';
/**
* --------------------------------------------------------------------------
* Timestamp Format
* --------------------------------------------------------------------------
*
* This is the format that will be used when creating new migrations
* using the CLI command:
* > php spark make:migration
*
* NOTE: if you set an unsupported format, migration runner will not find
* your migration files.
*
* Supported formats:
* - YmdHis_
* - Y-m-d-His_
* - Y_m_d_His_
*/
public string $timestampFormat = 'Y-m-d-His_';
/**
* --------------------------------------------------------------------------
* Enable/Disable Migration Lock
* --------------------------------------------------------------------------
*
* Locking is disabled by default.
*
* When enabled, it will prevent multiple migration processes
* from running at the same time by using a lock mechanism.
*
* This is useful in production environments to avoid conflicts
* or race conditions during concurrent deployments.
*/
public bool $lock = false;
}
+534
View File
@@ -0,0 +1,534 @@
<?php
namespace Config;
/**
* This file contains an array of mime types. It is used by the
* Upload class to help identify allowed file types.
*
* When more than one variation for an extension exist (like jpg, jpeg, etc)
* the most common one should be first in the array to aid the guess*
* methods. The same applies when more than one mime-type exists for a
* single extension.
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array<string, list<string>|string>
*/
public static array $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
'application/x-binhex40',
'application/x-mac-binhex40',
],
'cpt' => 'application/mac-compactpro',
'csv' => [
'text/csv',
'text/x-comma-separated-values',
'text/comma-separated-values',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain',
],
'bin' => [
'application/macbinary',
'application/mac-binary',
'application/octet-stream',
'application/x-binary',
'application/x-macbinary',
],
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/vnd.microsoft.portable-executable',
'application/x-dosexec',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
'psd' => [
'application/x-photoshop',
'image/vnd.adobe.photoshop',
],
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => [
'application/pdf',
'application/force-download',
'application/x-download',
],
'ai' => [
'application/pdf',
'application/postscript',
],
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => [
'application/vnd.ms-excel',
'application/msexcel',
'application/x-msexcel',
'application/x-ms-excel',
'application/x-excel',
'application/x-dos_ms_excel',
'application/xls',
'application/x-xls',
'application/excel',
'application/download',
'application/vnd.ms-office',
'application/msword',
],
'ppt' => [
'application/vnd.ms-powerpoint',
'application/powerpoint',
'application/vnd.ms-office',
'application/msword',
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => [
'application/x-php',
'application/x-httpd-php',
'application/php',
'text/php',
'text/x-php',
'application/x-httpd-php-source',
],
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => [
'application/x-javascript',
'text/plain',
],
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => [
'application/x-tar',
'application/x-gzip-compressed',
],
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => [
'application/x-zip',
'application/zip',
'application/x-zip-compressed',
'application/s-compressed',
'multipart/x-zip',
],
'rar' => [
'application/vnd.rar',
'application/x-rar',
'application/rar',
'application/x-rar-compressed',
],
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => [
'audio/mpeg',
'audio/mpg',
'audio/mpeg3',
'audio/mp3',
],
'aif' => [
'audio/x-aiff',
'audio/aiff',
],
'aiff' => [
'audio/x-aiff',
'audio/aiff',
],
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => [
'audio/x-wav',
'audio/wave',
'audio/wav',
],
'bmp' => [
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/x-xbitmap',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/ms-bmp',
'image/x-ms-bmp',
'application/bmp',
'application/x-bmp',
'application/x-win-bitmap',
],
'gif' => 'image/gif',
'jpg' => [
'image/jpeg',
'image/pjpeg',
],
'jpeg' => [
'image/jpeg',
'image/pjpeg',
],
'jpe' => [
'image/jpeg',
'image/pjpeg',
],
'jp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'j2k' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpf' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpg2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpx' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpm' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mj2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mjp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'png' => [
'image/png',
'image/x-png',
],
'webp' => 'image/webp',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
'text/css',
'text/plain',
],
'html' => [
'text/html',
'text/plain',
],
'htm' => [
'text/html',
'text/plain',
],
'shtml' => [
'text/html',
'text/plain',
],
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => [
'text/plain',
'text/x-log',
],
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => [
'application/xml',
'text/xml',
'text/plain',
],
'xsl' => [
'application/xml',
'text/xsl',
'text/xml',
],
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => [
'video/x-msvideo',
'video/msvideo',
'video/avi',
'application/x-troff-msvideo',
],
'movie' => 'video/x-sgi-movie',
'doc' => [
'application/msword',
'application/vnd.ms-office',
],
'docx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
'application/x-zip',
],
'dot' => [
'application/msword',
'application/vnd.ms-office',
],
'dotx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
],
'xlsx' => [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/vnd.ms-excel',
'application/msword',
'application/x-zip',
],
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'word' => [
'application/msword',
'application/octet-stream',
],
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => [
'application/json',
'text/json',
],
'pem' => [
'application/x-x509-user-cert',
'application/x-pem-file',
'application/octet-stream',
],
'p10' => [
'application/x-pkcs10',
'application/pkcs10',
],
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7m' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => [
'application/x-x509-ca-cert',
'application/x-x509-user-cert',
'application/pkix-cert',
],
'crl' => [
'application/pkix-crl',
'application/pkcs-crl',
],
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => [
'application/pkix-cert',
'application/x-x509-ca-cert',
],
'3g2' => 'video/3gpp2',
'3gp' => [
'video/3gp',
'video/3gpp',
],
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => [
'video/mp4',
'video/x-f4v',
],
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => [
'video/x-ms-wmv',
'video/x-ms-asf',
],
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => [
'audio/ogg',
'video/ogg',
'application/ogg',
],
'kmz' => [
'application/vnd.google-earth.kmz',
'application/zip',
'application/x-zip',
],
'kml' => [
'application/vnd.google-earth.kml+xml',
'application/xml',
'text/xml',
],
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => [
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
],
'cdr' => [
'application/cdr',
'application/coreldraw',
'application/x-cdr',
'application/x-coreldraw',
'image/cdr',
'image/x-cdr',
'zz-application/zz-winassoc-cdr',
],
'wma' => [
'audio/x-ms-wma',
'video/x-ms-asf',
],
'jar' => [
'application/java-archive',
'application/x-java-application',
'application/x-jar',
'application/x-compressed',
],
'svg' => [
'image/svg+xml',
'image/svg',
'application/xml',
'text/xml',
],
'vcf' => 'text/x-vcard',
'srt' => [
'text/srt',
'text/plain',
],
'vtt' => [
'text/vtt',
'text/plain',
],
'ico' => [
'image/x-icon',
'image/x-ico',
'image/vnd.microsoft.icon',
],
'stl' => [
'application/sla',
'application/vnd.ms-pki.stl',
'application/x-navistyle',
'model/stl',
'application/octet-stream',
],
];
/**
* Attempts to determine the best mime type for the given file extension.
*
* @return string|null The mime type found, or none if unable to determine.
*/
public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes)) {
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
}
/**
* Attempts to determine the best file extension for a given mime type.
*
* @param string|null $proposedExtension - default extension (in case there is more than one with the same mime type)
*
* @return string|null The extension determined, or null if unable to match.
*/
public static function guessExtensionFromType(string $type, ?string $proposedExtension = null)
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if (
$proposedExtension !== ''
&& array_key_exists($proposedExtension, static::$mimes)
&& in_array($type, (array) static::$mimes[$proposedExtension], true)
) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// Reverse check the mime type list if no extension was proposed.
// This search is order sensitive!
foreach (static::$mimes as $ext => $types) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}
return null;
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Modules extends BaseModules
{
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all elements listed in
* $aliases below. If false, no auto-discovery will happen at all,
* giving a slight performance boost.
*
* @var bool
*/
public $enabled = true;
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery Within Composer Packages?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all namespaces loaded
* by Composer, as well as the namespaces configured locally.
*
* @var bool
*/
public $discoverInComposer = true;
/**
* The Composer package list for Auto-Discovery
* This setting is optional.
*
* E.g.:
* [
* 'only' => [
* // List up all packages to auto-discover
* 'codeigniter4/shield',
* ],
* ]
* or
* [
* 'exclude' => [
* // List up packages to exclude.
* 'pestphp/pest',
* ],
* ]
*
* @var array{only?: list<string>, exclude?: list<string>}
*/
public $composerPackages = [];
/**
* --------------------------------------------------------------------------
* Auto-Discovery Rules
* --------------------------------------------------------------------------
*
* Aliases list of all discovery classes that will be active and used during
* the current application request.
*
* If it is not listed, only the base application elements will be used.
*
* @var list<string>
*/
public $aliases = [
'events',
'filters',
'registrars',
'routes',
'services',
];
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Config;
/**
* Optimization Configuration.
*
* NOTE: This class does not extend BaseConfig for performance reasons.
* So you cannot replace the property values with Environment Variables.
*
* WARNING: Do not use these options when running the app in the Worker Mode.
*/
class Optimize
{
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/factories.html#config-caching
*/
public bool $configCacheEnabled = false;
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/autoloader.html#file-locator-caching
*/
public bool $locatorCacheEnabled = false;
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Pager extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Templates
* --------------------------------------------------------------------------
*
* Pagination links are rendered out using views to configure their
* appearance. This array contains aliases and the view names to
* use when rendering the links.
*
* Within each view, the Pager object will be available as $pager,
* and the desired group as $pagerGroup;
*
* @var array<string, string>
*/
public array $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
];
/**
* --------------------------------------------------------------------------
* Items Per Page
* --------------------------------------------------------------------------
*
* The default number of results shown in a single page.
*/
public int $perPage = 20;
}
+90
View File
@@ -0,0 +1,90 @@
<?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
*
* Modifying these allows you to restructure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Paths
{
/**
* ---------------------------------------------------------------
* SYSTEM FOLDER NAME
* ---------------------------------------------------------------
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*/
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/**
* ---------------------------------------------------------------
* APPLICATION FOLDER NAME
* ---------------------------------------------------------------
*
* If you want this front controller to use a different "app"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path.
*
* @see http://codeigniter.com/user_guide/general/managing_apps.html
*/
public string $appDirectory = __DIR__ . '/..';
/**
* ---------------------------------------------------------------
* WRITABLE DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "writable" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*/
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* ---------------------------------------------------------------
* VIEW DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory that
* contains the view files used by your application. By
* default this is in `app/Views`. This value
* is used when no value is provided to `Services::renderer()`.
*/
public string $viewDirectory = __DIR__ . '/../Views';
/**
* ---------------------------------------------------------------
* ENVIRONMENT DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory where
* the .env file is located.
* Please consider security implications when changing this
* value - the directory should not be publicly accessible.
*/
public string $envDirectory = __DIR__ . '/../../';
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace Config;
use CodeIgniter\Config\Publisher as BasePublisher;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BasePublisher
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(s?css|js|map|html?|xml|json|webmanifest|ttf|eot|woff2?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
}
+33
View File
@@ -0,0 +1,33 @@
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
$routes->get('/', 'Home::index');
$routes->get('deals', 'Home::feedOnly');
$routes->get('deals/(:segment)', 'Home::preset/$1');
$routes->get('game/(:segment)', 'Game::show/$1');
$routes->get('stores', 'Stores::index');
$routes->get('rankings', 'Rankings::index');
$routes->get('vouchers', 'Vouchers::index');
$routes->get('vouchers/(:segment)', 'Vouchers::store/$1');
$routes->get('news', 'News::index');
$routes->get('news/(:segment)', 'News::index/$1');
$routes->get('article/(:segment)', 'News::article/$1');
$routes->get('deal/(:segment)', 'News::article/$1');
$routes->get('freebie/(:segment)', 'News::article/$1');
$routes->get('giveaway/(:segment)', 'News::article/$1');
$routes->get('games', 'Games::index');
$routes->get('games/(:segment)', 'Games::index/$1');
$routes->get('prepaids', 'Prepaids::index');
$routes->get('wishlist', 'Wishlist::index');
$routes->get('api/wishlist', 'Wishlist::data');
$routes->get('franchises', 'Franchise::all');
$routes->get('franchise/(:segment)', 'Franchise::index/$1');
$routes->get('bundle/(:segment)', 'Bundle::index/$1');
$routes->get('api/suggest', 'Api::suggest');
$routes->get('api/prices', 'Api::prices');
$routes->get('api', 'Api::docs');
$routes->get('faq', 'Pages::faq');
$routes->get('page/(:segment)', 'Pages::tutorial/$1');
$routes->get('subscriptions', 'Subscriptions::index');
+149
View File
@@ -0,0 +1,149 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Config\Routing as BaseRouting;
/**
* Routing configuration
*/
class Routing extends BaseRouting
{
/**
* For Defined Routes.
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*
* @var list<string>
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* For Defined Routes and Auto Routing.
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* For Auto Routing.
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* For Defined Routes and Auto Routing.
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* For Auto Routing.
* Whether to translate dashes in URIs for controller/method to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be the controller/method name like: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* If TRUE, the system will look for attributes on controller
* class and methods that can run before and after the
* controller/method.
*
* If FALSE, will ignore any attributes.
*/
public bool $useControllerAttributes = true;
/**
* For Defined Routes.
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* For Defined Routes.
* If TRUE, matched multiple URI segments will be passed as one parameter.
*
* Default: false
*/
public bool $multipleSegmentsOneParam = false;
/**
* For Auto Routing (Improved).
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array<string, string>
*/
public array $moduleRoutes = [];
/**
* For Auto Routing (Improved).
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*
* If you enable this, $translateURIDashes is ignored.
*
* Default: false
*/
public bool $translateUriToCamelCase = true;
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Security extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CSRF Protection Method
* --------------------------------------------------------------------------
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*/
public string $csrfProtection = 'cookie';
/**
* --------------------------------------------------------------------------
* CSRF Token Randomization
* --------------------------------------------------------------------------
*
* Randomize the CSRF Token for added security.
*/
public bool $tokenRandomize = false;
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection.
*/
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Header name for Cross Site Request Forgery protection.
*/
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection.
*/
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expires
* --------------------------------------------------------------------------
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*/
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every submission.
*/
public bool $regenerate = true;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*
* @see https://codeigniter4.github.io/userguide/libraries/security.html#redirection-on-failure
*/
public bool $redirect = (ENVIRONMENT === 'production');
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This file holds any application-specific services, or service overrides
* that you might need. An example has been included with the general
* method format you should use for your service methods. For more examples,
* see the core Services file at system/Config/Services.php.
*/
class Services extends BaseService
{
/*
* public static function example($getShared = true)
* {
* if ($getShared) {
* return static::getSharedInstance('example');
* }
*
* return new \CodeIgniter\Example();
* }
*/
}
+128
View File
@@ -0,0 +1,128 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Handlers\BaseHandler;
use CodeIgniter\Session\Handlers\FileHandler;
class Session extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Session Driver
* --------------------------------------------------------------------------
*
* The session storage driver to use:
* - `CodeIgniter\Session\Handlers\ArrayHandler` (for testing)
* - `CodeIgniter\Session\Handlers\FileHandler`
* - `CodeIgniter\Session\Handlers\DatabaseHandler`
* - `CodeIgniter\Session\Handlers\MemcachedHandler`
* - `CodeIgniter\Session\Handlers\RedisHandler`
*
* @var class-string<BaseHandler>
*/
public string $driver = FileHandler::class;
/**
* --------------------------------------------------------------------------
* Session Cookie Name
* --------------------------------------------------------------------------
*
* The session cookie name, must contain only [0-9a-z_-] characters
*/
public string $cookieName = 'ci_session';
/**
* --------------------------------------------------------------------------
* Session Expiration
* --------------------------------------------------------------------------
*
* The number of SECONDS you want the session to last.
* Setting to 0 (zero) means expire when the browser is closed.
*/
public int $expiration = 7200;
/**
* --------------------------------------------------------------------------
* Session Save Path
* --------------------------------------------------------------------------
*
* The location to save sessions to and is driver dependent.
*
* For the 'files' driver, it's a path to a writable directory.
* WARNING: Only absolute paths are supported!
*
* For the 'database' driver, it's a table name.
* Please read up the manual for the format with other session drivers.
*
* IMPORTANT: You are REQUIRED to set a valid save path!
*/
public string $savePath = WRITEPATH . 'session';
/**
* --------------------------------------------------------------------------
* Session Match IP
* --------------------------------------------------------------------------
*
* Whether to match the user's IP address when reading the session data.
*
* WARNING: If you're using the database driver, don't forget to update
* your session table's PRIMARY KEY when changing this setting.
*/
public bool $matchIP = false;
/**
* --------------------------------------------------------------------------
* Session Time to Update
* --------------------------------------------------------------------------
*
* How many seconds between CI regenerating the session ID.
*/
public int $timeToUpdate = 300;
/**
* --------------------------------------------------------------------------
* Session Regenerate Destroy
* --------------------------------------------------------------------------
*
* Whether to destroy session data associated with the old session ID
* when auto-regenerating the session ID. When set to FALSE, the data
* will be later deleted by the garbage collector.
*/
public bool $regenerateDestroy = false;
/**
* --------------------------------------------------------------------------
* Session Database Group
* --------------------------------------------------------------------------
*
* DB Group for the database session.
*/
public ?string $DBGroup = null;
/**
* --------------------------------------------------------------------------
* Lock Retry Interval (microseconds)
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Time (microseconds) to wait if lock cannot be acquired.
* The default is 100,000 microseconds (= 0.1 seconds).
*/
public int $lockRetryInterval = 100_000;
/**
* --------------------------------------------------------------------------
* Lock Max Retries
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Maximum number of lock acquisition attempts.
* The default is 300 times. That is lock timeout is about 30 (0.1 * 300)
* seconds.
*/
public int $lockMaxRetries = 300;
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\Toolbar\Collectors\Database;
use CodeIgniter\Debug\Toolbar\Collectors\Events;
use CodeIgniter\Debug\Toolbar\Collectors\Files;
use CodeIgniter\Debug\Toolbar\Collectors\Logs;
use CodeIgniter\Debug\Toolbar\Collectors\Routes;
use CodeIgniter\Debug\Toolbar\Collectors\Timers;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
/**
* --------------------------------------------------------------------------
* Debug Toolbar
* --------------------------------------------------------------------------
*
* The Debug Toolbar provides a way to see information about the performance
* and state of your application during that page display. By default it will
* NOT be displayed under production environments, and will only display if
* `CI_DEBUG` is true, since if it's not, there's not much to display anyway.
*/
class Toolbar extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Toolbar Collectors
* --------------------------------------------------------------------------
*
* List of toolbar collectors that will be called when Debug Toolbar
* fires up and collects data from.
*
* @var list<class-string>
*/
public array $collectors = [
Timers::class,
Database::class,
Logs::class,
Views::class,
// \CodeIgniter\Debug\Toolbar\Collectors\Cache::class,
Files::class,
Routes::class,
Events::class,
];
/**
* --------------------------------------------------------------------------
* Collect Var Data
* --------------------------------------------------------------------------
*
* If set to false var data from the views will not be collected. Useful to
* avoid high memory usage when there are lots of data passed to the view.
*/
public bool $collectVarData = true;
/**
* --------------------------------------------------------------------------
* Max History
* --------------------------------------------------------------------------
*
* `$maxHistory` sets a limit on the number of past requests that are stored,
* helping to conserve file space used to store them. You can set it to
* 0 (zero) to not have any history stored, or -1 for unlimited history.
*/
public int $maxHistory = 20;
/**
* --------------------------------------------------------------------------
* Toolbar Views Path
* --------------------------------------------------------------------------
*
* The full path to the the views that are used by the toolbar.
* This MUST have a trailing slash.
*/
public string $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
/**
* --------------------------------------------------------------------------
* Max Queries
* --------------------------------------------------------------------------
*
* If the Database Collector is enabled, it will log every query that the
* the system generates so they can be displayed on the toolbar's timeline
* and in the query log. This can lead to memory issues in some instances
* with hundreds of queries.
*
* `$maxQueries` defines the maximum amount of queries that will be stored.
*/
public int $maxQueries = 100;
/**
* --------------------------------------------------------------------------
* Watched Directories
* --------------------------------------------------------------------------
*
* Contains an array of directories that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
* We restrict the values to keep performance as high as possible.
*
* NOTE: The ROOTPATH will be prepended to all values.
*
* @var list<string>
*/
public array $watchedDirectories = [
'app',
];
/**
* --------------------------------------------------------------------------
* Watched File Extensions
* --------------------------------------------------------------------------
*
* Contains an array of file extensions that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
*
* @var list<string>
*/
public array $watchedExtensions = [
'php', 'css', 'js', 'html', 'svg', 'json', 'env',
];
/**
* --------------------------------------------------------------------------
* Ignored HTTP Headers
* --------------------------------------------------------------------------
*
* CodeIgniter Debug Toolbar normally injects HTML and JavaScript into every
* HTML response. This is correct for full page loads, but it breaks requests
* that expect only a clean HTML fragment.
*
* Libraries like HTMX, Unpoly, and Hotwire (Turbo) update parts of the page or
* manage navigation on the client side. Injecting the Debug Toolbar into their
* responses can cause invalid HTML, duplicated scripts, or JavaScript errors
* (such as infinite loops or "Maximum call stack size exceeded").
*
* Any request containing one of the following headers is treated as a
* client-managed or partial request, and the Debug Toolbar injection is skipped.
*
* @var array<string, string|null>
*/
public array $disableOnHeaders = [
'X-Requested-With' => 'xmlhttprequest', // AJAX requests
'HX-Request' => 'true', // HTMX requests
'X-Up-Version' => null, // Unpoly partial requests
];
}
+262
View File
@@ -0,0 +1,262 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* -------------------------------------------------------------------
* User Agents
* -------------------------------------------------------------------
*
* This file contains four arrays of user agent data. It is used by the
* User Agent Class to help identify browser, platform, robot, and
* mobile device data. The array keys are used to identify the device
* and the array values are used to set the actual name of the item.
*/
class UserAgents extends BaseConfig
{
/**
* -------------------------------------------------------------------
* OS Platforms
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS',
];
/**
* -------------------------------------------------------------------
* Browsers
* -------------------------------------------------------------------
*
* The order of this array should NOT be changed. Many browsers return
* multiple browser types so we want to identify the subtype first.
*
* @var array<string, string>
*/
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Edg' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser',
'Vivaldi' => 'Vivaldi',
];
/**
* -------------------------------------------------------------------
* Mobiles
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile',
];
/**
* -------------------------------------------------------------------
* Robots
* -------------------------------------------------------------------
*
* There are hundred of bots but these are the most common.
*
* @var array<string, string>
*/
public array $robots = [
'googlebot' => 'Googlebot',
'google-pagerenderer' => 'Google Page Renderer',
'google-read-aloud' => 'Google Read Aloud',
'google-safety' => 'Google Safety Bot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'bingpreview' => 'BingPreview',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot',
'duckduckbot' => 'DuckDuckBot',
'sogou' => 'Sogou Spider',
'exabot' => 'Exabot',
'bot' => 'Generic Bot',
'crawler' => 'Generic Crawler',
'spider' => 'Generic Spider',
];
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\StrictRules\CreditCardRules;
use CodeIgniter\Validation\StrictRules\FileRules;
use CodeIgniter\Validation\StrictRules\FormatRules;
use CodeIgniter\Validation\StrictRules\Rules;
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var list<string>
*/
public array $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace Config;
use CodeIgniter\Config\View as BaseView;
use CodeIgniter\View\ViewDecoratorInterface;
class View extends BaseView
{
/**
* When false, the view method will clear the data between each
* call. This keeps your data safe and ensures there is no accidental
* leaking between calls, so you would need to explicitly pass the data
* to each view. You might prefer to have the data stick around between
* calls so that it is available to all views. If that is the case,
* set $saveData to true.
*
* @var bool
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*
* Examples:
* { title|esc(js) }
* { created_on|date(Y-m-d)|esc(attr) }
*
* @var array<string, (callable(mixed): mixed)&string>
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*
* @var array<string, (callable(mixed...): mixed)|((callable(mixed...): mixed)&string)|list<(callable(mixed...): mixed)&string>>
*/
public $plugins = [];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var list<class-string<ViewDecoratorInterface>>
*/
public array $decorators = [];
/**
* Subdirectory within app/Views for namespaced view overrides.
*
* Namespaced views will be searched in:
*
* app/Views/{$appOverridesFolder}/{Namespace}/{view_path}.{php|html...}
*
* This allows application-level overrides for package or module views
* without modifying vendor source files.
*
* Examples:
* 'overrides' -> app/Views/overrides/Example/Blog/post/card.php
* 'vendor' -> app/Views/vendor/Example/Blog/post/card.php
* '' -> app/Views/Example/Blog/post/card.php (direct mapping)
*/
public string $appOverridesFolder = 'overrides';
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace Config;
/**
* This configuration controls how CodeIgniter behaves when running
* in worker mode (with FrankenPHP).
*/
class WorkerMode
{
/**
* Persistent Services
*
* List of service names that should persist across requests.
* These services will NOT be reset between requests.
*
* Services not in this list will be reset for each request to prevent
* state leakage.
*
* Recommended persistent services:
* - `autoloader`: PSR-4 autoloading configuration
* - `locator`: File locator
* - `exceptions`: Exception handler
* - `commands`: CLI commands registry
* - `codeigniter`: Main application instance
* - `superglobals`: Superglobals wrapper
* - `routes`: Router configuration
* - `cache`: Cache instance
*
* @var list<string>
*/
public array $persistentServices = [
'autoloader',
'locator',
'exceptions',
'commands',
'codeigniter',
'superglobals',
'routes',
'cache',
];
/**
* Reset Event Listeners
*
* List of event names whose listeners should be removed between requests.
* Use this if you register event listeners inside other event callbacks
* (rather than at the top level of Config/Events.php), which would cause
* them to accumulate across requests in worker mode.
*
* @var list<string>
*/
public array $resetEventListeners = [];
/**
* Force Garbage Collection
*
* Whether to force garbage collection after each request.
* Helps prevent memory leaks at a small performance cost.
*/
public bool $forceGarbageCollection = true;
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Libraries\Mongo;
use App\Models\GameModel;
use CodeIgniter\Controller;
class Api extends Controller
{
public function suggest(): \CodeIgniter\HTTP\ResponseInterface
{
$q = trim((string) service('request')->getGet('q'));
if (mb_strlen($q) < 2) {
return service('response')->setJSON([]);
}
return service('response')->setJSON((new GameModel())->suggest($q));
}
/**
* Game Prices API: lowest price by Steam App ID.
* GET /api/prices?appid=1245620
*/
public function prices(): \CodeIgniter\HTTP\ResponseInterface
{
$appid = (int) service('request')->getGet('appid');
if ($appid <= 0) {
return service('response')->setStatusCode(400)->setJSON([
'error' => 'bad_request',
'message' => 'Missing or invalid "appid" query parameter.',
]);
}
// appid map is in the CrawlCovers command; reuse via a public map.
$game = (new GameModel())->findByAppId($appid);
if ($game === null) {
return service('response')->setStatusCode(404)->setJSON([
'error' => 'not_found',
'message' => "No game found for Steam App ID {$appid}.",
]);
}
return service('response')->setJSON([
'game' => [
'title' => $game['title'],
'slug' => $game['slug'],
'url' => '/game/' . $game['slug'],
'steam_appid' => $appid,
'regular_price' => (float) $game['base_price'],
'best_official' => [
'price' => (float) $game['best_official']['price'],
'store' => $game['best_official']['store'],
'cut' => (int) $game['best_official']['cut'],
],
'best_keyshop' => [
'price' => (float) $game['best_keyshop']['price'],
'store' => $game['best_keyshop']['store'],
'cut' => (int) $game['best_keyshop']['cut'],
],
'all_time_low' => [
'price' => (float) $game['all_time_low']['price'],
'store' => $game['all_time_low']['store'],
'date' => $game['all_time_low']['date'] instanceof \MongoDB\BSON\UTCDateTime
? $game['all_time_low']['date']->toDateTime()->format('Y-m-d')
: null,
],
'active_deals' => (int) $game['active_deals'],
'metacritic' => (int) $game['score'],
],
]);
}
/**
* API documentation page data (regions, endpoints).
*/
public function docs(): string
{
$model = new GameModel();
$data = [
'pageTitle' => 'GG.deals API — Game Deals, Bundles and Prices API',
'stats' => $model->stats(),
];
return view('api', $data);
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
*
* Extend this class in any new controllers:
* ```
* class Home extends BaseController
* ```
*
* For security, be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
/**
* Be sure to declare properties for any property fetch you initialized.
* The creation of dynamic property is deprecated in PHP 8.2.
*/
// protected $session;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Load here all helpers you want to be available in your controllers that extend BaseController.
// Caution: Do not put the this below the parent::initController() call below.
// $this->helpers = ['form', 'url'];
// Caution: Do not edit this line.
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
// $this->session = service('session');
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Libraries\Mongo;
use App\Models\GameModel;
use App\Models\StoreModel;
use CodeIgniter\Controller;
class Bundle extends Controller
{
public function index(string $slug): string
{
$b = Mongo::collection('bundles')->findOne(['slug' => $slug]);
if ($b === null) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$games = [];
foreach ($b['games'] as $gslug) {
$g = (new GameModel())->findBySlug($gslug);
if ($g !== null) {
$games[] = $g;
}
}
$data = [
'pageTitle' => $b['title'] . ' Bundle — GG.deals',
'bundle' => $b,
'games' => $games,
'stores' => (new StoreModel())->map(),
];
return view('bundle', $data);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Libraries\Mongo;
use App\Models\GameModel;
use CodeIgniter\Controller;
class Franchise extends Controller
{
public function index(string $slug): string
{
$fr = Mongo::collection('franchises')->findOne(['slug' => $slug]);
if ($fr === null) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$games = [];
foreach ($fr['games'] as $gslug) {
$g = (new GameModel())->findBySlug($gslug);
if ($g !== null) {
$games[] = $g;
}
}
$data = [
'pageTitle' => $fr['name'] . ' Franchise — GG.deals',
'franchise' => $fr,
'games' => $games,
'allFranchises' => Mongo::collection('franchises')->find([], ['sort' => ['name' => 1]])->toArray(),
];
return view('franchise', $data);
}
public function all(): string
{
$list = Mongo::collection('franchises')->find([], ['sort' => ['name' => 1]])->toArray();
$data = [
'pageTitle' => 'Franchises — GG.deals',
'franchises' => $list,
];
return view('franchises', $data);
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Libraries\Mongo;
use App\Models\GameModel;
use App\Models\StoreModel;
use CodeIgniter\Controller;
class Game extends Controller
{
public function show(string $slug): string
{
$model = new GameModel();
$game = $model->findBySlug($slug);
if ($game === null) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$deals = $model->dealsFor($slug);
$history = $model->historyFor($slug);
$similar = $model->similar($game, 8);
$bundles = $model->bundlesFor($slug);
$franchises = $model->franchisesFor($slug);
$subscriptions = Mongo::collection('subscriptions')->find([], ['sort' => ['price' => 1]])->toArray();
$data = [
'pageTitle' => $game['title'] . ' — best deals — GG.deals',
'game' => $game,
'deals' => $deals,
'history' => $history,
'stores' => (new StoreModel())->map(),
'similar' => $similar,
'bundles' => $bundles,
'franchises' => $franchises,
'subscriptions' => $subscriptions,
];
return view('game', $data);
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Models\GameModel;
use App\Models\StoreModel;
use CodeIgniter\Controller;
class Games extends Controller
{
public function index(string $genre = ''): string
{
$model = new GameModel();
$request = service('request');
// genre map (slug => name)
$genres = [];
foreach ($model->genres() as $g) {
$slug = url_title((string) $g['_id'], '-', true);
$genres[$slug] = ['name' => $g['_id'], 'count' => $g['count']];
}
ksort($genres);
$genreName = '';
if ($genre !== '') {
if (! isset($genres[$genre])) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$genreName = $genres[$genre]['name'];
}
// ---- filters (same shape as the deal feed) ----
$filters = [
'stores' => array_values(array_filter(array_map('strval', (array) $request->getGet('stores')))),
'kind' => (string) ($request->getGet('kind') ?? ''),
'min_price' => $request->getGet('min_price') !== null ? (string) $request->getGet('min_price') : '',
'max_price' => $request->getGet('max_price') !== null ? (string) $request->getGet('max_price') : '',
'min_cut' => (int) ($request->getGet('min_cut') ?? 0),
'hl_only' => (bool) $request->getGet('hl_only'),
'sort' => (string) ($request->getGet('sort') ?? 'trending'),
'q' => trim((string) ($request->getGet('q') ?? '')),
'price_tier' => (string) ($request->getGet('price_tier') ?? ''),
'discount_tier' => (string) ($request->getGet('discount_tier') ?? ''),
'deal_rating' => (string) ($request->getGet('deal_rating') ?? ''),
'release_range' => (string) ($request->getGet('release_range') ?? ''),
'time_range' => (string) ($request->getGet('time_range') ?? ''),
'genre' => $genreName,
'genres' => array_values(array_filter(array_map('strval', (array) $request->getGet('genres')))),
];
$page = max(1, (int) $request->getGet('page'));
$perPage = 20;
$feed = $model->feed($filters, $page, $perPage);
$data = [
'pageTitle' => ($genreName !== '' ? ucwords($genreName) . ' games — ' : '') . 'GG.deals',
'filters' => $filters,
'feed' => $feed['rows'],
'total' => $feed['total'],
'pages' => $feed['pages'],
'page' => $page,
'perPage' => $perPage,
'genres' => $genres,
'activeGenre' => $genre,
'activeGenreName' => $genreName,
'stores' => (new StoreModel())->all(),
'stats' => $model->stats(),
];
return view('games', $data);
}
}
+136
View File
@@ -0,0 +1,136 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Models\GameModel;
use App\Models\StoreModel;
use App\Libraries\Mongo;
class Home extends BaseController
{
/**
* Deal presets (mirrors gg.deals /deals/{preset}/ URLs).
*/
private const PRESETS = [
'hot-new-deals' => ['title' => 'Hot New Deals', 'sort' => 'hot', 'preset' => 'hot_new'],
'new-deals' => ['title' => 'New Deals', 'sort' => 'recent', 'preset' => 'new'],
'historical-lows' => ['title' => 'Historical Lows', 'sort' => 'rating', 'preset' => 'hl'],
'ending-soon' => ['title' => 'Ending Soon', 'sort' => 'ending', 'preset' => 'ending'],
'at-least-75-off' => ['title' => 'At least 75% off', 'sort' => 'cut', 'preset' => 'cut75'],
'at-least-85-off' => ['title' => 'At least 85% off', 'sort' => 'cut', 'preset' => 'cut85'],
];
public function index(): string
{
$request = service('request');
// If any filter/search is active → regular deal feed. Otherwise → homepage dashboard.
$hasFilters = $request->getGet('stores') !== null || $request->getGet('kind') !== null
|| $request->getGet('min_price') !== null || $request->getGet('max_price') !== null
|| $request->getGet('min_cut') !== null || $request->getGet('hl_only') !== null
|| $request->getGet('sort') !== null || $request->getGet('price_tier') !== null
|| $request->getGet('discount_tier') !== null || $request->getGet('deal_rating') !== null
|| $request->getGet('release_range') !== null || $request->getGet('q') !== null;
if (! $hasFilters) {
return $this->dashboard();
}
return $this->renderFeed([]);
}
/**
* Plain deal feed (used by /deals) regardless of filters.
*/
public function feedOnly(): string
{
return $this->renderFeed([]);
}
/**
* Homepage dashboard mirroring gg.deals: multiple preset sections.
*/
private function dashboard(): string
{
$model = new GameModel();
$data = [
'pageTitle' => 'GG.deals — Best game deals, prices &amp; discounts',
'popular' => $model->dashboardDeals('best', 8),
'newDeals' => $model->dashboardDeals('new', 8),
'bestDeals' => $model->dashboardDeals('hot', 8),
'histLows' => $model->dashboardDeals('hl', 8),
'endingSoon' => $model->dashboardDeals('ending', 8),
'mostWanted' => $model->dashboardGames('wanted', 8),
'newReleases' => $model->dashboardGames('releases', 8),
'upcoming' => $model->dashboardGames('upcoming', 8),
'news' => $model->recentNews(6),
'prepaids' => Mongo::collection('prepaids')->find([], ['sort' => ['name' => 1], 'limit' => 8])->toArray(),
'stats' => $model->stats(),
'stores' => (new StoreModel())->map(),
'trending' => $model->trending(12),
];
return view('homepage', $data);
}
public function preset(string $name): string
{
if (! isset(self::PRESETS[$name])) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
return $this->renderFeed(self::PRESETS[$name]);
}
private function renderFeed(array $preset): string
{
$request = service('request');
$filters = [
'stores' => array_values(array_filter(array_map('strval', (array) $request->getGet('stores')))),
'kind' => (string) ($request->getGet('kind') ?? ''),
'min_price' => $request->getGet('min_price') !== null ? (string) $request->getGet('min_price') : '',
'max_price' => $request->getGet('max_price') !== null ? (string) $request->getGet('max_price') : '',
'min_cut' => (int) ($request->getGet('min_cut') ?? 0),
'hl_only' => (bool) $request->getGet('hl_only'),
'sort' => (string) ($request->getGet('sort') ?? ($preset['sort'] ?? 'trending')),
'q' => trim((string) ($request->getGet('q') ?? '')),
'price_tier'=> (string) ($request->getGet('price_tier') ?? ''),
'discount_tier' => (string) ($request->getGet('discount_tier') ?? ''),
'deal_rating' => (string) ($request->getGet('deal_rating') ?? ''),
'release_range' => (string) ($request->getGet('release_range') ?? ''),
'time_range' => (string) ($request->getGet('time_range') ?? ''),
'view' => (string) ($request->getGet('view') ?? 'sidebar'),
'wishlist' => array_values(array_filter(array_map('strval', (array) $request->getGet('wishlist')))),
];
$filters['preset'] = $preset['preset'] ?? '';
$filters['preset_name'] = $preset['title'] ?? '';
$page = max(1, (int) $request->getGet('page'));
$perPage = 20;
$model = new GameModel();
$feed = $model->feed($filters, $page, $perPage);
$data = [
'pageTitle' => ($filters['preset_name'] !== '' ? $filters['preset_name'] . ' — ' : '') . 'Best PC game deals — GG.deals',
'filters' => $filters,
'feed' => $feed['rows'],
'total' => $feed['total'],
'pages' => $feed['pages'],
'page' => $page,
'perPage' => $perPage,
'trending' => $model->trending(12),
'stores' => (new StoreModel())->all(),
'stats' => $model->stats(),
'presets' => self::PRESETS,
'activePreset' => $filters['preset_name'],
];
return view('home', $data);
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Libraries\Mongo;
use CodeIgniter\Controller;
class News extends Controller
{
private const CATEGORIES = [
'' => 'All news',
'deals' => 'Deals',
'bundles' => 'Bundles',
'freebies' => 'Freebies',
'giveaways' => 'Giveaways',
'subscriptions' => 'Subscriptions',
];
public function index(string $cat = ''): string
{
if (! isset(self::CATEGORIES[$cat])) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$filter = $cat !== '' ? ['category' => $cat] : [];
$posts = Mongo::collection('news')
->find($filter, ['sort' => ['date' => -1], 'limit' => 40])
->toArray();
$data = [
'pageTitle' => 'Video game news — GG.deals',
'posts' => $posts,
'cats' => self::CATEGORIES,
'active' => $cat,
];
return view('news', $data);
}
public function article(string $slug): string
{
$post = Mongo::collection('news')->findOne(['slug' => $slug]);
if ($post === null) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$related = Mongo::collection('news')
->find(
['slug' => ['$ne' => $slug], 'category' => $post['category']],
['sort' => ['date' => -1], 'limit' => 4]
)
->toArray();
$data = [
'pageTitle' => $post['title'] . ' — GG.deals',
'post' => $post,
'related' => $related,
'cats' => self::CATEGORIES,
'active' => $post['category'],
];
return view('news_article', $data);
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use CodeIgniter\Controller;
class Pages extends Controller
{
public function faq(): string
{
$data = [
'pageTitle' => 'FAQ — GG.deals',
];
return view('faq', $data);
}
public function tutorial(string $topic): string
{
$tutorials = [
'activate-steam' => ['How to activate Steam CD key', 'steam'],
'activate-gog' => ['How to activate GOG CD key', 'gog'],
'activate-epic' => ['How to activate Epic Games CD key', 'epic'],
'activate-origin' => ['How to activate Origin CD key', 'origin'],
'activate-uplay' => ['How to activate Uplay CD key', 'uplay'],
'keyshops-risks' => ['Keyshops — what to know', 'keyshops'],
];
if (! isset($tutorials[$topic])) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$data = [
'pageTitle' => $tutorials[$topic][0] . ' — GG.deals',
'tutorial' => $tutorials[$topic],
'all' => $tutorials,
];
return view('tutorial', $data);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Libraries\Mongo;
use CodeIgniter\Controller;
class Prepaids extends Controller
{
public function index(): string
{
$groups = Mongo::collection('prepaids')->find([], ['sort' => ['name' => 1]])->toArray();
$data = [
'pageTitle' => 'Gift Cards &amp; Prepaids — GG.deals',
'groups' => $groups,
];
return view('prepaids', $data);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Models\GameModel;
use CodeIgniter\Controller;
class Rankings extends Controller
{
public function index(): string
{
$model = new GameModel();
$data = [
'pageTitle' => 'Rankings — GG.deals',
'wishlisted' => $model->ranked('trending', 20),
'collected' => $model->ranked('rating_pct', 20),
'metacritic' => $model->ranked('score', 20),
'reviews' => $model->ranked('rating_pct', 20),
];
return view('rankings', $data);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Models\GameModel;
use CodeIgniter\Controller;
class Stores extends Controller
{
public function index(): string
{
$model = new GameModel();
$data = [
'pageTitle' => 'Stores — GG.deals',
'stores' => $model->storeStats(),
];
return view('stores', $data);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Libraries\Mongo;
use CodeIgniter\Controller;
class Subscriptions extends Controller
{
public function index(): string
{
$subs = Mongo::collection('subscriptions')
->find([], ['sort' => ['price' => 1]])
->toArray();
$data = [
'pageTitle' => 'Subscriptions — GG.deals',
'subs' => $subs,
'stores' => (new \App\Models\StoreModel())->map(),
];
return view('subscriptions', $data);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Models\StoreModel;
use App\Libraries\Mongo;
use CodeIgniter\Controller;
class Vouchers extends Controller
{
public function index(): string
{
$vouchers = Mongo::collection('vouchers')->find([], ['sort' => ['store' => 1]])->toArray();
$data = [
'pageTitle' => 'Promo Codes &amp; Coupons — GG.deals',
'vouchers' => $vouchers,
'stores' => (new StoreModel())->map(),
];
return view('vouchers', $data);
}
public function store(string $code): string
{
$vouchers = Mongo::collection('vouchers')->find(['store' => $code], ['sort' => ['created' => -1]])->toArray();
$data = [
'pageTitle' => ucfirst($code) . ' promo codes — GG.deals',
'vouchers' => $vouchers,
'stores' => (new StoreModel())->map(),
'storeCode' => $code,
];
return view('vouchers', $data);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Models\GameModel;
use CodeIgniter\Controller;
class Wishlist extends Controller
{
public function index(): string
{
// wishlist slugs come from localStorage client-side; the page shows
// the JS-powered collection with an optional server fetch fallback.
$data = [
'pageTitle' => 'Wishlist — GG.deals',
];
return view('wishlist', $data);
}
/**
* JSON: fetch full game data for a list of slugs (used by the wishlist page).
*/
public function data(): \CodeIgniter\HTTP\ResponseInterface
{
$slugs = (array) service('request')->getGet('slugs');
$games = [];
foreach (array_unique(array_filter($slugs)) as $slug) {
$g = (new GameModel())->findBySlug($slug);
if ($g !== null) {
$games[] = $g;
}
}
return service('response')->setJSON($games);
}
}
View File
View File
View File
View File
+110
View File
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
/**
* Price formatter.
*/
function money(float|int|null $v): string
{
if ($v === null) {
return '—';
}
return '$' . number_format((float) $v, 2);
}
/**
* Discount badge class: bigger cut => hotter color.
*/
function cut_class(int $cut): string
{
return $cut >= 75 ? 'cut-hi' : ($cut >= 50 ? 'cut-mid' : 'cut-lo');
}
/**
* Deal rating label comparing current price to the all-time low.
*/
function deal_rating(float $hl, float $price): array
{
$ratio = $price > 0 ? $hl / $price : 0;
return match (true) {
$ratio >= 0.99 => ['label' => '🔥 Hot', 'cls' => 'rating-best', 'ratio' => $ratio],
$ratio >= 0.85 => ['label' => '🔥 Hot', 'cls' => 'rating-great', 'ratio' => $ratio],
$ratio >= 0.6 => ['label' => 'Good deal', 'cls' => 'rating-good', 'ratio' => $ratio],
$ratio >= 0.35 => ['label' => 'Fair deal', 'cls' => 'rating-fair', 'ratio' => $ratio],
default => ['label' => 'High price', 'cls' => 'rating-high', 'ratio' => $ratio],
};
}
/**
* Build a URL like the current one with query params overridden.
*/
function qs_url(array $overrides = [], array $remove = []): string
{
$get = service('request')->getGet();
$get = array_map(static fn ($v) => is_array($v) ? array_values(array_filter($v, 'strlen')) : $v, $get);
foreach ($remove as $key) {
unset($get[$key]);
}
$get = array_merge($get, $overrides);
// drop empty / zero-default params for clean URLs
foreach ($get as $key => $val) {
if (is_array($val)) {
if ($val === []) unset($get[$key]);
continue;
}
if ($key === 'min_cut' && (int) $val === 0) { unset($get[$key]); continue; }
if ($key === 'kind' && $val === '') { unset($get[$key]); continue; }
if ($key === 'page' && ($val === null || (int) $val === 1)) { unset($get[$key]); continue; }
if (($key === 'min_price' || $key === 'max_price' || $key === 'q') && $val === '') { unset($get[$key]); continue; }
}
$qs = http_build_query($get);
// keep the current path (e.g. /games/rpg) so filters stay within it
$path = '/' . ltrim(uri_string(), '/');
return $path . ($qs !== '' ? '?' . $qs : '');
}
function store_initials(string $name): string
{
$words = preg_split('/\s+/', $name) ?: [];
$ini = '';
foreach ($words as $w) {
if ($w === '' || ! ctype_alpha($w[0])) {
continue;
}
$ini .= strtoupper($w[0]);
if (strlen($ini) >= 2) {
break;
}
}
return $ini !== '' ? $ini : strtoupper(substr($name, 0, 2));
}
function time_ago(int|string|MongoDB\BSON\UTCDateTime $ts): string
{
if ($ts instanceof MongoDB\BSON\UTCDateTime) {
$ts = $ts->toDateTime()->getTimestamp();
}
$diff = max(1, time() - (int) $ts);
if ($diff < 3600) return floor($diff / 60) . ' min ago';
if ($diff < 86400) return floor($diff / 3600) . ' h ago';
if ($diff < 86400*30) return floor($diff / 86400) . ' days ago';
if ($diff < 86400*365) return floor($diff / (86400*30)) . ' months ago';
return floor($diff / (86400*365)) . ' y ago';
}
function bson_date($ts): ?string
{
if (! $ts instanceof MongoDB\BSON\UTCDateTime) {
return null;
}
return date('M j, Y', $ts->toDateTime()->getTimestamp());
}
View File
+4
View File
@@ -0,0 +1,4 @@
<?php
// override core en language system validation or define your own en language validation message
return [];
View File
+61
View File
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace App\Libraries;
use MongoDB\Client;
use MongoDB\Database;
/**
* Shared MongoDB connection wrapper.
*/
final class Mongo
{
private static ?Database $db = null;
public static function db(): Database
{
if (self::$db === null) {
$db = env('MONGO_DB', 'ggdeals');
$client = new Client(
self::uri(),
[],
[
'typeMap' => [
'root' => 'array',
'document' => 'array',
'array' => 'array',
],
]
);
self::$db = $client->selectDatabase($db);
}
return self::$db;
}
private static function uri(): string
{
$uri = env('MONGO_URI');
if (is_string($uri) && $uri !== '') {
return $uri;
}
$host = env('MONGO_HOST', 'harness-mongo');
$port = env('MONGO_PORT', '27017');
$user = (string) env('MONGO_USER', '');
$pass = (string) env('MONGO_PASS', '');
$auth = $user !== '' ? urlencode($user) . ':' . urlencode($pass) . '@' : '';
return "mongodb://{$auth}{$host}:{$port}/?authSource=admin";
}
public static function collection(string $name): \MongoDB\Collection
{
return self::db()->selectCollection($name);
}
}
View File
+587
View File
@@ -0,0 +1,587 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Libraries\Mongo;
use MongoDB\BSON\UTCDateTime;
/**
* Game data access layer built on MongoDB aggregations.
*/
class GameModel
{
/**
* Deal feed: best current deal per game, filtered + sorted.
*/
public function feed(array $filters, int $page, int $perPage): array
{
$match = [];
$stores = $filters['stores'] ?? [];
if ($stores !== []) {
$match['store_code'] = ['$in' => $stores];
}
if (! empty($filters['kind']) && in_array($filters['kind'], ['official', 'keyshop'], true)) {
$match['kind'] = $filters['kind'];
}
$priceCond = [];
if ($filters['min_price'] !== null && $filters['min_price'] !== '') {
$priceCond['$gte'] = (float) $filters['min_price'];
}
if ($filters['max_price'] !== null && $filters['max_price'] !== '') {
$priceCond['$lte'] = (float) $filters['max_price'];
}
if ($priceCond !== []) {
$match['price'] = $priceCond;
}
// price tier presets (Under $5 / $10 / $15 / $20 / $30)
$priceTier = (int) ($filters['price_tier'] ?? 0);
if ($priceTier > 0) {
$match['price'] = array_merge($match['price'] ?? [], ['$lte' => (float) $priceTier]);
}
$minCut = (int) ($filters['min_cut'] ?? 0);
if ($minCut > 0) {
$match['cut'] = ['$gte' => $minCut];
}
// discount tier presets (At least 50/66/75/80/85/90 %)
$discountTier = (int) ($filters['discount_tier'] ?? 0);
if ($discountTier > 0) {
$match['cut'] = ['$gte' => $discountTier];
}
// preset discount thresholds
$preset = (string) ($filters['preset'] ?? '');
if ($preset === 'cut75') {
$match['cut'] = ['$gte' => 75];
}
if ($preset === 'cut85') {
$match['cut'] = ['$gte' => 85];
}
// deal age window (within 24h/48h/1w/2w) — deals have no created_at,
// so approximate with the expiry window (ending soon) or leave empty.
$timeRange = (string) ($filters['time_range'] ?? '');
if ($timeRange !== '' && $timeRange !== 'any') {
// apply on game.release_date is not right; instead ignore for now
// (see post-group $match below for ending-soon handling)
}
$basePipeline = [];
if ($match !== []) {
$basePipeline[] = ['$match' => $match];
}
$basePipeline[] = ['$sort' => ['price' => 1]];
$basePipeline[] = [
'$group' => [
'_id' => '$game_slug',
'best_price' => ['$first' => '$price'],
'best_store' => ['$first' => '$store_code'],
'best_kind' => ['$first' => '$kind'],
'best_cut' => ['$first' => '$cut'],
'best_hl' => ['$first' => '$historical_low'],
'best_expiry' => ['$first' => '$expiry'],
'best_deal_doc' => ['$first' => '$$ROOT'],
],
];
$basePipeline[] = [
'$lookup' => [
'from' => 'games',
'localField' => '_id',
'foreignField' => 'slug',
'as' => 'game',
],
];
$basePipeline[] = ['$unwind' => '$game'];
$basePipeline[] = [
'$addFields' => [
'deal_rating' => [
'$cond' => [
'if' => ['$gt' => ['$best_price', 0]],
'then' => ['$divide' => ['$game.all_time_low.price', '$best_price']],
'else' => 0,
],
],
'ends_within' => [
'$cond' => [
'if' => ['$ne' => ['$best_expiry', null]],
'then' => ['$subtract' => ['$best_expiry', '$$NOW']],
'else' => 86400000 * 365,
],
],
],
];
if (! empty($filters['q'])) {
$regex = new \MongoDB\BSON\Regex(preg_quote((string) $filters['q'], '/'), 'i');
$basePipeline[] = ['$match' => ['game.title' => $regex]];
}
// genre filter (e.g. /games/{genre})
if (! empty($filters['genre'])) {
$basePipeline[] = ['$match' => ['game.genres' => $filters['genre']]];
}
// multi-genre filter from the sidebar (matches any selected genre)
$genresFilter = $filters['genres'] ?? [];
if ($genresFilter !== []) {
$basePipeline[] = ['$match' => ['game.genres' => ['$in' => $genresFilter]]];
}
if (! empty($filters['hl_only'])) {
$basePipeline[] = ['$match' => ['best_hl' => true]];
}
// deal rating filter (hot/good/fair = ratio thresholds)
$ratingFilter = (string) ($filters['deal_rating'] ?? '');
if ($ratingFilter !== '' && $ratingFilter !== 'any') {
$ratios = [
'hot' => ['$gte' => 0.85],
'good' => ['$gte' => 0.6],
'fair' => ['$gte' => 0.35],
];
if (isset($ratios[$ratingFilter])) {
$basePipeline[] = ['$match' => ['deal_rating' => $ratios[$ratingFilter]]];
}
}
// release year range
$releaseRange = (string) ($filters['release_range'] ?? '');
if ($releaseRange !== '' && $releaseRange !== 'any') {
$ranges = [
'pre2000' => ['$lte' => mktime(0, 0, 0, 1, 1, 2000) * 1000],
'2000s' => ['$gte' => mktime(0, 0, 0, 1, 1, 2000) * 1000, '$lte' => mktime(0, 0, 0, 1, 1, 2010) * 1000],
'2010s' => ['$gte' => mktime(0, 0, 0, 1, 1, 2010) * 1000, '$lte' => mktime(0, 0, 0, 1, 1, 2020) * 1000],
'2020s' => ['$gte' => mktime(0, 0, 0, 1, 1, 2020) * 1000],
];
if (isset($ranges[$releaseRange])) {
$basePipeline[] = ['$match' => ['game.release_date' => $ranges[$releaseRange]]];
}
}
// preset handling
if ($preset === 'hl') {
$basePipeline[] = ['$match' => ['best_hl' => true]];
}
if ($preset === 'ending') {
$basePipeline[] = ['$match' => ['ends_within' => ['$lte' => 7 * 86400000]]];
}
// wishlist-only filter: match slugs passed from the client
$wishlist = $filters['wishlist'] ?? [];
if ($wishlist !== []) {
$basePipeline[] = ['$match' => ['game.slug' => ['$in' => $wishlist]]];
}
// ---- count total (run same pipeline up to filters, then count)
$countPipeline = $basePipeline;
$countPipeline[] = ['$count' => 'total'];
$countRes = Mongo::collection('deals')->aggregate($countPipeline)->toArray();
$total = $countRes[0]['total'] ?? 0;
// ---- sort
$sortStage = match ($filters['sort'] ?? 'trending') {
'price' => ['best_price' => 1],
'cut' => ['best_cut' => -1],
'recent' => ['game.release_date' => -1],
'hl' => ['game.all_time_low.price' => 1],
'rating' => ['deal_rating' => -1],
'title' => ['game.title' => 1],
'metascore' => ['game.score' => -1],
'length' => ['game.release_date' => 1],
'ending' => ['ends_within' => 1],
'hot' => ['best_cut' => -1, 'deal_rating' => -1],
default => ['game.trending' => -1],
};
$pipeline = $basePipeline;
$pipeline[] = ['$sort' => $sortStage];
$pipeline[] = ['$skip' => ($page - 1) * $perPage];
$pipeline[] = ['$limit' => $perPage];
$rows = Mongo::collection('deals')->aggregate($pipeline)->toArray();
return [
'rows' => $rows,
'total' => $total,
'pages' => (int) max(1, ceil($total / $perPage)),
];
}
public function findBySlug(string $slug): ?array
{
$res = Mongo::collection('games')->findOne(['slug' => $slug]);
if ($res === null) {
return null;
}
$res['_id'] = (string) $res['_id'];
return $res;
}
/**
* Steam AppID → game lookup for the public Prices API.
*/
public function findByAppId(int $appid): ?array
{
$slug = array_search($appid, \App\Commands\CrawlCovers::APP_IDS, true);
if ($slug === false) {
return null;
}
return $this->findBySlug((string) $slug);
}
/**
* All active deals for a game, sorted by price.
*/
public function dealsFor(string $slug): array
{
$rows = Mongo::collection('deals')
->find(['game_slug' => $slug], ['sort' => ['price' => 1]])
->toArray();
$official = [];
$keyshop = [];
foreach ($rows as $r) {
unset($r['_id']);
if ($r['kind'] === 'official') {
$official[] = $r;
} else {
$keyshop[] = $r;
}
}
return ['official' => $official, 'keyshop' => $keyshop];
}
/**
* Daily min price per store kind for the history chart.
*/
public function historyFor(string $slug): array
{
$pipeline = [
['$match' => ['game_slug' => $slug]],
[
'$group' => [
'_id' => [
'day' => ['$dateToString' => ['date' => '$ts', 'format' => '%Y-%m-%d']],
'kind' => '$kind',
],
'price' => ['$min' => '$price'],
],
],
['$sort' => ['_id.day' => 1]],
];
$rows = Mongo::collection('price_history')->aggregate($pipeline)->toArray();
$series = ['official' => [], 'keyshop' => []];
foreach ($rows as $r) {
$series[$r['_id']['kind']][] = ['day' => $r['_id']['day'], 'price' => round($r['price'], 2)];
}
return $series;
}
public function trending(int $limit = 12): array
{
$rows = Mongo::collection('games')
->find([], ['sort' => ['trending' => -1], 'limit' => $limit])
->toArray();
foreach ($rows as &$r) {
$r['_id'] = (string) $r['_id'];
}
return $rows;
}
/**
* Ranking list by a numeric field (score, rating_pct, trending, etc).
*/
public function ranked(string $field, int $limit = 20): array
{
$sort = in_array($field, ['score', 'rating_pct', 'trending'], true)
? [$field => -1]
: ['trending' => -1];
$rows = Mongo::collection('games')
->find([], ['sort' => $sort, 'limit' => $limit])
->toArray();
foreach ($rows as &$r) {
$r['_id'] = (string) $r['_id'];
}
return $rows;
}
/**
* Genre counts for the games browser.
*/
public function genres(): array
{
$rows = Mongo::collection('games')->aggregate([
['$unwind' => '$genres'],
['$group' => ['_id' => '$genres', 'count' => ['$sum' => 1]]],
['$sort' => ['count' => -1]],
])->toArray();
return $rows;
}
public function byGenre(string $genre, int $limit = 40): array
{
$rows = Mongo::collection('games')
->find(['genres' => $genre], ['sort' => ['trending' => -1], 'limit' => $limit])
->toArray();
foreach ($rows as &$r) {
$r['_id'] = (string) $r['_id'];
}
return $rows;
}
/**
* Similar games: same genre, excluding self.
*/
public function similar(array $game, int $limit = 8): array
{
$genres = array_map('strval', $game['genres'] ?? []);
if ($genres === []) {
return [];
}
$rows = Mongo::collection('games')
->find(
['slug' => ['$ne' => $game['slug']], 'genres' => ['$in' => $genres]],
['sort' => ['trending' => -1], 'limit' => $limit]
)
->toArray();
foreach ($rows as &$r) {
$r['_id'] = (string) $r['_id'];
}
return $rows;
}
public function suggest(string $q, int $limit = 8): array
{
$regex = new \MongoDB\BSON\Regex(preg_quote($q, '/'), 'i');
$rows = Mongo::collection('games')
->find(['title' => $regex], [
'sort' => ['trending' => -1],
'limit' => $limit,
'projection' => ['title' => 1, 'slug' => 1, 'cover' => 1, 'all_time_low' => 1, 'best_official' => 1, 'best_keyshop' => 1, 'active_deals' => 1],
])
->toArray();
$out = [];
foreach ($rows as $r) {
$out[] = [
'title' => $r['title'],
'slug' => $r['slug'],
'cover' => $r['cover']['file'] ?? '',
'hl' => $r['all_time_low']['price'] ?? null,
'deals' => $r['active_deals'] ?? 0,
];
}
return $out;
}
public function storeStats(): array
{
$pipeline = [
[
'$group' => [
'_id' => '$store_code',
'deals' => ['$sum' => 1],
'min_price' => ['$min' => '$price'],
'avg_cut' => ['$avg' => '$cut'],
],
],
];
$rows = Mongo::collection('deals')->aggregate($pipeline)->toArray();
$stores = [];
foreach (Mongo::collection('stores')->find()->toArray() as $s) {
$stores[$s['code']] = [
'code' => $s['code'],
'name' => $s['name'],
'kind' => $s['kind'],
'color' => $s['color'],
'textcolor' => $s['textcolor'],
'logo' => $s['logo'] ?? '/img/stores/' . $s['code'] . '.png',
'deals' => 0,
'min_price' => null,
'avg_cut' => 0,
];
}
foreach ($rows as $r) {
if (isset($stores[$r['_id']])) {
$stores[$r['_id']]['deals'] = $r['deals'];
$stores[$r['_id']]['min_price'] = $r['min_price'];
$stores[$r['_id']]['avg_cut'] = round($r['avg_cut'], 1);
}
}
usort($stores, static fn ($a, $b) => $b['deals'] <=> $a['deals']);
return array_values($stores);
}
public function stats(): array
{
$games = Mongo::collection('games')->countDocuments();
$deals = Mongo::collection('deals')->countDocuments();
return [
'games' => $games,
'deals' => $deals,
'stores' => Mongo::collection('stores')->countDocuments(),
'hl_now' => Mongo::collection('deals')->countDocuments(['historical_low' => true]),
];
}
/**
* Compact deal rows for the homepage dashboard sections.
* $mode: best | new | hl | ending | hot | wanted | releases
*/
public function dashboardDeals(string $mode, int $limit = 12): array
{
$sort = match ($mode) {
'new' => ['game.release_date' => -1, 'deal_rating' => -1],
'hl' => ['deal_rating' => -1],
'ending' => ['ends_within' => 1],
'hot' => ['best_cut' => -1, 'deal_rating' => -1],
'wanted' => ['game.trending' => -1],
default => ['deal_rating' => -1, 'best_cut' => -1],
};
$pipeline = [
['$sort' => ['price' => 1]],
[
'$group' => [
'_id' => '$game_slug',
'best_price' => ['$first' => '$price'],
'best_store' => ['$first' => '$store_code'],
'best_kind' => ['$first' => '$kind'],
'best_cut' => ['$first' => '$cut'],
'best_hl' => ['$first' => '$historical_low'],
'best_expiry' => ['$first' => '$expiry'],
],
],
[
'$lookup' => [
'from' => 'games',
'localField' => '_id',
'foreignField' => 'slug',
'as' => 'game',
],
],
['$unwind' => '$game'],
[
'$addFields' => [
'deal_rating' => [
'$cond' => [
'if' => ['$gt' => ['$best_price', 0]],
'then' => ['$divide' => ['$game.all_time_low.price', '$best_price']],
'else' => 0,
],
],
'ends_within' => [
'$cond' => [
'if' => ['$ne' => ['$best_expiry', null]],
'then' => ['$subtract' => ['$best_expiry', '$$NOW']],
'else' => 86400000 * 365,
],
],
],
],
];
if ($mode === 'hl') {
$pipeline[] = ['$match' => ['best_hl' => true]];
}
if ($mode === 'ending') {
$pipeline[] = ['$match' => ['ends_within' => ['$lte' => 7 * 86400000]]];
}
$pipeline[] = ['$sort' => $sort];
$pipeline[] = ['$limit' => $limit];
return Mongo::collection('deals')->aggregate($pipeline)->toArray();
}
/**
* Most wanted / new releases / upcoming games (game-only lists).
*/
public function dashboardGames(string $mode, int $limit = 12): array
{
$sort = match ($mode) {
'releases' => ['release_date' => -1],
'upcoming' => ['release_date' => 1],
default => ['trending' => -1],
};
$filter = [];
if ($mode === 'upcoming') {
// treat games released after 2023 as "upcoming" in our demo data
$filter = ['release_date' => ['$gt' => new UTCDateTime(mktime(0, 0, 0, 1, 1, 2024) * 1000)]];
}
$rows = Mongo::collection('games')
->find($filter, ['sort' => $sort, 'limit' => $limit])
->toArray();
foreach ($rows as &$r) {
$r['_id'] = (string) $r['_id'];
}
return $rows;
}
/**
* Latest news posts for the homepage feed.
*/
public function recentNews(int $limit = 6): array
{
return Mongo::collection('news')
->find([], ['sort' => ['date' => -1], 'limit' => $limit])
->toArray();
}
/**
* Bundles that include this game.
*/
public function bundlesFor(string $slug): array
{
return Mongo::collection('bundles')
->find(['games' => $slug], ['sort' => ['price' => 1]])
->toArray();
}
/**
* Franchises containing this game.
*/
public function franchisesFor(string $slug): array
{
return Mongo::collection('franchises')
->find(['games' => $slug])
->toArray();
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Libraries\Mongo;
class StoreModel
{
private ?array $all = null;
/** @return array<int, array> */
public function all(): array
{
if ($this->all === null) {
$this->all = Mongo::collection('stores')->find([], ['sort' => ['kind' => 1, 'name' => 1]])->toArray();
}
return $this->all;
}
/** @return array<string, array> code => store */
public function map(): array
{
$map = [];
foreach ($this->all() as $s) {
$map[$s['code']] = $s;
}
return $map;
}
}
View File
+102
View File
@@ -0,0 +1,102 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<div class="mb-8">
<h1 class="text-2xl font-extrabold text-white tracking-tight">GG.deals API</h1>
<p class="text-sm text-muted mt-1">
Access real-time deals, discounts, bundles, and historical low prices — perfect for bots, apps, websites, side projects, and commercial platforms.
</p>
</div>
<div class="grid lg:grid-cols-3 gap-6 mb-8">
<!-- API key card -->
<div class="bg-panel border border-line rounded-2xl p-6 lg:col-span-1">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-4">Get your API key</h2>
<p class="text-sm text-muted mb-4">
Find the lowest prices for <span class="text-zinc-200 font-semibold"><?= number_format($stats['games']) ?> games</span> across
<span class="text-zinc-200 font-semibold"><?= $stats['stores'] ?> stores</span>. Check historical low prices of digital games.
</p>
<div class="flex items-center gap-3 mb-4">
<div class="flex-1 bg-page border border-line rounded-lg px-3 py-2.5 font-mono text-xs text-muted truncate">demo-key-<?= substr(md5((string) time()), 0, 12) ?></div>
<button @click="navigator.clipboard.writeText(document.querySelector('#apikey').textContent.trim()); $el.textContent='✓'"
class="px-3 py-2.5 rounded-lg bg-accent text-accent-ink text-xs font-bold hover:bg-accent/90 transition-colors shrink-0">Copy</button>
</div>
<p id="apikey" class="hidden">demo-key-<?= substr(md5((string) time()), 0, 12) ?></p>
<p class="text-xs text-muted leading-relaxed">Integrate using simple HTTP requests. Free for non-commercial use.</p>
</div>
<!-- endpoint docs -->
<div class="lg:col-span-2 space-y-4">
<div class="bg-card border border-line rounded-2xl overflow-hidden">
<div class="px-5 py-4 border-b border-line flex items-center justify-between">
<div class="flex items-center gap-3">
<span class="w-2 h-2 rounded-full bg-accent"></span>
<h2 class="text-sm font-bold text-zinc-200">Game Prices API</h2>
</div>
<span class="kind-tag kind-official">GET</span>
</div>
<div class="p-5">
<p class="text-sm text-muted mb-3">Retrieve the lowest prices by Steam App ID.</p>
<div class="bg-page border border-line rounded-xl p-4 font-mono text-xs text-zinc-200 mb-4 break-all">
<span class="text-accent">GET</span> /api/prices?appid=<span class="text-amber-300">1245620</span>
</div>
<div class="bg-page border border-line rounded-xl p-4 font-mono text-[11px] text-zinc-300 overflow-x-auto">
<pre>{
"game": {
"title": "Elden Ring",
"slug": "elden-ring",
"steam_appid": 1245620,
"regular_price": 59.99,
"best_official": { "price": 40.67, "store": "fanatical", "cut": 32 },
"best_keyshop": { "price": 32.14, "store": "eneba", "cut": 46 },
"all_time_low": { "price": 35.99, "store": "kinguin", "date": "2026-03-24" },
"active_deals": 11,
"metacritic": 96
}
}</pre>
</div>
</div>
</div>
<div class="grid sm:grid-cols-2 gap-4">
<div class="bg-card border border-line rounded-xl p-5">
<div class="flex items-center gap-2 mb-2">
<span class="text-lg">🔌</span>
<span class="text-sm font-bold text-zinc-100">Browser extension</span>
</div>
<p class="text-xs text-muted leading-relaxed">Instantly view GG.deals price comparisons while browsing game stores.</p>
</div>
<div class="bg-card border border-line rounded-xl p-5">
<div class="flex items-center gap-2 mb-2">
<span class="text-lg">✉️</span>
<span class="text-sm font-bold text-zinc-100">Suggest an endpoint</span>
</div>
<p class="text-xs text-muted leading-relaxed">Write to us — we'll get back to you shortly!</p>
</div>
</div>
</div>
</div>
<!-- live test -->
<div class="bg-panel border border-line rounded-2xl p-6 mb-8" x-data="{ appid: '1245620', result: null, loading: false }">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-4">Try it live</h2>
<div class="flex flex-wrap items-center gap-3 mb-4">
<input x-model="appid" type="number" placeholder="Steam App ID (e.g. 1245620)"
class="filter-input flex-1 min-w-[220px]">
<button @click="async () => { loading = true; try { const r = await fetch('/api/prices?appid=' + appid); result = { status: r.status, body: await r.json() }; } catch(e) { result = { status: 0, body: { error: e.message } }; } loading = false; }"
class="bg-accent text-accent-ink font-bold text-sm py-2.5 px-6 rounded-lg hover:bg-accent/90 transition-colors">
Send request
</button>
</div>
<div x-show="loading" class="text-sm text-muted">Loading…</div>
<template x-if="result">
<div class="bg-page border border-line rounded-xl p-4 font-mono text-[11px]">
<div class="mb-2">
<span class="kind-tag" :class="result.status === 200 ? 'kind-official' : 'kind-keyshop'" x-text="'HTTP ' + result.status"></span>
</div>
<pre x-text="JSON.stringify(result.body, null, 2)" class="text-zinc-300 overflow-x-auto"></pre>
</div>
</template>
</div>
<?= $this->endSection() ?>
+66
View File
@@ -0,0 +1,66 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<div class="text-xs text-muted mb-4 flex items-center gap-1.5">
<a href="/news" class="hover:text-accent">News</a>
<span></span>
<span class="text-zinc-400">Bundles</span>
</div>
<!-- bundle header -->
<div class="bg-panel border border-line rounded-2xl p-6 mb-6">
<div class="flex flex-col lg:flex-row lg:items-center gap-5">
<div class="flex-1 min-w-0">
<span class="kind-tag kind-keyshop mb-2 inline-block">Bundle</span>
<h1 class="text-2xl font-extrabold text-white tracking-tight leading-tight"><?= esc($bundle['title']) ?></h1>
<p class="text-sm text-muted mt-2 leading-relaxed max-w-2xl"><?= esc($bundle['desc']) ?></p>
<div class="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted">
<span><span class="text-zinc-300 font-semibold"><?= (int) $bundle['game_count'] ?></span> games</span>
<span>Regular value <span class="text-zinc-300 line-through"><?= money((float) $bundle['regular']) ?></span></span>
<span>You save <span class="text-accent font-bold">-<?= (int) round((1 - (float) $bundle['price'] / (float) $bundle['regular']) * 100) ?>%</span></span>
</div>
</div>
<div class="lg:w-[280px] shrink-0 bg-card border border-line rounded-xl p-4">
<div class="text-[11px] font-bold uppercase tracking-wider text-muted">Bundle price</div>
<div class="mt-2 flex items-baseline gap-2">
<span class="text-3xl font-extrabold text-accent"><?= money((float) $bundle['price']) ?></span>
<span class="text-xs text-muted line-through"><?= money((float) $bundle['regular']) ?></span>
</div>
<?php $bStore = $stores[$bundle['store']] ?? null; ?>
<div class="mt-2 flex items-center gap-1.5 text-xs text-muted">
<?php if ($bStore): ?><?= view('partials/store_badge', ['store' => $bStore]) ?><?php endif; ?>
<span><?= esc($bStore['name'] ?? '') ?></span>
</div>
<a href="https://www.google.com/search?q=<?= rawurlencode('buy ' . $bundle['title'] . ' bundle') ?>" target="_blank" rel="nofollow noopener"
class="mt-4 block text-center bg-accent text-accent-ink font-extrabold text-sm py-3 rounded-lg hover:bg-accent/90 transition-colors">
Get the bundle →
</a>
<?php if ($bundle['expires'] instanceof MongoDB\BSON\UTCDateTime): ?>
<div class="mt-2 text-center text-[11px] text-amber-400/90">
ends in <?= max(1, (int) floor(($bundle['expires']->toDateTime()->getTimestamp() - time()) / 86400)) ?> days
</div>
<?php endif; ?>
</div>
</div>
</div>
<!-- games in bundle -->
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-3">Games in this bundle</h2>
<div class="grid sm:grid-cols-2 gap-2.5 mb-8">
<?php foreach ($games as $g): ?>
<div class="flex items-center gap-3 bg-card border border-line rounded-xl p-2.5 hover:border-accent/40 transition-colors group">
<a href="/game/<?= $g['slug'] ?>" class="shrink-0 rounded-md overflow-hidden ring-1 ring-line">
<img src="<?= esc($g['cover']['file']) ?>" alt="" class="w-[104px] h-[49px] object-cover" loading="lazy">
</a>
<div class="min-w-0 flex-1">
<a href="/game/<?= $g['slug'] ?>" class="block text-[13px] font-semibold text-zinc-100 truncate group-hover:text-accent"><?= esc($g['title']) ?></a>
<div class="text-[11px] text-muted mt-0.5">
<span class="score-chip mr-1">MC <?= (int) $g['score'] ?></span>
<span><?= money($g['base_price']) ?></span>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?= $this->endSection() ?>
+7
View File
@@ -0,0 +1,7 @@
<?php
use CodeIgniter\CLI\CLI;
CLI::error('ERROR: ' . $code);
CLI::write($message);
CLI::newLine();
+65
View File
@@ -0,0 +1,65 @@
<?php
use CodeIgniter\CLI\CLI;
// The main Exception
CLI::write('[' . $exception::class . ']', 'light_gray', 'red');
CLI::write($message);
CLI::write('at ' . CLI::color(clean_path($exception->getFile()) . ':' . $exception->getLine(), 'green'));
CLI::newLine();
$last = $exception;
while ($prevException = $last->getPrevious()) {
$last = $prevException;
CLI::write(' Caused by:');
CLI::write(' [' . $prevException::class . ']', 'red');
CLI::write(' ' . $prevException->getMessage());
CLI::write(' at ' . CLI::color(clean_path($prevException->getFile()) . ':' . $prevException->getLine(), 'green'));
CLI::newLine();
}
// The backtrace
if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) {
$backtraces = $last->getTrace();
if ($backtraces) {
CLI::write('Backtrace:', 'green');
}
foreach ($backtraces as $i => $error) {
$padFile = ' '; // 4 spaces
$padClass = ' '; // 7 spaces
$c = str_pad($i + 1, 3, ' ', STR_PAD_LEFT);
if (isset($error['file'])) {
$filepath = clean_path($error['file']) . ':' . $error['line'];
CLI::write($c . $padFile . CLI::color($filepath, 'yellow'));
} else {
CLI::write($c . $padFile . CLI::color('[internal function]', 'yellow'));
}
$function = '';
if (isset($error['class'])) {
$type = ($error['type'] === '->') ? '()' . $error['type'] : $error['type'];
$function .= $padClass . $error['class'] . $type . $error['function'];
} elseif (! isset($error['class']) && isset($error['function'])) {
$function .= $padClass . $error['function'];
}
$args = implode(', ', array_map(static fn ($value): string => match (true) {
is_object($value) => 'Object(' . $value::class . ')',
is_array($value) => $value !== [] ? '[...]' : '[]',
$value === null => 'null', // return the lowercased version
default => var_export($value, true),
}, array_values($error['args'] ?? [])));
$function .= '(' . $args . ')';
CLI::write($function);
CLI::newLine();
}
}
+5
View File
@@ -0,0 +1,5 @@
<?php
// On the CLI, we still want errors in productions
// so just use the exception template.
include __DIR__ . '/error_exception.php';
+194
View File
@@ -0,0 +1,194 @@
:root {
--main-bg-color: #fff;
--main-text-color: #555;
--dark-text-color: #222;
--light-text-color: #c7c7c7;
--brand-primary-color: #DC4814;
--light-bg-color: #ededee;
--dark-bg-color: #404040;
}
body {
height: 100%;
background: var(--main-bg-color);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
color: var(--main-text-color);
font-weight: 300;
margin: 0;
padding: 0;
}
h1 {
font-weight: lighter;
font-size: 3rem;
color: var(--dark-text-color);
margin: 0;
}
h1.headline {
margin-top: 20%;
font-size: 5rem;
}
.text-center {
text-align: center;
}
p.lead {
font-size: 1.6rem;
}
.container {
max-width: 75rem;
margin: 0 auto;
padding: 1rem;
}
.header {
background: var(--light-bg-color);
color: var(--dark-text-color);
margin-top: 2.17rem;
}
.header .container {
padding: 1rem;
}
.header h1 {
font-size: 2.5rem;
font-weight: 500;
}
.header p {
font-size: 1.2rem;
margin: 0;
line-height: 2.5;
}
.header a {
color: var(--brand-primary-color);
margin-left: 2rem;
display: none;
text-decoration: none;
}
.header:hover a {
display: inline;
}
.environment {
background: var(--brand-primary-color);
color: var(--main-bg-color);
text-align: center;
padding: calc(4px + 0.2083vw);
width: 100%;
top: 0;
position: fixed;
}
.source {
background: #343434;
color: var(--light-text-color);
padding: 0.5em 1em;
border-radius: 5px;
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
font-size: 0.85rem;
margin: 0;
overflow-x: scroll;
}
.source span.line {
line-height: 1.4;
}
.source span.line .number {
color: #666;
}
.source .line .highlight {
display: block;
background: var(--dark-text-color);
color: var(--light-text-color);
}
.source span.highlight .number {
color: #fff;
}
.tabs {
list-style: none;
list-style-position: inside;
margin: 0;
padding: 0;
margin-bottom: -1px;
}
.tabs li {
display: inline;
}
.tabs a:link,
.tabs a:visited {
padding: 0 1rem;
line-height: 2.7;
text-decoration: none;
color: var(--dark-text-color);
background: var(--light-bg-color);
border: 1px solid rgba(0,0,0,0.15);
border-bottom: 0;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
display: inline-block;
}
.tabs a:hover {
background: var(--light-bg-color);
border-color: rgba(0,0,0,0.15);
}
.tabs a.active {
background: var(--main-bg-color);
color: var(--main-text-color);
}
.tab-content {
background: var(--main-bg-color);
border: 1px solid rgba(0,0,0,0.15);
}
.content {
padding: 1rem;
}
.hide {
display: none;
}
.alert {
margin-top: 2rem;
display: block;
text-align: center;
line-height: 3.0;
background: #d9edf7;
border: 1px solid #bcdff1;
border-radius: 5px;
color: #31708f;
}
table {
width: 100%;
overflow: hidden;
}
th {
text-align: left;
border-bottom: 1px solid #e7e7e7;
padding-bottom: 0.5rem;
}
td {
padding: 0.2rem 0.5rem 0.2rem 0;
}
tr:hover td {
background: #f1f1f1;
}
td pre {
white-space: pre-wrap;
}
.trace a {
color: inherit;
}
.trace table {
width: auto;
}
.trace tr td:first-child {
min-width: 5em;
font-weight: bold;
}
.trace td {
background: var(--light-bg-color);
padding: 0 1rem;
}
.trace td pre {
margin: 0;
}
.args {
display: none;
}
+116
View File
@@ -0,0 +1,116 @@
var tabLinks = new Array();
var contentDivs = new Array();
function init()
{
// Grab the tab links and content divs from the page
var tabListItems = document.getElementById('tabs').childNodes;
console.log(tabListItems);
for (var i = 0; i < tabListItems.length; i ++)
{
if (tabListItems[i].nodeName == "LI")
{
var tabLink = getFirstChildWithTagName(tabListItems[i], 'A');
var id = getHash(tabLink.getAttribute('href'));
tabLinks[id] = tabLink;
contentDivs[id] = document.getElementById(id);
}
}
// Assign onclick events to the tab links, and
// highlight the first tab
var i = 0;
for (var id in tabLinks)
{
tabLinks[id].onclick = showTab;
tabLinks[id].onfocus = function () {
this.blur()
};
if (i == 0)
{
tabLinks[id].className = 'active';
}
i ++;
}
// Hide all content divs except the first
var i = 0;
for (var id in contentDivs)
{
if (i != 0)
{
console.log(contentDivs[id]);
contentDivs[id].className = 'content hide';
}
i ++;
}
}
function showTab()
{
var selectedId = getHash(this.getAttribute('href'));
// Highlight the selected tab, and dim all others.
// Also show the selected content div, and hide all others.
for (var id in contentDivs)
{
if (id == selectedId)
{
tabLinks[id].className = 'active';
contentDivs[id].className = 'content';
}
else
{
tabLinks[id].className = '';
contentDivs[id].className = 'content hide';
}
}
// Stop the browser following the link
return false;
}
function getFirstChildWithTagName(element, tagName)
{
for (var i = 0; i < element.childNodes.length; i ++)
{
if (element.childNodes[i].nodeName == tagName)
{
return element.childNodes[i];
}
}
}
function getHash(url)
{
var hashPos = url.lastIndexOf('#');
return url.substring(hashPos + 1);
}
function toggle(elem)
{
elem = document.getElementById(elem);
if (elem.style && elem.style['display'])
{
// Only works with the "style" attr
var disp = elem.style['display'];
}
else if (elem.currentStyle)
{
// For MSIE, naturally
var disp = elem.currentStyle['display'];
}
else if (window.getComputedStyle)
{
// For most other browsers
var disp = document.defaultView.getComputedStyle(elem, null).getPropertyValue('display');
}
// Toggle the state of the "display" style
elem.style.display = disp == 'block' ? 'none' : 'block';
return false;
}
+84
View File
@@ -0,0 +1,84 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= lang('Errors.badRequest') ?></title>
<style>
div.logo {
height: 200px;
width: 155px;
display: inline-block;
opacity: 0.08;
position: absolute;
top: 2rem;
left: 50%;
margin-left: -73px;
}
body {
height: 100%;
background: #fafafa;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #777;
font-weight: 300;
}
h1 {
font-weight: lighter;
letter-spacing: normal;
font-size: 3rem;
margin-top: 0;
margin-bottom: 0;
color: #222;
}
.wrap {
max-width: 1024px;
margin: 5rem auto;
padding: 2rem;
background: #fff;
text-align: center;
border: 1px solid #efefef;
border-radius: 0.5rem;
position: relative;
}
pre {
white-space: normal;
margin-top: 1.5rem;
}
code {
background: #fafafa;
border: 1px solid #efefef;
padding: 0.5rem 1rem;
border-radius: 5px;
display: block;
}
p {
margin-top: 1.5rem;
}
.footer {
margin-top: 2rem;
border-top: 1px solid #efefef;
padding: 1em 2em 0 2em;
font-size: 85%;
color: #999;
}
a:active,
a:link,
a:visited {
color: #dd4814;
}
</style>
</head>
<body>
<div class="wrap">
<h1>400</h1>
<p>
<?php if (ENVIRONMENT !== 'production') : ?>
<?= nl2br(esc($message)) ?>
<?php else : ?>
<?= lang('Errors.sorryBadRequest') ?>
<?php endif; ?>
</p>
</div>
</body>
</html>
+84
View File
@@ -0,0 +1,84 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= lang('Errors.pageNotFound') ?></title>
<style>
div.logo {
height: 200px;
width: 155px;
display: inline-block;
opacity: 0.08;
position: absolute;
top: 2rem;
left: 50%;
margin-left: -73px;
}
body {
height: 100%;
background: #fafafa;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #777;
font-weight: 300;
}
h1 {
font-weight: lighter;
letter-spacing: normal;
font-size: 3rem;
margin-top: 0;
margin-bottom: 0;
color: #222;
}
.wrap {
max-width: 1024px;
margin: 5rem auto;
padding: 2rem;
background: #fff;
text-align: center;
border: 1px solid #efefef;
border-radius: 0.5rem;
position: relative;
}
pre {
white-space: normal;
margin-top: 1.5rem;
}
code {
background: #fafafa;
border: 1px solid #efefef;
padding: 0.5rem 1rem;
border-radius: 5px;
display: block;
}
p {
margin-top: 1.5rem;
}
.footer {
margin-top: 2rem;
border-top: 1px solid #efefef;
padding: 1em 2em 0 2em;
font-size: 85%;
color: #999;
}
a:active,
a:link,
a:visited {
color: #dd4814;
}
</style>
</head>
<body>
<div class="wrap">
<h1>404</h1>
<p>
<?php if (ENVIRONMENT !== 'production') : ?>
<?= nl2br(esc($message)) ?>
<?php else : ?>
<?= lang('Errors.sorryCannotFind') ?>
<?php endif; ?>
</p>
</div>
</body>
</html>
+429
View File
@@ -0,0 +1,429 @@
<?php
use CodeIgniter\HTTP\Header;
use CodeIgniter\CodeIgniter;
$errorId = uniqid('error', true);
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title><?= esc($title) ?></title>
<style>
<?= preg_replace('#[\r\n\t ]+#', ' ', file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.css')) ?>
</style>
<script>
<?= file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.js') ?>
</script>
</head>
<body onload="init()">
<!-- Header -->
<div class="header">
<div class="environment">
Displayed at <?= esc(date('H:i:s')) ?> &mdash;
PHP: <?= esc(PHP_VERSION) ?> &mdash;
CodeIgniter: <?= esc(CodeIgniter::CI_VERSION) ?> --
Environment: <?= ENVIRONMENT ?>
</div>
<div class="container">
<h1><?= esc($title), esc($exception->getCode() ? ' #' . $exception->getCode() : '') ?></h1>
<p>
<?= nl2br(esc($exception->getMessage())) ?>
<a href="https://www.duckduckgo.com/?q=<?= urlencode($title . ' ' . preg_replace('#\'.*\'|".*"#Us', '', $exception->getMessage())) ?>"
rel="noreferrer" target="_blank">search &rarr;</a>
</p>
</div>
</div>
<!-- Source -->
<div class="container">
<p><b><?= esc(clean_path($file)) ?></b> at line <b><?= esc($line) ?></b></p>
<?php if (is_file($file)) : ?>
<div class="source">
<?= static::highlightFile($file, $line, 15); ?>
</div>
<?php endif; ?>
</div>
<div class="container">
<?php
$last = $exception;
while ($prevException = $last->getPrevious()) {
$last = $prevException;
?>
<pre>
Caused by:
<?= esc($prevException::class), esc($prevException->getCode() ? ' #' . $prevException->getCode() : '') ?>
<?= nl2br(esc($prevException->getMessage())) ?>
<a href="https://www.duckduckgo.com/?q=<?= urlencode($prevException::class . ' ' . preg_replace('#\'.*\'|".*"#Us', '', $prevException->getMessage())) ?>"
rel="noreferrer" target="_blank">search &rarr;</a>
<?= esc(clean_path($prevException->getFile()) . ':' . $prevException->getLine()) ?>
</pre>
<?php
}
?>
</div>
<?php if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) : ?>
<div class="container">
<ul class="tabs" id="tabs">
<li><a href="#backtrace">Backtrace</a></li>
<li><a href="#server">Server</a></li>
<li><a href="#request">Request</a></li>
<li><a href="#response">Response</a></li>
<li><a href="#files">Files</a></li>
<li><a href="#memory">Memory</a></li>
</ul>
<div class="tab-content">
<!-- Backtrace -->
<div class="content" id="backtrace">
<ol class="trace">
<?php foreach ($trace as $index => $row) : ?>
<li>
<p>
<!-- Trace info -->
<?php if (isset($row['file']) && is_file($row['file'])) : ?>
<?php
if (isset($row['function']) && in_array($row['function'], ['include', 'include_once', 'require', 'require_once'], true)) {
echo esc($row['function'] . ' ' . clean_path($row['file']));
} else {
echo esc(clean_path($row['file']) . ' : ' . $row['line']);
}
?>
<?php else: ?>
{PHP internal code}
<?php endif; ?>
<!-- Class/Method -->
<?php if (isset($row['class'])) : ?>
&nbsp;&nbsp;&mdash;&nbsp;&nbsp;<?= esc($row['class'] . $row['type'] . $row['function']) ?>
<?php if (! empty($row['args'])) : ?>
<?php $argsId = $errorId . 'args' . $index ?>
( <a href="#" onclick="return toggle('<?= esc($argsId, 'attr') ?>');">arguments</a> )
<div class="args" id="<?= esc($argsId, 'attr') ?>">
<table cellspacing="0">
<?php
$params = null;
// Reflection by name is not available for closure function
if (! str_ends_with($row['function'], '}')) {
$mirror = isset($row['class']) ? new ReflectionMethod($row['class'], $row['function']) : new ReflectionFunction($row['function']);
$params = $mirror->getParameters();
}
foreach ($row['args'] as $key => $value) : ?>
<tr>
<td><code><?= esc(isset($params[$key]) ? '$' . $params[$key]->name : "#{$key}") ?></code></td>
<td><pre><?= esc(print_r($value, true)) ?></pre></td>
</tr>
<?php endforeach ?>
</table>
</div>
<?php else : ?>
()
<?php endif; ?>
<?php endif; ?>
<?php if (! isset($row['class']) && isset($row['function'])) : ?>
&nbsp;&nbsp;&mdash;&nbsp;&nbsp; <?= esc($row['function']) ?>()
<?php endif; ?>
</p>
<!-- Source? -->
<?php if (isset($row['file']) && is_file($row['file']) && isset($row['class'])) : ?>
<div class="source">
<?= static::highlightFile($row['file'], $row['line']) ?>
</div>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ol>
</div>
<!-- Server -->
<div class="content" id="server">
<?php foreach (['_SERVER', '_SESSION'] as $var) : ?>
<?php
if (empty($GLOBALS[$var]) || ! is_array($GLOBALS[$var])) {
continue;
} ?>
<h3>$<?= esc($var) ?></h3>
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($GLOBALS[$var] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endforeach ?>
<!-- Constants -->
<?php $constants = get_defined_constants(true); ?>
<?php if (! empty($constants['user'])) : ?>
<h3>Constants</h3>
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($constants['user'] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Request -->
<div class="content" id="request">
<?php $request = service('request'); ?>
<table>
<tbody>
<tr>
<td style="width: 10em">Path</td>
<td><?= esc($request->getUri()) ?></td>
</tr>
<tr>
<td>HTTP Method</td>
<td><?= esc($request->getMethod()) ?></td>
</tr>
<tr>
<td>IP Address</td>
<td><?= esc($request->getIPAddress()) ?></td>
</tr>
<tr>
<td style="width: 10em">Is AJAX Request?</td>
<td><?= $request->isAJAX() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>Is CLI Request?</td>
<td><?= $request->isCLI() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>Is Secure Request?</td>
<td><?= $request->isSecure() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>User Agent</td>
<td><?= esc($request->getUserAgent()->getAgentString()) ?></td>
</tr>
</tbody>
</table>
<?php $empty = true; ?>
<?php foreach (['_GET', '_POST', '_COOKIE'] as $var) : ?>
<?php
if (empty($GLOBALS[$var]) || ! is_array($GLOBALS[$var])) {
continue;
} ?>
<?php $empty = false; ?>
<h3>$<?= esc($var) ?></h3>
<table style="width: 100%">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($GLOBALS[$var] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endforeach ?>
<?php if ($empty) : ?>
<div class="alert">
No $_GET, $_POST, or $_COOKIE Information to show.
</div>
<?php endif; ?>
<?php $headers = $request->headers(); ?>
<?php if (! empty($headers)) : ?>
<h3>Headers</h3>
<table>
<thead>
<tr>
<th>Header</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($headers as $name => $value) : ?>
<tr>
<td><?= esc($name, 'html') ?></td>
<td>
<?php
if ($value instanceof Header) {
echo esc($value->getValueLine(), 'html');
} else {
foreach ($value as $i => $header) {
echo ' ('. $i+1 . ') ' . esc($header->getValueLine(), 'html');
}
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Response -->
<?php
$response = service('response');
$response->setStatusCode(http_response_code());
?>
<div class="content" id="response">
<table>
<tr>
<td style="width: 15em">Response Status</td>
<td><?= esc($response->getStatusCode() . ' - ' . $response->getReasonPhrase()) ?></td>
</tr>
</table>
<?php $headers = $response->headers(); ?>
<?php if (! empty($headers)) : ?>
<h3>Headers</h3>
<table>
<thead>
<tr>
<th>Header</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($headers as $name => $value) : ?>
<tr>
<td><?= esc($name, 'html') ?></td>
<td>
<?php
if ($value instanceof Header) {
echo esc($response->getHeaderLine($name), 'html');
} else {
foreach ($value as $i => $header) {
echo ' ('. $i+1 . ') ' . esc($header->getValueLine(), 'html');
}
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Files -->
<div class="content" id="files">
<?php $files = get_included_files(); ?>
<ol>
<?php foreach ($files as $file) :?>
<li><?= esc(clean_path($file)) ?></li>
<?php endforeach ?>
</ol>
</div>
<!-- Memory -->
<div class="content" id="memory">
<table>
<tbody>
<tr>
<td>Memory Usage</td>
<td><?= esc(static::describeMemory(memory_get_usage(true))) ?></td>
</tr>
<tr>
<td style="width: 12em">Peak Memory Usage:</td>
<td><?= esc(static::describeMemory(memory_get_peak_usage(true))) ?></td>
</tr>
<tr>
<td>Memory Limit:</td>
<td><?= esc(ini_get('memory_limit')) ?></td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /tab-content -->
</div> <!-- /container -->
<?php endif; ?>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title><?= lang('Errors.whoops') ?></title>
<style>
<?= preg_replace('#[\r\n\t ]+#', ' ', file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.css')) ?>
</style>
</head>
<body>
<div class="container text-center">
<h1 class="headline"><?= lang('Errors.whoops') ?></h1>
<p class="lead"><?= lang('Errors.weHitASnag') ?></p>
</div>
</body>
</html>
+45
View File
@@ -0,0 +1,45 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<div class="max-w-3xl mb-8">
<h1 class="text-2xl font-extrabold text-white tracking-tight mb-4">Frequently Asked Questions</h1>
<div class="space-y-3" x-data="{ open: null }">
<?php
$faqs = [
['What is GG.deals?', 'GG.deals is a price comparison service for digital video games. We track prices across official stores and keyshop marketplaces, maintain historical price data, and help you find the best deal for any PC, PlayStation, Xbox or Switch game.'],
['Are keyshops safe?', 'Keyshops are third-party marketplaces that resell game keys. While most keyshop sellers are legitimate, buying from them carries some risk — keys may be region-locked or purchased with stolen payment methods. We mark keyshop offers clearly and let you disable them entirely in settings.'],
['What is a historical low?', 'A historical low (all-time low) is the lowest price ever recorded for a game on GG.deals. We highlight deals that reach this price with a special "New HL" badge so you know when a deal is truly exceptional.'],
['How does the deal rating work?', 'The deal rating compares the current best price to the game\'s historical low. Deals within 15% of the all-time low get a "Hot" rating, within 40% get "Good", and further away get "Fair" or "High price".'],
['What is a voucher code?', 'Voucher codes are discount codes offered by stores. We list active vouchers on the Vouchers page — copy the code and apply it at checkout to save extra on top of the listed price.'],
['How do I activate a CD key?', 'After buying a key, open the corresponding store client (Steam, GOG, Epic, etc.), go to "Activate a Product" or "Redeem Code", and enter the key. Each platform has a dedicated tutorial on our site.'],
['Can I import my game collection?', 'Yes! Create a free account and connect your Steam profile to automatically track which games you own, plus mark games as owned, wishlisted or ignored for better filtering.'],
['Does GG.deals have an API?', 'Yes — our Game Prices API lets you retrieve the lowest prices by Steam App ID for any game we track. See the API page for documentation and a live demo.'],
];
foreach ($faqs as $i => [$q, $a]): ?>
<div class="bg-card border border-line rounded-xl overflow-hidden">
<button @click="open = open === <?= $i ?> ? null : <?= $i ?>" class="w-full flex items-center justify-between px-5 py-4 text-left hover:bg-elev/50 transition-colors">
<span class="text-[15px] font-semibold text-zinc-100"><?= esc($q) ?></span>
<svg class="w-4 h-4 text-muted transition-transform" :class="open === <?= $i ?> ? 'rotate-180' : ''" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg>
</button>
<div x-show="open === <?= $i ?>" x-cloak class="px-5 pb-4">
<p class="text-sm text-muted leading-relaxed"><?= esc($a) ?></p>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<div class="bg-panel border border-line rounded-2xl p-6 max-w-3xl">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-4">Tutorials</h2>
<div class="grid sm:grid-cols-2 gap-2.5">
<?php foreach (['activate-steam', 'activate-gog', 'activate-epic', 'activate-origin', 'activate-uplay', 'keyshops-risks'] as $t): ?>
<a href="/page/<?= $t ?>" class="flex items-center gap-3 bg-card border border-line rounded-xl px-4 py-3 hover:border-accent/40 transition-colors group">
<span class="text-lg">📖</span>
<span class="text-sm font-semibold text-zinc-100 group-hover:text-accent"><?= ucwords(str_replace('-', ' ', $t)) ?></span>
</a>
<?php endforeach; ?>
</div>
</div>
<?= $this->endSection() ?>
+40
View File
@@ -0,0 +1,40 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<div class="mb-6">
<h1 class="text-2xl font-extrabold text-white tracking-tight"><?= esc($franchise['name']) ?> Franchise</h1>
<p class="text-sm text-muted mt-1">All games in the <?= esc($franchise['name']) ?> series with current best prices.</p>
</div>
<div class="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 mb-8">
<?php foreach ($games as $g): ?>
<a href="/game/<?= $g['slug'] ?>" class="group bg-card border border-line rounded-xl overflow-hidden hover:border-accent/50 transition-colors">
<div class="relative">
<img src="<?= esc($g['cover']['file']) ?>" alt="<?= esc($g['title']) ?>" class="w-full h-[105px] object-cover group-hover:opacity-90 transition-opacity">
<span class="absolute top-2 right-2 score-chip">MC <?= (int) $g['score'] ?></span>
</div>
<div class="p-3">
<div class="text-sm font-semibold text-zinc-100 truncate group-hover:text-accent"><?= esc($g['title']) ?></div>
<div class="mt-1 flex items-center justify-between text-xs">
<span class="text-muted"><?= money($g['base_price']) ?></span>
<span class="text-accent font-extrabold"><?= money(min($g['best_official']['price'], $g['best_keyshop']['price'])) ?></span>
</div>
</div>
</a>
<?php endforeach; ?>
</div>
<?php if ($allFranchises !== []): ?>
<div class="bg-panel border border-line rounded-2xl p-5">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-3">All franchises</h2>
<div class="flex flex-wrap gap-2">
<?php foreach ($allFranchises as $f): ?>
<a href="/franchise/<?= esc($f['slug']) ?>" class="chip hover:border-accent/60 transition-colors">
<?= esc($f['name']) ?> <span class="text-muted">(<?= count($f['games']) ?>)</span>
</a>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
<?= $this->endSection() ?>
+18
View File
@@ -0,0 +1,18 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<div class="mb-6">
<h1 class="text-2xl font-extrabold text-white tracking-tight">Franchises</h1>
<p class="text-sm text-muted mt-1">Browse game series and franchises.</p>
</div>
<div class="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
<?php foreach ($franchises as $f): ?>
<a href="/franchise/<?= esc($f['slug']) ?>" class="group bg-card border border-line rounded-xl p-4 hover:border-accent/50 transition-colors">
<div class="text-[15px] font-semibold text-zinc-100 group-hover:text-accent"><?= esc($f['name']) ?></div>
<div class="mt-1 text-xs text-muted"><?= count($f['games']) ?> games</div>
</a>
<?php endforeach; ?>
</div>
<?= $this->endSection() ?>
+601
View File
@@ -0,0 +1,601 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<?php
$hl = $game['all_time_low'];
$hlStore = $stores[$hl['store']] ?? null;
$allDeals = array_merge($deals['official'], $deals['keyshop']);
$bestDeal = $allDeals ? $allDeals[array_key_first($allDeals)] : null; // already sorted by price
$bestStore = $bestDeal ? ($stores[$bestDeal['store_code']] ?? null) : null;
$releaseY = substr((string) bson_date($game['release_date']), -4);
$ratingPct = (int) $game['rating_pct'];
$ratingLabel = $ratingPct >= 90 ? 'Overwhelmingly positive' : ($ratingPct >= 75 ? 'Very positive' : ($ratingPct >= 50 ? 'Mostly positive' : 'Mixed'));
?>
<!-- breadcrumbs -->
<div class="text-xs text-muted mb-4 flex items-center gap-1.5">
<a href="/" class="hover:text-accent">Deals</a>
<span></span>
<span class="text-zinc-400"><?= esc($game['title']) ?></span>
</div>
<!-- ======= game header ======= -->
<div class="bg-panel border border-line rounded-2xl p-5 mb-6">
<div class="flex flex-col lg:flex-row gap-6">
<!-- cover + info -->
<div class="flex gap-5 min-w-0 flex-1">
<img src="<?= esc($game['cover']['file']) ?>" alt="<?= esc($game['title']) ?>"
class="w-[220px] h-[103px] object-cover rounded-xl ring-1 ring-line shrink-0">
<div class="min-w-0">
<h1 class="text-2xl font-extrabold text-white tracking-tight leading-tight"><?= esc($game['title']) ?></h1>
<div class="mt-2 flex flex-wrap items-center gap-2 text-xs">
<span class="score-chip" title="Critic score">MC <?= (int) $game['score'] ?></span>
<span class="chip <?= $ratingPct >= 75 ? 'chip-green' : 'chip-amber' ?>"><?= $ratingLabel ?> · <?= $ratingPct ?>%</span>
<span class="chip"><?= esc($releaseY) ?></span>
<?php foreach (array_slice($game['genres'], 0, 3) as $genre): ?>
<span class="chip"><?= esc($genre) ?></span>
<?php endforeach; ?>
</div>
<div class="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted">
<span><span class="text-zinc-300 font-semibold"><?= count($allDeals) ?></span> active offers</span>
<span>
<span class="text-zinc-300 font-semibold"><?= count($deals['official']) ?></span> official store<?= count($deals['official']) !== 1 ? 's' : '' ?>
· <span class="text-zinc-300 font-semibold"><?= count($deals['keyshop']) ?></span> keyshop<?= count($deals['keyshop']) !== 1 ? 's' : '' ?>
</span>
</div>
<div class="mt-3 flex gap-2">
<button class="chip hover:border-accent/60 flex items-center gap-1.5 cursor-pointer">
<span class="text-accent">🔔</span> Create price alert
</button>
<button @click="$store.gg.toggleWishlist('<?= $game['slug'] ?>', $event)"
:class="$store.gg.inWishlist('<?= $game['slug'] ?>') ? 'border-accent/60 text-accent' : 'hover:border-accent/60'"
class="chip cursor-pointer flex items-center gap-1.5 transition-colors">
<svg class="w-3.5 h-3.5" :fill="$store.gg.inWishlist('<?= $game['slug'] ?>') ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
<span x-text="$store.gg.inWishlist('<?= $game['slug'] ?>') ? 'In wishlist' : 'Wishlist'"></span>
</button>
</div>
</div>
</div>
<!-- best offer panel -->
<?php if ($bestDeal !== null): ?>
<?php $bestRating = deal_rating((float) $hl['price'], (float) $bestDeal['price']); ?>
<div class="lg:w-[340px] shrink-0 bg-card border border-line rounded-xl p-4 flex flex-col">
<div class="text-[11px] font-bold uppercase tracking-wider text-muted">Best current deal</div>
<div class="mt-2.5 flex items-center justify-between gap-3">
<div>
<div class="flex items-baseline gap-2">
<span class="text-3xl font-extrabold text-accent leading-none"><?= money($bestDeal['price']) ?></span>
<?php if ((int) $bestDeal['cut'] > 0): ?>
<span class="cut <?= cut_class((int) $bestDeal['cut']) ?> cut-badge">-<?= (int) $bestDeal['cut'] ?>%</span>
<?php endif; ?>
</div>
<div class="text-xs text-muted line-through mt-1"><?= money($game['base_price']) ?> regular price</div>
</div>
<div class="text-right">
<div class="flex items-center gap-1.5 justify-end">
<?php if ($bestStore): ?><?= view('partials/store_badge', ['store' => $bestStore, 'size' => 'lg']) ?><?php endif; ?>
</div>
<div class="text-xs text-zinc-300 mt-1.5"><?= esc($bestStore['name'] ?? '') ?></div>
<div class="kind-tag <?= $bestDeal['kind'] === 'official' ? 'kind-official' : 'kind-keyshop' ?>">
<?= $bestDeal['kind'] === 'official' ? 'Official store' : 'Keyshop' ?>
</div>
</div>
</div>
<a href="<?= esc($bestDeal['url']) ?>" target="_blank" rel="nofollow noopener"
class="mt-4 block text-center bg-accent text-accent-ink font-extrabold text-sm py-3 rounded-lg hover:bg-accent/90 transition-colors">
Go to store →
</a>
<div class="mt-3 pt-3 border-t border-line/70 text-xs text-muted space-y-1">
<div>
All-time low:
<span class="text-accent font-bold"><?= money($hl['price']) ?></span>
at <span class="text-zinc-300"><?= esc($hlStore['name'] ?? '?') ?></span>
</div>
<div>
Reached <span class="text-zinc-300"><?= time_ago($hl['date']) ?></span> (<?= bson_date($hl['date']) ?>)
</div>
<div class="pt-1"><span class="rating <?= $bestRating['cls'] ?>"><?= $bestRating['label'] ?></span></div>
</div>
</div>
<?php endif; ?>
</div>
</div>
<!-- ======= header price tabs (Current Prices / Historical Low) ======= -->
<div x-data="{ priceTab: 'current' }" class="mb-6">
<div class="flex gap-1 border-b border-line mb-4">
<button @click="priceTab='current'" :class="priceTab==='current' ? 'text-accent border-accent' : 'text-muted border-transparent hover:text-zinc-300'"
class="px-4 py-2.5 text-sm font-bold border-b-2 -mb-px transition-colors">Current Prices</button>
<button @click="priceTab='historical'" :class="priceTab==='historical' ? 'text-accent border-accent' : 'text-muted border-transparent hover:text-zinc-300'"
class="px-4 py-2.5 text-sm font-bold border-b-2 -mb-px transition-colors">Historical Low</button>
</div>
<div x-show="priceTab==='current'" x-cloak>
<div class="grid sm:grid-cols-2 lg:grid-cols-4 gap-3">
<!-- official stores low -->
<div class="bg-card border border-line rounded-xl p-4">
<div class="flex items-center justify-between mb-2">
<span class="kind-tag kind-official">Official Stores</span>
<?php if ((int) $game['best_official']['cut'] > 0): ?>
<span class="cut <?= cut_class((int) $game['best_official']['cut']) ?> cut-badge">-<?= (int) $game['best_official']['cut'] ?>%</span>
<?php endif; ?>
</div>
<div class="flex items-baseline gap-2">
<span class="text-2xl font-extrabold text-accent"><?= money($game['best_official']['price']) ?></span>
<span class="text-xs text-muted line-through"><?= money($game['base_price']) ?></span>
</div>
<div class="mt-1.5 flex items-center gap-1.5 text-xs text-muted">
<?php $offStore = $stores[$game['best_official']['store']] ?? null; ?>
<?php if ($offStore): ?><?= view('partials/store_badge', ['store' => $offStore]) ?><?php endif; ?>
<span><?= esc($offStore['name'] ?? '') ?></span>
</div>
</div>
<!-- keyshops low -->
<div class="bg-card border border-line rounded-xl p-4">
<div class="flex items-center justify-between mb-2">
<span class="kind-tag kind-keyshop">Keyshops</span>
<?php if ((int) $game['best_keyshop']['cut'] > 0): ?>
<span class="cut <?= cut_class((int) $game['best_keyshop']['cut']) ?> cut-badge">-<?= (int) $game['best_keyshop']['cut'] ?>%</span>
<?php endif; ?>
</div>
<div class="flex items-baseline gap-2">
<span class="text-2xl font-extrabold text-accent"><?= money($game['best_keyshop']['price']) ?></span>
<span class="text-xs text-muted line-through"><?= money($game['base_price']) ?></span>
</div>
<div class="mt-1.5 flex items-center gap-1.5 text-xs text-muted">
<?php $keyStore = $stores[$game['best_keyshop']['store']] ?? null; ?>
<?php if ($keyStore): ?><?= view('partials/store_badge', ['store' => $keyStore]) ?><?php endif; ?>
<span><?= esc($keyStore['name'] ?? '') ?></span>
</div>
</div>
<!-- subscriptions -->
<div class="bg-card border border-line rounded-xl p-4">
<span class="kind-tag kind-official mb-2 inline-block">Subscriptions</span>
<?php if ($subscriptions !== []): ?>
<div class="text-2xl font-extrabold text-zinc-100"><?= money((float) $subscriptions[0]['price']) ?></div>
<div class="text-xs text-muted mt-1"><?= esc($subscriptions[0]['name']) ?></div>
<div class="text-[11px] text-muted/70 mt-1">included in the library</div>
<?php else: ?>
<div class="text-sm text-muted">Not available</div>
<?php endif; ?>
</div>
<!-- all-time low -->
<div class="bg-card border border-line rounded-xl p-4">
<span class="kind-tag kind-official mb-2 inline-block">All-time low</span>
<div class="flex items-baseline gap-2">
<span class="text-2xl font-extrabold text-accent"><?= money($hl['price']) ?></span>
<span class="text-xs text-muted"><?= bson_date($hl['date']) ?></span>
</div>
<div class="mt-1.5 flex items-center gap-1.5 text-xs text-muted">
<?php if ($hlStore): ?><?= view('partials/store_badge', ['store' => $hlStore]) ?><?php endif; ?>
<span><?= esc($hlStore['name'] ?? '') ?></span>
</div>
</div>
</div>
</div>
<div x-show="priceTab==='historical'" x-cloak>
<div class="grid sm:grid-cols-2 gap-3">
<div class="bg-card border border-line rounded-xl p-4">
<div class="kind-tag kind-official mb-2 inline-block">Official Stores Low</div>
<div class="text-2xl font-extrabold text-accent"><?= money($game['best_official']['price']) ?></div>
<div class="text-xs text-muted mt-1">Lowest official-store price right now</div>
</div>
<div class="bg-card border border-line rounded-xl p-4">
<div class="kind-tag kind-keyshop mb-2 inline-block">Keyshops Low</div>
<div class="text-2xl font-extrabold text-accent"><?= money($game['best_keyshop']['price']) ?></div>
<div class="text-xs text-muted mt-1">Lowest keyshop price right now</div>
</div>
</div>
</div>
</div>
<!-- ======= tabs ======= -->
<div x-data="gamePage()" class="mb-6">
<div class="flex gap-1 border-b border-line mb-5">
<button @click="tab='deals'" :class="tab==='deals' ? 'text-accent border-accent' : 'text-muted border-transparent hover:text-zinc-300'"
class="px-4 py-2.5 text-sm font-bold border-b-2 -mb-px transition-colors">
All deals (<?= count($allDeals) ?>)
</button>
<button @click="tab='history'; $nextTick(() => initChart())" :class="tab==='history' ? 'text-accent border-accent' : 'text-muted border-transparent hover:text-zinc-300'"
class="px-4 py-2.5 text-sm font-bold border-b-2 -mb-px transition-colors">
Price history
</button>
</div>
<!-- ======= deals tab ======= -->
<div x-show="tab==='deals'" x-cloak>
<!-- official stores -->
<div class="mb-6">
<div class="flex items-center gap-2.5 mb-3">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">Official stores</h2>
<span class="kind-tag kind-official">Verified &amp; trusted</span>
</div>
<div class="bg-card border border-line rounded-xl overflow-hidden">
<?php if ($deals['official'] === []): ?>
<div class="p-6 text-center text-sm text-muted">No official store deals right now.</div>
<?php else: ?>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-[11px] uppercase tracking-wider text-muted bg-page/60">
<th class="px-4 py-2.5 font-semibold">Store</th>
<th class="px-4 py-2.5 font-semibold">DRM</th>
<th class="px-4 py-2.5 font-semibold text-right">Discount</th>
<th class="px-4 py-2.5 font-semibold text-right">Price</th>
<th class="px-4 py-2.5 font-semibold"></th>
</tr>
</thead>
<tbody class="divide-y divide-line/60">
<?php foreach ($deals['official'] as $d): $ds = $stores[$d['store_code']] ?? null; ?>
<tr class="hover:bg-elev/50 transition-colors">
<td class="px-4 py-3">
<div class="flex items-center gap-2.5">
<?php if ($ds): ?><?= view('partials/store_badge', ['store' => $ds]) ?><?php endif; ?>
<span class="font-semibold text-zinc-200"><?= esc($ds['name'] ?? '?') ?></span>
<?php if ($d['historical_low']): ?><span class="hl-flag">★ HL</span><?php endif; ?>
</div>
</td>
<td class="px-4 py-3 text-xs text-muted"><?= esc($d['drm']) ?></td>
<td class="px-4 py-3 text-right">
<?php if ((int) $d['cut'] > 0): ?>
<span class="cut <?= cut_class((int) $d['cut']) ?> cut-badge">-<?= (int) $d['cut'] ?>%</span>
<?php else: ?>
<span class="text-muted text-xs">—</span>
<?php endif; ?>
</td>
<td class="px-4 py-3 text-right">
<span class="font-extrabold text-accent text-base"><?= money($d['price']) ?></span>
<span class="block text-[11px] text-muted line-through"><?= money($d['regular']) ?></span>
</td>
<td class="px-4 py-3 text-right whitespace-nowrap">
<?php if ($d['expiry']): ?>
<?php $daysLeft = max(1, (int) floor(($d['expiry']->toDateTime()->getTimestamp() - time()) / 86400)); ?>
<span class="text-[11px] text-amber-400/90 mr-3">ends in <?= $daysLeft ?>d</span>
<?php endif; ?>
<a href="<?= esc($d['url']) ?>" target="_blank" rel="nofollow noopener"
class="btn-buy">Buy</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
<!-- keyshops -->
<div>
<div class="flex items-center gap-2.5 mb-3">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">Keyshops</h2>
<span class="kind-tag kind-keyshop">Marketplace sellers</span>
</div>
<div class="bg-card border border-line rounded-xl overflow-hidden">
<?php if ($deals['keyshop'] === []): ?>
<div class="p-6 text-center text-sm text-muted">No keyshop offers right now.</div>
<?php else: ?>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-[11px] uppercase tracking-wider text-muted bg-page/60">
<th class="px-4 py-2.5 font-semibold">Store</th>
<th class="px-4 py-2.5 font-semibold">Edition</th>
<th class="px-4 py-2.5 font-semibold text-right">Discount</th>
<th class="px-4 py-2.5 font-semibold text-right">Price</th>
<th class="px-4 py-2.5 font-semibold"></th>
</tr>
</thead>
<tbody class="divide-y divide-line/60">
<?php foreach ($deals['keyshop'] as $d): $ds = $stores[$d['store_code']] ?? null; ?>
<tr class="hover:bg-elev/50 transition-colors">
<td class="px-4 py-3">
<div class="flex items-center gap-2.5">
<?php if ($ds): ?><?= view('partials/store_badge', ['store' => $ds]) ?><?php endif; ?>
<span class="font-semibold text-zinc-200"><?= esc($ds['name'] ?? '?') ?></span>
<?php if ($d['historical_low']): ?><span class="hl-flag">★ HL</span><?php endif; ?>
</div>
</td>
<td class="px-4 py-3 text-xs text-muted">
Global
<?php if ($d['regional']): ?>
<span class="text-amber-400/90">· ⚠ region-locked</span>
<?php endif; ?>
</td>
<td class="px-4 py-3 text-right">
<?php if ((int) $d['cut'] > 0): ?>
<span class="cut <?= cut_class((int) $d['cut']) ?> cut-badge">-<?= (int) $d['cut'] ?>%</span>
<?php else: ?>
<span class="text-muted text-xs">—</span>
<?php endif; ?>
</td>
<td class="px-4 py-3 text-right">
<span class="font-extrabold text-accent text-base"><?= money($d['price']) ?></span>
<span class="block text-[11px] text-muted line-through"><?= money($d['regular']) ?></span>
</td>
<td class="px-4 py-3 text-right">
<a href="<?= esc($d['url']) ?>" target="_blank" rel="nofollow noopener" class="btn-buy">Buy</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
<div class="px-4 py-2.5 text-[11px] text-muted/80 bg-page/40 border-t border-line/60">
Keyshop offers are sold by marketplace sellers. GG.deals is not responsible for their content.
</div>
</div>
</div>
</div>
<!-- ======= history tab ======= -->
<div x-show="tab==='history'" x-cloak class="bg-panel border border-line rounded-2xl p-5">
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
<div>
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider"><?= esc($game['title']) ?> price history</h2>
<p class="text-xs text-muted mt-1">Lowest recorded price per day</p>
</div>
<div class="flex gap-1 bg-card border border-line rounded-lg p-1">
<template x-for="r in [['90','3M'],['180','6M'],['365','1Y'],['0','All']]" :key="r[0]">
<button @click="range=Number(r[0]); setRange()"
:class="range===Number(r[0]) ? 'bg-elev text-accent' : 'text-muted hover:text-zinc-200'"
class="px-3 py-1.5 text-xs font-semibold rounded-md transition-colors" x-text="r[1]"></button>
</template>
</div>
</div>
<div class="h-[360px]"><canvas id="historyChart"></canvas></div>
<div class="mt-4 grid sm:grid-cols-3 gap-3 text-sm">
<div class="bg-card border border-line rounded-lg p-3">
<div class="text-[11px] uppercase tracking-wider text-muted">All-time low</div>
<div class="text-accent font-extrabold text-lg mt-0.5"><?= money($hl['price']) ?></div>
<div class="text-xs text-muted mt-0.5"><?= esc($hlStore['name'] ?? '') ?> · <?= time_ago($hl['date']) ?></div>
</div>
<div class="bg-card border border-line rounded-lg p-3">
<div class="text-[11px] uppercase tracking-wider text-muted">Best official store now</div>
<div class="text-zinc-100 font-extrabold text-lg mt-0.5"><?= money($game['best_official']['price']) ?></div>
<div class="text-xs text-muted mt-0.5"><?= esc($stores[$game['best_official']['store']]['name'] ?? '') ?></div>
</div>
<div class="bg-card border border-line rounded-lg p-3">
<div class="text-[11px] uppercase tracking-wider text-muted">Best keyshop now</div>
<div class="text-zinc-100 font-extrabold text-lg mt-0.5"><?= money($game['best_keyshop']['price']) ?></div>
<div class="text-xs text-muted mt-0.5"><?= esc($stores[$game['best_keyshop']['store']]['name'] ?? '') ?></div>
</div>
</div>
</div>
</div>
<!-- ======= about / requirements ======= -->
<div class="grid lg:grid-cols-3 gap-6 mb-8">
<div class="lg:col-span-2 bg-panel border border-line rounded-2xl p-5">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-3">About <?= esc($game['title']) ?></h2>
<p class="text-sm text-muted leading-relaxed"><?= esc($game['description'] ?? '') ?></p>
<div class="mt-4 flex flex-wrap items-center gap-2 text-xs">
<span class="chip"><span class="text-muted">Developer:</span> <span class="text-zinc-200"><?= esc($game['developer'] ?? '—') ?></span></span>
<span class="chip"><span class="text-muted">Publisher:</span> <span class="text-zinc-200"><?= esc($game['publisher'] ?? '—') ?></span></span>
<span class="chip"><span class="text-muted">Age rating:</span> <span class="text-zinc-200"><?= esc($game['age_rating'] ?? '—') ?></span></span>
<span class="chip"><span class="text-muted">Release:</span> <span class="text-zinc-200"><?= esc($releaseY) ?></span></span>
</div>
</div>
<div class="bg-panel border border-line rounded-2xl p-5">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider mb-3">System Requirements</h2>
<?php $reqs = $game['sys_reqs'] ?? []; ?>
<div class="space-y-2.5 text-sm">
<?php foreach (['os' => 'OS', 'cpu' => 'CPU', 'ram' => 'RAM', 'gpu' => 'GPU', 'storage' => 'Storage'] as $k => $label): ?>
<div class="flex justify-between gap-3">
<span class="text-muted shrink-0"><?= $label ?></span>
<span class="text-zinc-200 text-right"><?= esc($reqs[$k] ?? '—') ?></span>
</div>
<?php endforeach; ?>
</div>
<?php if (! empty($game['length'])): ?>
<div class="mt-4 pt-4 border-t border-line/60">
<div class="text-[11px] font-bold uppercase tracking-wider text-muted mb-2">How long to beat</div>
<div class="grid grid-cols-3 gap-2 text-center">
<div class="bg-card border border-line rounded-lg py-2"><div class="text-accent font-extrabold"><?= (int) $game['length']['main'] ?>h</div><div class="text-[10px] text-muted">Main</div></div>
<div class="bg-card border border-line rounded-lg py-2"><div class="text-accent font-extrabold"><?= (int) $game['length']['completion'] ?>h</div><div class="text-[10px] text-muted">Completion</div></div>
<div class="bg-card border border-line rounded-lg py-2"><div class="text-accent font-extrabold"><?= (int) $game['length']['perfect'] ?>h</div><div class="text-[10px] text-muted">100%</div></div>
</div>
</div>
<?php endif; ?>
</div>
</div>
<!-- ======= bundles ======= -->
<?php if ($bundles !== []): ?>
<section class="mb-8">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">Bundles with <?= esc($game['title']) ?></h2>
<a href="/deals" class="text-xs font-bold text-accent hover:underline">See all →</a>
</div>
<div class="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
<?php foreach ($bundles as $b): ?>
<a href="/bundle/<?= esc($b['slug']) ?>" class="bg-card border border-line rounded-xl p-4 hover:border-accent/40 transition-colors group block">
<div class="flex items-center justify-between mb-2">
<span class="kind-tag kind-keyshop">Bundle</span>
<span class="text-[11px] text-muted"><?= (int) $b['game_count'] ?> games</span>
</div>
<div class="text-[15px] font-semibold text-zinc-100 mb-1 group-hover:text-accent"><?= esc($b['title']) ?></div>
<p class="text-xs text-muted leading-relaxed mb-3 line-clamp-2"><?= esc($b['desc']) ?></p>
<div class="flex items-center justify-between">
<div>
<span class="text-accent font-extrabold"><?= money((float) $b['price']) ?></span>
<span class="text-[11px] text-muted line-through ml-1.5"><?= money((float) $b['regular']) ?></span>
</div>
<span class="text-[10px] text-amber-400/90">ends in <?= $b['expires'] instanceof MongoDB\BSON\UTCDateTime ? max(1, (int) floor(($b['expires']->toDateTime()->getTimestamp() - time()) / 86400)) . 'd' : 'soon' ?></span>
</div>
</a>
<?php endforeach; ?>
</div>
</section>
<?php endif; ?>
<!-- ======= franchises ======= -->
<?php if ($franchises !== []): ?>
<section class="mb-8">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">Series &amp; franchises</h2>
</div>
<div class="flex flex-wrap gap-2">
<?php foreach ($franchises as $fr): ?>
<a href="/franchise/<?= esc($fr['slug']) ?>" class="chip hover:border-accent/60 transition-colors">
<?= esc($fr['name']) ?> <span class="text-muted">(<?= count($fr['games']) ?>)</span>
</a>
<?php endforeach; ?>
</div>
</section>
<?php endif; ?>
<!-- ======= similar games ======= -->
<?php if ($similar !== []): ?>
<section class="mb-8">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">Similar games</h2>
</div>
<div class="flex gap-3 overflow-x-auto scroll-smooth snap-x pb-1 gg-scroll -mx-1 px-1">
<?php foreach ($similar as $sg): ?>
<a href="/game/<?= $sg['slug'] ?>" class="snap-start group shrink-0 w-[196px] rounded-xl bg-card border border-line hover:border-accent/50 overflow-hidden transition-colors">
<div class="relative">
<img src="<?= esc($sg['cover']['file']) ?>" alt="<?= esc($sg['title']) ?>" class="w-full h-[92px] object-cover">
<span class="score-chip absolute top-2 left-2">MC <?= (int) $sg['score'] ?></span>
</div>
<div class="p-2.5">
<div class="text-[13px] font-semibold text-zinc-100 truncate group-hover:text-accent"><?= esc($sg['title']) ?></div>
<div class="mt-1 flex items-baseline justify-between">
<span class="text-accent font-extrabold"><?= money(min($sg['best_official']['price'], $sg['best_keyshop']['price'])) ?></span>
<span class="text-[11px] text-muted line-through"><?= money($sg['base_price']) ?></span>
</div>
</div>
</a>
<?php endforeach; ?>
</div>
</section>
<?php endif; ?>
<script>
window.__GG__ = {
history: <?= json_encode($history) ?>,
hl: <?= json_encode((float) $hl['price']) ?>,
base: <?= json_encode((float) $game['base_price']) ?>,
title: <?= json_encode($game['title']) ?>
};
</script>
<script src="/js/chart.umd.js"></script>
<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
function gamePage() {
// Chart instance lives OUTSIDE the Alpine reactive data object —
// Alpine proxies every property access, and Chart.js's internal
// option resolver trips the proxy into infinite recursion.
let chart = null;
const data = window.__GG__.history;
const base = window.__GG__.base;
const hl = window.__GG__.hl;
return {
tab: 'deals',
range: 0,
setRange() {
if (!chart) return;
const cutoff = this.range > 0 ? new Date(Date.now() - this.range * 86400000).toISOString().slice(0, 10) : null;
const filter = (arr) => cutoff ? arr.filter(p => p.day >= cutoff) : arr;
chart.data.labels = filter(data.official).map(p => p.day);
chart.data.datasets[0].data = filter(data.official).map(p => p.price);
chart.data.datasets[1].data = filter(data.keyshop).map(p => p.price);
chart.update();
},
initChart() {
if (chart) { this.setRange(); return; }
const ctx = document.getElementById('historyChart');
if (!ctx) return;
chart = new Chart(ctx, {
type: 'line',
data: {
labels: data.official.map(p => p.day),
datasets: [
{
label: 'Official stores',
data: data.official.map(p => p.price),
borderColor: '#8be04b',
backgroundColor: 'rgba(139,224,75,0.08)',
fill: true,
tension: 0.25,
pointRadius: 0,
borderWidth: 2
},
{
label: 'Keyshops',
data: data.keyshop.map(p => p.price),
borderColor: '#ffa657',
backgroundColor: 'rgba(255,166,87,0.06)',
fill: true,
tension: 0.25,
pointRadius: 0,
borderWidth: 2
},
{
label: 'All-time low',
data: data.official.map(() => hl),
borderColor: 'rgba(255,255,255,0.35)',
borderDash: [6, 5],
pointRadius: 0,
borderWidth: 1.5,
fill: false
},
{
label: 'Regular price',
data: data.official.map(() => base),
borderColor: 'rgba(157,157,180,0.25)',
borderDash: [3, 4],
pointRadius: 0,
borderWidth: 1,
fill: false
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
interaction: { mode: 'index', intersect: false },
plugins: {
legend: { labels: { color: '#b9b9c9', usePointStyle: true, boxWidth: 8 } },
tooltip: {
backgroundColor: '#20202d',
borderColor: '#2e2e42',
borderWidth: 1,
titleColor: '#fff',
callbacks: { label: (c) => c.dataset.label + ': $' + Number(c.parsed.y).toFixed(2) }
}
},
scales: {
x: {
ticks: { color: '#71718a', maxTicksLimit: 10 },
grid: { color: 'rgba(46,46,66,0.5)' }
},
y: {
ticks: { color: '#71718a', callback: (v) => '$' + v },
grid: { color: 'rgba(46,46,66,0.5)' }
}
}
}
});
}
}
}
</script>
<?= $this->endSection() ?>
+277
View File
@@ -0,0 +1,277 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<?php
$storesMap = [];
foreach ($stores as $s) {
$storesMap[$s['code']] = $s;
}
$officialStores = array_filter($stores, static fn ($s) => $s['kind'] === 'official');
$keyshopStores = array_filter($stores, static fn ($s) => $s['kind'] === 'keyshop');
$selectedStores = $filters['stores'];
$selectedGenres = $filters['genres'] ?? [];
$anyFilter = $selectedStores !== [] || $filters['kind'] !== '' || $filters['min_price'] !== ''
|| $filters['max_price'] !== '' || $filters['min_cut'] > 0 || $filters['hl_only'] || $filters['q'] !== ''
|| $filters['price_tier'] !== '' || $filters['discount_tier'] !== '' || $filters['deal_rating'] !== ''
|| $filters['release_range'] !== '' || $selectedGenres !== [];
$genreQuery = $activeGenre !== '' ? '?genre=' . urlencode($activeGenre) : '';
?>
<!-- ======= page head ======= -->
<div class="flex flex-wrap items-end justify-between gap-3 mb-4">
<div>
<h1 class="text-2xl font-extrabold text-white tracking-tight">
<?= $activeGenreName !== '' ? ucwords($activeGenreName) . ' games' : 'Popular video games' ?>
</h1>
<p class="text-sm text-muted mt-1">
<span class="text-zinc-300 font-semibold"><?= number_format($total) ?></span> games with deals ·
<span class="text-zinc-300 font-semibold"><?= number_format($stats['games']) ?></span> games in database ·
<span class="text-zinc-300 font-semibold"><?= $stats['stores'] ?></span> stores
</p>
</div>
</div>
<!-- ======= main grid ======= -->
<div class="grid lg:grid-cols-[290px_1fr] gap-6 items-start">
<!-- ============ filters sidebar ============ -->
<form id="filters" method="get" action="/games<?= $activeGenre !== '' ? '/' . urlencode($activeGenre) : '' ?>" x-data="{ cut: <?= (int) $filters['min_cut'] ?>, genreSearch: '' }"
class="lg:sticky lg:top-24 bg-panel border border-line rounded-xl overflow-hidden">
<input type="hidden" name="q" value="<?= esc($filters['q']) ?>">
<div class="px-4 py-3 border-b border-line flex items-center justify-between">
<span class="text-sm font-bold text-zinc-200 uppercase tracking-wider">Filters</span>
<?php if ($anyFilter || $activeGenre !== ''): ?>
<a href="/games" class="text-xs text-muted hover:text-accent">Reset</a>
<?php endif; ?>
</div>
<div class="p-4 space-y-5" @change="$root.submit()">
<!-- deal type -->
<div>
<div class="filter-label">Deal type</div>
<div class="grid grid-cols-3 gap-1 bg-page rounded-lg p-1 mt-2">
<?php foreach (['' => 'All deals', 'official' => 'Official', 'keyshop' => 'Keyshops'] as $k => $label): ?>
<label class="cursor-pointer">
<input type="radio" name="kind" value="<?= $k ?>" class="peer sr-only" <?= $filters['kind'] === $k ? 'checked' : '' ?>>
<span class="block text-center text-xs font-semibold py-1.5 rounded-md text-muted peer-checked:bg-card peer-checked:text-accent hover:text-zinc-200 transition-colors"><?= $label ?></span>
</label>
<?php endforeach; ?>
</div>
</div>
<!-- price tier presets -->
<div>
<div class="filter-label">Price</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$priceTiers = ['' => 'Any', '2' => 'Under $2', '5' => 'Under $5', '10' => 'Under $10', '15' => 'Under $15', '20' => 'Under $20', '30' => 'Under $30'];
foreach ($priceTiers as $v => $l): ?>
<a href="<?= qs_url(['price_tier' => $v]) ?>"
class="preset-chip <?= (string) ($filters['price_tier'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
<div class="flex items-center gap-2 mt-2">
<input type="number" name="min_price" min="0" step="0.5" placeholder="from" value="<?= esc($filters['min_price']) ?>"
class="filter-input">
<span class="text-muted text-xs">—</span>
<input type="number" name="max_price" min="0" step="0.5" placeholder="to" value="<?= esc($filters['max_price']) ?>"
class="filter-input">
</div>
</div>
<!-- discount tier presets -->
<div>
<div class="filter-label">Discount</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$discountTiers = ['' => 'Any', '50' => '≥50%', '66' => '≥66%', '75' => '≥75%', '80' => '≥80%', '85' => '≥85%', '90' => '≥90%'];
foreach ($discountTiers as $v => $l): ?>
<a href="<?= qs_url(['discount_tier' => $v]) ?>"
class="preset-chip <?= (string) ($filters['discount_tier'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
<div class="mt-2">
<div class="filter-label flex justify-between">
<span>Minimum discount</span>
<span class="text-accent font-bold" x-text="cut + '%'"></span>
</div>
<input type="range" name="min_cut" min="0" max="90" step="5" x-model.number="cut"
class="gg-range mt-3 w-full">
</div>
</div>
<!-- deal rating -->
<div>
<div class="filter-label">Deal rating</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$ratings = ['' => 'Any', 'hot' => '🔥 Hot', 'good' => 'Good', 'fair' => 'Fair'];
foreach ($ratings as $v => $l): ?>
<a href="<?= qs_url(['deal_rating' => $v]) ?>"
class="preset-chip <?= (string) ($filters['deal_rating'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
</div>
<!-- release year -->
<div>
<div class="filter-label">Release year</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$years = ['' => 'Any', 'pre2000' => 'Before 2000', '2000s' => '20002009', '2010s' => '20102019', '2020s' => '2020+'];
foreach ($years as $v => $l): ?>
<a href="<?= qs_url(['release_range' => $v]) ?>"
class="preset-chip <?= (string) ($filters['release_range'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
</div>
<!-- genres -->
<div>
<div class="filter-label">Genres</div>
<div class="relative mt-2">
<svg class="absolute left-2.5 top-1/2 -translate-y-1/2 w-3 h-3 text-muted" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.35-4.35"/></svg>
<input type="text" x-model="genreSearch" placeholder="Search genres…"
class="filter-input pl-8">
</div>
<div class="mt-2 space-y-0.5 max-h-52 overflow-y-auto gg-scroll pr-1">
<?php foreach ($genres as $slug => $g):
$gl = mb_strtolower($g['name']); ?>
<label class="store-row" x-show="!genreSearch || '<?= $gl ?>'.includes(genreSearch.toLowerCase())">
<input type="checkbox" name="genres[]" value="<?= esc($g['name']) ?>" <?= in_array($g['name'], $selectedGenres, true) ? 'checked' : '' ?> class="gg-check">
<span class="text-xs text-zinc-300 truncate flex-1"><?= esc($g['name']) ?></span>
<span class="text-[10px] text-muted"><?= $g['count'] ?></span>
</label>
<?php endforeach; ?>
</div>
</div>
<!-- historical low only -->
<label class="flex items-center gap-2.5 cursor-pointer select-none">
<input type="checkbox" name="hl_only" value="1" <?= $filters['hl_only'] ? 'checked' : '' ?> class="gg-check">
<span class="text-xs text-zinc-300">Only all-time low offers</span>
</label>
<!-- stores -->
<div>
<div class="filter-label">Official stores</div>
<div class="mt-2 space-y-0.5 max-h-56 overflow-y-auto gg-scroll pr-1">
<?php foreach ($officialStores as $s): ?>
<label class="store-row">
<input type="checkbox" name="stores[]" value="<?= $s['code'] ?>" <?= in_array($s['code'], $selectedStores, true) ? 'checked' : '' ?> class="gg-check">
<?= view('partials/store_badge', ['store' => $s]) ?>
<span class="text-xs text-zinc-300 truncate flex-1"><?= esc($s['name']) ?></span>
<?php if (in_array($s['code'], $selectedStores, true)): ?>
<span class="text-accent">✓</span>
<?php endif; ?>
</label>
<?php endforeach; ?>
</div>
</div>
<div>
<div class="filter-label">Keyshops</div>
<div class="mt-2 space-y-0.5 max-h-56 overflow-y-auto gg-scroll pr-1">
<?php foreach ($keyshopStores as $s): ?>
<label class="store-row">
<input type="checkbox" name="stores[]" value="<?= $s['code'] ?>" <?= in_array($s['code'], $selectedStores, true) ? 'checked' : '' ?> class="gg-check">
<?= view('partials/store_badge', ['store' => $s]) ?>
<span class="text-xs text-zinc-300 truncate flex-1"><?= esc($s['name']) ?></span>
<?php if (in_array($s['code'], $selectedStores, true)): ?>
<span class="text-accent">✓</span>
<?php endif; ?>
</label>
<?php endforeach; ?>
</div>
</div>
<button type="submit" class="w-full bg-accent text-accent-ink font-bold text-sm py-2.5 rounded-lg hover:bg-accent/90 transition-colors">
Apply filters
</button>
</div>
</form>
<!-- ============ feed ============ -->
<div class="min-w-0">
<!-- tabs + sort -->
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
<div class="flex gap-1 bg-panel border border-line rounded-lg p-1">
<?php
$tabs = [
'trending' => 'Best deals',
'rating' => 'Deal rating',
'cut' => 'Biggest discount',
'hl' => 'Cheapest ever',
'recent' => 'New releases',
];
foreach ($tabs as $key => $label): ?>
<a href="<?= qs_url(['sort' => $key, 'page' => null]) ?>"
class="px-3 py-1.5 text-xs font-semibold rounded-md transition-colors <?= ($filters['sort'] === $key || ($key === 'trending' && $filters['sort'] === '')) ? 'bg-card text-accent' : 'text-muted hover:text-zinc-200' ?>">
<?= $label ?>
</a>
<?php endforeach; ?>
</div>
<div class="flex items-center gap-2 text-xs text-muted">
<span class="hidden sm:inline">Sort by</span>
<select name="sort" form="filters" onchange="document.getElementById('filters').submit()"
class="bg-card border border-line rounded-lg px-3 py-2 text-xs text-zinc-200 focus:outline-none focus:border-accent/60">
<?php
$sortOptions = $tabs + [
'price' => 'Lowest price',
'title' => 'Title AZ',
'metascore' => 'Metascore',
'length' => 'Oldest release',
'ending' => 'Ending soon',
];
foreach ($sortOptions as $key => $label): ?>
<option value="<?= $key ?>" <?= $filters['sort'] === $key ? 'selected' : '' ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<!-- rows -->
<div class="space-y-2.5">
<?php if ($feed === []): ?>
<div class="bg-card border border-line rounded-xl p-10 text-center">
<div class="text-4xl mb-3">🕹️</div>
<div class="text-zinc-200 font-semibold">No games match your filters</div>
<div class="text-muted text-sm mt-1">Try widening the price range or clearing store filters.</div>
<a href="/games" class="inline-block mt-4 bg-accent text-accent-ink font-bold text-sm py-2 px-5 rounded-lg hover:bg-accent/90">Reset filters</a>
</div>
<?php endif; ?>
<?php foreach ($feed as $row): ?>
<?= view('partials/deal_row', ['row' => $row, 'stores' => $storesMap]) ?>
<?php endforeach; ?>
</div>
<!-- pagination -->
<?php if ($pages > 1): ?>
<div class="flex items-center justify-center gap-1.5 mt-6">
<?php
$window = range(max(1, $page - 3), min($pages, $page + 3));
if ($page > 1): ?>
<a href="<?= qs_url(['page' => $page - 1]) ?>" class="pg-btn">← Prev</a>
<?php endif;
if (! in_array(1, $window, true) && $pages > 1): ?>
<a href="<?= qs_url(['page' => 1]) ?>" class="pg-btn">1</a>
<span class="pg-dots">…</span>
<?php endif;
foreach ($window as $p): ?>
<a href="<?= qs_url(['page' => $p]) ?>" class="pg-btn <?= $p === $page ? 'pg-active' : '' ?>"><?= $p ?></a>
<?php endforeach;
if (! in_array($pages, $window, true)): ?>
<span class="pg-dots">…</span>
<a href="<?= qs_url(['page' => $pages]) ?>" class="pg-btn"><?= $pages ?></a>
<?php endif;
if ($page < $pages): ?>
<a href="<?= qs_url(['page' => $page + 1]) ?>" class="pg-btn">Next →</a>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
<?= $this->endSection() ?>
+332
View File
@@ -0,0 +1,332 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<?php
$storesMap = [];
foreach ($stores as $s) {
$storesMap[$s['code']] = $s;
}
$officialStores = array_filter($stores, static fn ($s) => $s['kind'] === 'official');
$keyshopStores = array_filter($stores, static fn ($s) => $s['kind'] === 'keyshop');
$selectedStores = $filters['stores'];
$anyFilter = $selectedStores !== [] || $filters['kind'] !== '' || $filters['min_price'] !== ''
|| $filters['max_price'] !== '' || $filters['min_cut'] > 0 || $filters['hl_only'] || $filters['q'] !== ''
|| $filters['price_tier'] !== '' || $filters['discount_tier'] !== '' || $filters['deal_rating'] !== ''
|| $filters['release_range'] !== '';
?>
<!-- ======= page head ======= -->
<div class="flex flex-wrap items-end justify-between gap-3 mb-4">
<div>
<h1 class="text-2xl font-extrabold text-white tracking-tight">
<?= $filters['preset_name'] !== '' ? esc($filters['preset_name']) : 'The best PC game deals' ?>
</h1>
<p class="text-sm text-muted mt-1">
<span class="text-zinc-300 font-semibold"><?= number_format($stats['games']) ?></span> games ·
<span class="text-zinc-300 font-semibold"><?= number_format($stats['deals']) ?></span> deals from
<span class="text-zinc-300 font-semibold"><?= $stats['stores'] ?></span> stores ·
<span class="text-accent font-semibold"><?= $stats['hl_now'] ?></span> all-time lows right now
</p>
</div>
<?php if ($filters['q'] !== ''): ?>
<div class="text-sm text-muted">
Search: <span class="text-zinc-100 font-semibold"><?= esc($filters['q']) ?></span>
<a href="<?= qs_url([], ['q']) ?>" class="ml-2 text-accent hover:underline">clear</a>
</div>
<?php endif; ?>
</div>
<!-- ======= preset tabs (gg.deals style) ======= -->
<div class="flex flex-wrap gap-1.5 mb-6">
<?php
$presetLinks = [
'' => 'Best deals',
'hot-new-deals' => '🔥 Hot new deals',
'new-deals' => 'New deals',
'historical-lows' => 'Historical lows',
'ending-soon' => 'Ending soon',
'at-least-75-off' => '≥75% off',
'at-least-85-off' => '≥85% off',
];
$currentPreset = $activePreset ?? '';
$presetKey = '';
foreach ($presets as $k => $p) {
if ($p['title'] === $currentPreset) { $presetKey = $k; break; }
}
foreach ($presetLinks as $key => $label): ?>
<a href="<?= $key === '' ? qs_url(['preset' => null], ['preset']) : '/deals/' . $key ?>"
class="px-3.5 py-2 text-xs font-bold rounded-lg transition-colors border <?= $presetKey === $key ? 'bg-accent/15 text-accent border-accent/40' : 'bg-card border-line text-muted hover:text-zinc-200 hover:border-accent/30' ?>">
<?= $label ?>
</a>
<?php endforeach; ?>
</div>
<!-- ======= trending carousel ======= -->
<section class="mb-8" x-data="{ el: null }" x-init="el = $refs.track">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">🔥 Trending deals</h2>
<div class="flex gap-1.5">
<button @click="el.scrollBy({left: -480, behavior:'smooth'})" class="w-8 h-8 rounded-lg bg-card border border-line hover:border-accent/50 flex items-center justify-center">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6"/></svg>
</button>
<button @click="el.scrollBy({left: 480, behavior:'smooth'})" class="w-8 h-8 rounded-lg bg-card border border-line hover:border-accent/50 flex items-center justify-center">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></svg>
</button>
</div>
</div>
<div class="relative -mx-1 px-1">
<div x-ref="track" class="flex gap-3 overflow-x-auto scroll-smooth snap-x pb-1 gg-scroll">
<?php foreach ($trending as $t): ?>
<a href="/game/<?= $t['slug'] ?>" class="snap-start group shrink-0 w-[196px] rounded-xl bg-card border border-line hover:border-accent/50 overflow-hidden transition-colors">
<div class="relative">
<img src="<?= esc($t['cover']['file']) ?>" alt="<?= esc($t['title']) ?>" class="w-full h-[92px] object-cover">
<?php $tCut = (int) round((1 - $t['best_keyshop']['price'] / $t['base_price']) * 100); ?>
<?php if ($tCut > 0): ?>
<span class="cut <?= cut_class($tCut) ?> cut-badge absolute top-2 left-2">-<?= $tCut ?>%</span>
<?php endif; ?>
</div>
<div class="p-2.5">
<div class="text-[13px] font-semibold text-zinc-100 truncate group-hover:text-accent"><?= esc($t['title']) ?></div>
<div class="mt-1 flex items-baseline justify-between">
<span class="text-accent font-extrabold"><?= money(min($t['best_official']['price'], $t['best_keyshop']['price'])) ?></span>
<span class="text-[11px] text-muted line-through"><?= money($t['base_price']) ?></span>
</div>
</div>
</a>
<?php endforeach; ?>
</div>
</div>
</section>
<!-- ======= main grid ======= -->
<div class="grid lg:grid-cols-[290px_1fr] gap-6 items-start">
<!-- ============ filters sidebar ============ -->
<form id="filters" method="get" action="/" x-data="{ cut: <?= (int) $filters['min_cut'] ?> }"
class="lg:sticky lg:top-24 bg-panel border border-line rounded-xl overflow-hidden">
<input type="hidden" name="q" value="<?= esc($filters['q']) ?>">
<div class="px-4 py-3 border-b border-line flex items-center justify-between">
<span class="text-sm font-bold text-zinc-200 uppercase tracking-wider">Filters</span>
<?php if ($anyFilter): ?>
<a href="/" class="text-xs text-muted hover:text-accent">Reset</a>
<?php endif; ?>
</div>
<div class="p-4 space-y-5" @change="$root.submit()">
<!-- deal type -->
<div>
<div class="filter-label">Deal type</div>
<div class="grid grid-cols-3 gap-1 bg-page rounded-lg p-1 mt-2">
<?php foreach (['' => 'All deals', 'official' => 'Official', 'keyshop' => 'Keyshops'] as $k => $label): ?>
<label class="cursor-pointer">
<input type="radio" name="kind" value="<?= $k ?>" class="peer sr-only" <?= $filters['kind'] === $k ? 'checked' : '' ?>>
<span class="block text-center text-xs font-semibold py-1.5 rounded-md text-muted peer-checked:bg-card peer-checked:text-accent hover:text-zinc-200 transition-colors"><?= $label ?></span>
</label>
<?php endforeach; ?>
</div>
</div>
<!-- price tier presets (gg.deals style) -->
<div>
<div class="filter-label">Price</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$priceTiers = ['' => 'Any', '2' => 'Under $2', '5' => 'Under $5', '10' => 'Under $10', '15' => 'Under $15', '20' => 'Under $20', '30' => 'Under $30'];
foreach ($priceTiers as $v => $l): ?>
<a href="<?= qs_url(['price_tier' => $v]) ?>"
class="preset-chip <?= (string) ($filters['price_tier'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
<div class="flex items-center gap-2 mt-2">
<input type="number" name="min_price" min="0" step="0.5" placeholder="from" value="<?= esc($filters['min_price']) ?>"
class="filter-input">
<span class="text-muted text-xs">—</span>
<input type="number" name="max_price" min="0" step="0.5" placeholder="to" value="<?= esc($filters['max_price']) ?>"
class="filter-input">
</div>
</div>
<!-- discount tier presets -->
<div>
<div class="filter-label">Discount</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$discountTiers = ['' => 'Any', '50' => '≥50%', '66' => '≥66%', '75' => '≥75%', '80' => '≥80%', '85' => '≥85%', '90' => '≥90%'];
foreach ($discountTiers as $v => $l): ?>
<a href="<?= qs_url(['discount_tier' => $v]) ?>"
class="preset-chip <?= (string) ($filters['discount_tier'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
<div class="mt-2">
<div class="filter-label flex justify-between">
<span>Minimum discount</span>
<span class="text-accent font-bold" x-text="cut + '%'"></span>
</div>
<input type="range" name="min_cut" min="0" max="90" step="5" x-model.number="cut"
class="gg-range mt-3 w-full">
</div>
</div>
<!-- deal rating -->
<div>
<div class="filter-label">Deal rating</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$ratings = ['' => 'Any', 'hot' => '🔥 Hot', 'good' => 'Good', 'fair' => 'Fair'];
foreach ($ratings as $v => $l): ?>
<a href="<?= qs_url(['deal_rating' => $v]) ?>"
class="preset-chip <?= (string) ($filters['deal_rating'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
</div>
<!-- release year -->
<div>
<div class="filter-label">Release year</div>
<div class="flex flex-wrap gap-1.5 mt-2">
<?php
$years = ['' => 'Any', 'pre2000' => 'Before 2000', '2000s' => '20002009', '2010s' => '20102019', '2020s' => '2020+'];
foreach ($years as $v => $l): ?>
<a href="<?= qs_url(['release_range' => $v]) ?>"
class="preset-chip <?= (string) ($filters['release_range'] ?? '') === $v ? 'chip-active' : '' ?>"><?= $l ?></a>
<?php endforeach; ?>
</div>
</div>
<!-- historical low only -->
<label class="flex items-center gap-2.5 cursor-pointer select-none">
<input type="checkbox" name="hl_only" value="1" <?= $filters['hl_only'] ? 'checked' : '' ?> class="gg-check">
<span class="text-xs text-zinc-300">Only all-time low offers</span>
</label>
<!-- wishlist only -->
<div class="flex items-center gap-2.5">
<input type="checkbox" id="wishlist-filter" class="gg-check"
:checked="$store.gg.wishlist.length > 0"
@change="if ($event.target.checked && $store.gg.wishlist.length) { window.location = '<?= qs_url(['wishlist' => '1']) ?>'; }">
<span class="text-xs text-zinc-300 cursor-pointer" @click="$refs.wlcheck.click()">Only games from wishlist</span>
</div>
<!-- stores -->
<div>
<div class="filter-label">Official stores</div>
<div class="mt-2 space-y-0.5 max-h-56 overflow-y-auto gg-scroll pr-1">
<?php foreach ($officialStores as $s): ?>
<label class="store-row">
<input type="checkbox" name="stores[]" value="<?= $s['code'] ?>" <?= in_array($s['code'], $selectedStores, true) ? 'checked' : '' ?> class="gg-check">
<?= view('partials/store_badge', ['store' => $s]) ?>
<span class="text-xs text-zinc-300 truncate flex-1"><?= esc($s['name']) ?></span>
<?php if (in_array($s['code'], $selectedStores, true)): ?>
<span class="text-accent">✓</span>
<?php endif; ?>
</label>
<?php endforeach; ?>
</div>
</div>
<div>
<div class="filter-label">Keyshops</div>
<div class="mt-2 space-y-0.5 max-h-56 overflow-y-auto gg-scroll pr-1">
<?php foreach ($keyshopStores as $s): ?>
<label class="store-row">
<input type="checkbox" name="stores[]" value="<?= $s['code'] ?>" <?= in_array($s['code'], $selectedStores, true) ? 'checked' : '' ?> class="gg-check">
<?= view('partials/store_badge', ['store' => $s]) ?>
<span class="text-xs text-zinc-300 truncate flex-1"><?= esc($s['name']) ?></span>
<?php if (in_array($s['code'], $selectedStores, true)): ?>
<span class="text-accent">✓</span>
<?php endif; ?>
</label>
<?php endforeach; ?>
</div>
</div>
<button type="submit" class="w-full bg-accent text-accent-ink font-bold text-sm py-2.5 rounded-lg hover:bg-accent/90 transition-colors">
Apply filters
</button>
</div>
</form>
<!-- ============ feed ============ -->
<div class="min-w-0">
<!-- tabs + sort -->
<div class="flex flex-wrap items-center justify-between gap-3 mb-4">
<div class="flex gap-1 bg-panel border border-line rounded-lg p-1">
<?php
$tabs = [
'trending' => 'Best deals',
'rating' => 'Deal rating',
'cut' => 'Biggest discount',
'hl' => 'Cheapest ever',
'recent' => 'New releases',
];
foreach ($tabs as $key => $label): ?>
<a href="<?= qs_url(['sort' => $key, 'page' => null]) ?>"
class="px-3 py-1.5 text-xs font-semibold rounded-md transition-colors <?= ($filters['sort'] === $key || ($key === 'trending' && $filters['sort'] === '')) ? 'bg-card text-accent' : 'text-muted hover:text-zinc-200' ?>">
<?= $label ?>
</a>
<?php endforeach; ?>
</div>
<div class="flex items-center gap-2 text-xs text-muted">
<span class="hidden sm:inline">Sort by</span>
<select name="sort" form="filters" onchange="document.getElementById('filters').submit()"
class="bg-card border border-line rounded-lg px-3 py-2 text-xs text-zinc-200 focus:outline-none focus:border-accent/60">
<?php
$sortOptions = $tabs + [
'price' => 'Lowest price',
'title' => 'Title AZ',
'metascore' => 'Metascore',
'length' => 'Oldest release',
'ending' => 'Ending soon',
];
foreach ($sortOptions as $key => $label): ?>
<option value="<?= $key ?>" <?= $filters['sort'] === $key ? 'selected' : '' ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<!-- rows -->
<div class="space-y-2.5">
<?php if ($feed === []): ?>
<div class="bg-card border border-line rounded-xl p-10 text-center">
<div class="text-4xl mb-3">🕹️</div>
<div class="text-zinc-200 font-semibold">No deals match your filters</div>
<div class="text-muted text-sm mt-1">Try widening the price range or clearing store filters.</div>
<a href="/" class="inline-block mt-4 bg-accent text-accent-ink font-bold text-sm py-2 px-5 rounded-lg hover:bg-accent/90">Reset filters</a>
</div>
<?php endif; ?>
<?php foreach ($feed as $row): ?>
<?= view('partials/deal_row', ['row' => $row, 'stores' => $storesMap]) ?>
<?php endforeach; ?>
</div>
<!-- pagination -->
<?php if ($pages > 1): ?>
<div class="flex items-center justify-center gap-1.5 mt-6">
<?php
$window = range(max(1, $page - 3), min($pages, $page + 3));
if ($page > 1): ?>
<a href="<?= qs_url(['page' => $page - 1]) ?>" class="pg-btn">← Prev</a>
<?php endif;
if (! in_array(1, $window, true) && $pages > 1): ?>
<a href="<?= qs_url(['page' => 1]) ?>" class="pg-btn">1</a>
<span class="pg-dots">…</span>
<?php endif;
foreach ($window as $p): ?>
<a href="<?= qs_url(['page' => $p]) ?>" class="pg-btn <?= $p === $page ? 'pg-active' : '' ?>"><?= $p ?></a>
<?php endforeach;
if (! in_array($pages, $window, true)): ?>
<span class="pg-dots">…</span>
<a href="<?= qs_url(['page' => $pages]) ?>" class="pg-btn"><?= $pages ?></a>
<?php endif;
if ($page < $pages): ?>
<a href="<?= qs_url(['page' => $page + 1]) ?>" class="pg-btn">Next →</a>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
<?= $this->endSection() ?>
+132
View File
@@ -0,0 +1,132 @@
<?= $this->extend('layout') ?>
<?= $this->section('content') ?>
<?php
$dealSections = [
'popular' => ['Most Popular Games', 'popular', '/deals'],
'newDeals' => ['New deals', 'new', '/deals/new-deals'],
'bestDeals' => ['Best deals', 'hot', '/deals/hot-new-deals'],
'histLows' => ['Historical lows', 'hl', '/deals/historical-lows'],
'endingSoon' => ['Ending Soon', 'ending', '/deals/ending-soon'],
];
?>
<!-- ======= stats strip ======= -->
<div class="bg-panel border border-line rounded-2xl px-5 py-4 mb-8 flex flex-wrap items-center gap-x-8 gap-y-3">
<div>
<div class="text-2xl font-extrabold text-white"><?= number_format($stats['games']) ?></div>
<div class="text-[11px] uppercase tracking-wider text-muted">Games tracked</div>
</div>
<div>
<div class="text-2xl font-extrabold text-white"><?= number_format($stats['deals']) ?></div>
<div class="text-[11px] uppercase tracking-wider text-muted">Deals today</div>
</div>
<div>
<div class="text-2xl font-extrabold text-white"><?= $stats['stores'] ?></div>
<div class="text-[11px] uppercase tracking-wider text-muted">Stores</div>
</div>
<div>
<div class="text-2xl font-extrabold text-accent"><?= $stats['hl_now'] ?></div>
<div class="text-[11px] uppercase tracking-wider text-muted">All-time lows now</div>
</div>
<div class="ml-auto text-xs text-muted">
Compare prices of video games from <span class="text-zinc-200 font-semibold"><?= $stats['stores'] ?> stores</span>,
find the best game deals online. CD keys for PC games at the best price!
</div>
</div>
<!-- ======= deal sections ======= -->
<?php foreach ($dealSections as $key => [$title, $mode, $link]): ?>
<?php if (${$key} !== []): ?>
<section class="mb-8">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider"><?= $title ?></h2>
<a href="<?= $link ?>" class="text-xs font-bold text-accent hover:underline">See all →</a>
</div>
<div class="grid sm:grid-cols-2 lg:grid-cols-4 gap-2.5">
<?php foreach (${$key} as $d): ?>
<?= view('partials/dash_deal', ['d' => $d, 'stores' => $stores]) ?>
<?php endforeach; ?>
</div>
</section>
<?php endif; ?>
<?php endforeach; ?>
<!-- ======= game lists: most wanted / new releases / upcoming ======= -->
<div class="grid lg:grid-cols-3 gap-6 mb-8">
<?php
$gameSections = [
'mostWanted' => ['🔥 Most Wanted', 'wanted'],
'newReleases' => ['🆕 New releases', 'releases'],
'upcoming' => ['📅 Upcoming games', 'upcoming'],
];
foreach ($gameSections as $key => [$title, $mode]): ?>
<div class="bg-panel border border-line rounded-2xl overflow-hidden">
<div class="px-4 py-3 border-b border-line flex items-center justify-between">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider"><?= $title ?></h2>
<a href="/games" class="text-xs font-bold text-accent hover:underline">See all</a>
</div>
<div class="divide-y divide-line/60">
<?php foreach (${$key} as $i => $g): ?>
<a href="/game/<?= $g['slug'] ?>" class="flex items-center gap-3 px-4 py-2.5 hover:bg-elev/50 transition-colors group">
<span class="w-6 text-center font-extrabold <?= $i < 3 ? 'text-accent' : 'text-muted' ?>"><?= $i + 1 ?></span>
<img src="<?= esc($g['cover']['file']) ?>" alt="" class="w-[84px] h-[39px] object-cover rounded ring-1 ring-line shrink-0" loading="lazy">
<div class="min-w-0 flex-1">
<div class="text-[13px] font-semibold text-zinc-100 truncate group-hover:text-accent"><?= esc($g['title']) ?></div>
<div class="text-[11px] text-muted">
<span class="text-accent font-bold"><?= money(min($g['best_official']['price'], $g['best_keyshop']['price'])) ?></span>
<span class="line-through ml-1"><?= money($g['base_price']) ?></span>
</div>
</div>
</a>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<!-- ======= news + prepaids ======= -->
<div class="grid lg:grid-cols-3 gap-6">
<!-- news feed -->
<div class="lg:col-span-2 bg-panel border border-line rounded-2xl overflow-hidden">
<div class="px-4 py-3 border-b border-line flex items-center justify-between">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">📰 News</h2>
<a href="/news" class="text-xs font-bold text-accent hover:underline">All news →</a>
</div>
<div class="divide-y divide-line/60">
<?php foreach ($news as $p): ?>
<a href="/news" class="flex items-start gap-3 px-4 py-3 hover:bg-elev/50 transition-colors group">
<span class="kind-tag mt-0.5 <?= $p['category'] === 'freebies' ? 'kind-keyshop' : 'kind-official' ?> shrink-0"><?= esc($p['category']) ?></span>
<div class="min-w-0">
<div class="text-sm font-semibold text-zinc-100 group-hover:text-accent leading-snug"><?= esc($p['title']) ?></div>
<div class="text-[11px] text-muted mt-1"><?= time_ago($p['date']) ?></div>
</div>
</a>
<?php endforeach; ?>
</div>
</div>
<!-- prepaids -->
<div class="bg-panel border border-line rounded-2xl overflow-hidden">
<div class="px-4 py-3 border-b border-line flex items-center justify-between">
<h2 class="text-sm font-bold text-zinc-200 uppercase tracking-wider">🎁 Prepaids</h2>
<a href="/prepaids" class="text-xs font-bold text-accent hover:underline">All →</a>
</div>
<div class="p-3 space-y-2">
<?php foreach ($prepaids as $g): ?>
<a href="/prepaids" class="flex items-center justify-between px-3 py-2 rounded-lg bg-card border border-line hover:border-accent/40 transition-colors group">
<div class="flex items-center gap-2.5 min-w-0">
<span class="w-7 h-7 rounded-md flex items-center justify-center text-[10px] font-extrabold text-white shrink-0"
style="background: linear-gradient(135deg, <?= esc($g['color'][0]) ?>, <?= esc($g['color'][1]) ?>)">
<?= store_initials($g['name']) ?>
</span>
<span class="text-[13px] font-semibold text-zinc-100 truncate group-hover:text-accent"><?= esc($g['name']) ?></span>
</div>
<span class="text-xs text-accent font-bold shrink-0">from <?= money((float) $g['offers'][0]['price']) ?></span>
</a>
<?php endforeach; ?>
</div>
</div>
</div>
<?= $this->endSection() ?>

Some files were not shown because too many files have changed in this diff Show More