# External Integrations

**Analysis Date:** 2026-04-21

## APIs & External Services

**Lottery Data Scraping:**
- URL: `https://history.macaumarksix.com/history/macaujc2/y/{year}` (e.g., `2026`)
- Purpose: Fetching Macau Mark Six lottery historical results
- Client: `guzzlehttp/guzzle` ^7.10
- Integration point: `D:\code\php\amlhc\application\index\controller\Index.php` method `get_history()` (lines 20-58)
- Data flow: Scraped JSON response contains `expect` (period number), `openTime`, `openCode` (comma-separated numbers) -> parsed and upserted into `fa_history` table

**FastAdmin Official API:**
- URL: `https://api.fastadmin.net` (`application/config.php` `fastadmin.api_url`)
- Purpose: Plugin marketplace, version checks, addon updates

**WeChat (EasyWeChat SDK):**
- Package: `overtrue/wechat` ^4.6
- Purpose: WeChat OAuth login, messaging
- Integration point: Addon-level, managed via addon configuration

## Data Storage

**Databases:**
- **MySQL** - Primary database
  - Connection via env vars: `database.hostname`, `database.database`, `database.username`, `database.password`, `database.hostport` (`D:\code\php\amlhc\application\database.php`)
  - Charset: `utf8mb4` (configurable via `database.charset`)
  - Table prefix: `fa_` (configurable via `database.prefix`)
  - PDO driver required (`ext-pdo`)
  - Single server mode by default (`deploy: 0`), supports master-slave replication
  - Key tables: `fa_admin`, `fa_auth_group`, `fa_auth_rule`, `fa_user`, `fa_attachment`, `fa_history`, `fa_num`, `fa_command`

**Caching:**
- **File-based cache** - Default cache driver (`application/config.php` `cache.type => File`, path: `CACHE_PATH`)
- **Redis** - Used for queue system (`D:\code\php\amlhc\application\extra\queue.php`)
  - Host: `127.0.0.1`, Port: `6379`
  - Password: empty by default
  - Database: `0` (select)
  - Persistent connection: disabled
  - Expire: `0` (no expiration on tasks)
- **Token storage** - MySQL-backed (`application/config.php` `token.type => Mysql`)
- **Menu cache** - Uses ThinkPHP cache with key `"__menu__"` (`D:\code\php\amlhc\application\admin\library\Auth.php` line 461)
- Session supports Redis/memcache drivers but defaults to file-based

**File Storage:**
- **Local filesystem** - Default upload storage
  - Upload URL: `ajax/upload` (`D:\code\php\amlhc\application\extra\upload.php`)
  - Upload path pattern: `/uploads/{year}{mon}{day}/{filemd5}{.suffix}`
  - Max upload size: 10MB
  - Allowed types: `jpg,png,bmp,jpeg,gif,webp,zip,rar,wav,mp4,mp3,webm`
  - CDN support available via `cdnurl` config (empty by default)
  - Chunked upload support available (disabled by default, chunk size: 2MB)
  - Upload handled by: `D:\code\php\amlhc\application\api\controller\Common.php` `upload()` method with `app\common\library\Upload` class

## Authentication & Identity

**Backend Admin Auth:**
- Class: `D:\code\php\amlhc\application\admin\library\Auth.php` (extends `fast\Auth`)
- Password hashing: `md5(md5(password) . salt)` (double MD5 with salt)
- Session-based: Stores admin data in `Session::get('admin')`
- Role-based access control (RBAC): Admin -> AuthGroup -> AuthRule hierarchy
- Features:
  - Login retry limit: 10 attempts, 1-day cooldown (`fastadmin.login_failure_retry`)
  - IP change detection enabled (`fastadmin.loginip_check: true`)
  - Unique login option available (`fastadmin.login_unique: false` by default)
  - Safe code validation: MD5-based checksum of username + partial password + token key
  - Auto-login via `keeplogin` cookie with time-limited key
- Tables: `fa_admin`, `fa_auth_group`, `fa_auth_group_access`, `fa_auth_rule`

**Frontend User Auth:**
- Class: `D:\code\php\amlhc\application\common\library\Auth.php`
- Token-based: UUID tokens stored in MySQL token table
- Token default lifetime: 2,592,000 seconds (30 days)
- Password hashing: Same double MD5 + salt as admin
- Features:
  - Login by username, email, or mobile
  - User groups and rules (`fa_user_group`, `fa_user_rule`)
  - Score and money log tracking (`fa_money_log`, `fa_score_log`)
  - Hook events: `user_init_successed`, `user_register_successed`, `user_login_successed`, `user_logout_successed`, `user_changepwd_successed`, `user_delete_successed`
- Tables: `fa_user`, `fa_user_group`, `fa_user_rule`

**API Auth:**
- Token passed via `HTTP_TOKEN` header, `token` POST param, or Cookie
- Controller base: `D:\code\php\amlhc\application\common\controller\Api.php`
- HTTP 401 for unauthorized, 403 for forbidden
- CORS handling via `check_cors_request()`

**Captcha:**
- ThinkPHP captcha (`topthink/think-captcha` ^1.0.9) - Image-based, 4 characters, size 130x40
- Text captcha - For user registration (`fastadmin.user_register_captcha: text`)
- Login captcha: disabled by default (`fastadmin.login_captcha: false`)
- Generated via: `D:\code\php\amlhc\application\api\controller\Common.php` `captcha()` method (large format: 350x150)

## Queue System

**Think-Queue (Redis-backed):**
- Package: `topthink/think-queue` 1.1.6
- Connector: Redis (`D:\code\php\amlhc\application\extra\queue.php`)
- Default queue: `default`
- Config: `application/extra/queue.php`
  - Redis host: `127.0.0.1:6379`
  - No password by default
  - Persistent connection: disabled
  - Task expire: `0` (no expiration)
- CLI: `php think queue:work` / `php think queue:listen` for processing

## Addon/Plugin System

**FastAdmin Addons:**
- Package: `fastadminnet/fastadmin-addons` ~1.4.0
- Location: `addons/` directory
- Config: `D:\code\php\amlhc\application\extra\addons.php`
  - Autoload: `false` (manual loading)
  - Hooks: empty by default (configured per addon)
  - Routes: empty by default (configured per addon)
- PSR-4 autoload: `addons\` -> `addons/` (`composer.json`)
- Addon lifecycle: `install()`, `uninstall()`, `enable()`, `disable()` methods
- Example addon: `D:\code\php\amlhc\addons\command\Command.php`
  - Installs menu entries via `Menu::create()`
  - Deletes menu on uninstall via `Menu::delete()`
  - Enable/disable toggles menu visibility
- Pure mode: removes `application/`, `public/`, `assets/` from addon packages when enabled (`fastadmin.addon_pure_mode: true`)
- Unknown source addons: blocked by default (`fastadmin.unknownsources: false`)
- Backup global files on addon enable/disable: enabled (`fastadmin.backup_global_files: true`)
- CLI: `php think addon` for addon management
- Admin controller: `D:\code\php\amlhc\application\admin\controller\Addon.php`

## ThinkPHP Hooks & Behaviors

**Hook Integration Points:**
- `upload_config_init` - Called when upload config is initialized (`Backend.php`, `Frontend.php`, `Api.php`)
- `config_init` - Called after config assembly (`Backend.php`, `Frontend.php`)
- `admin_nologin` - Fired when admin access is denied due to no login (`Backend.php` line 145)
- `admin_nopermission` - Fired when admin access is denied due to no permission (`Backend.php` line 158)
- `admin_sidebar_begin` - Fired before sidebar rendering (`Auth.php` line 429)
- `user_init_successed` - Fired on successful frontend user init (`common/library/Auth.php` line 115)
- `user_register_successed` - Fired on user registration (`common/library/Auth.php` line 194)
- `user_login_successed` - Fired on user login (`common/library/Auth.php` line 334)
- `user_logout_successed` - Fired on user logout (`common/library/Auth.php` line 256)
- `user_changepwd_successed` - Fired on password change (`common/library/Auth.php` line 283)
- `user_delete_successed` - Fired on user deletion (`common/library/Auth.php` line 474)

**Tags/Behaviors:** Configured in `application/tags.php` with `addon_begin` behavior hook

## Email

**Mailer:**
- Package: `fastadminnet/fastadmin-mailer` ^2.0.0
- SMTP Configuration (`D:\code\php\amlhc\application\extra\site.php`):
  - Type: `1` (SMTP)
  - Host: `smtp.qq.com`
  - Port: `465` (SSL)
  - Verification type: `2` (SSL/TLS)
  - Username/password: configured via admin panel (empty by default)
  - Mail from address: configured via admin panel
- Used for: email verification, password reset, notifications
- Config groups: `basic`, `email`, `dictionary`, `user`, `example`

## Monitoring & Observability

**Error Tracking:**
- None configured

**Logs:**
- File-based logging (`application/config.php` `log.type => File`, path: `LOG_PATH` typically `runtime/log/`)
- Level: empty array (logs all levels by default)
- Auto-record admin logs enabled (`fastadmin.auto_record_log: true`)

**Debug/Trace:**
- App debug mode: configurable via `app.debug` env var (default: `false`)
- App trace: configurable via `app.trace` env var (default: `false`)
- SQL explain: disabled by default

## CI/CD & Deployment

**Hosting:**
- Self-hosted PHP deployment
- Web server entry: `D:\code\php\amlhc\public\index.php`
- Router compatibility: `D:\code\php\amlhc\public\router.php` for PHP built-in server
- Admin entry: formerly `public/admin.php` (deleted per git status)
- Install script: formerly `public/install.php` (deleted per git status)

**CI Pipeline:**
- Not detected

## Environment Configuration

**Required env vars** (via `think\Env` in config files):
```
[app]
debug = false
trace = false

[database]
hostname = 127.0.0.1
database = fastadmin
username = root
password = (configured)
hostport = (configured)
prefix = fa_
charset = utf8mb4
debug = false
```

**Secrets location:**
- `.env` file (present, not committed)
- Database credentials in env vars
- SMTP credentials in admin-configurable site settings (`application/extra/site.php`)
- WeChat app credentials managed via WeChat addon
- Token key: hardcoded in `application/config.php` `token.key`

## Webhooks & Callbacks

**Incoming:**
- Not detected in base configuration
- Addons may register their own webhook endpoints

**Outgoing:**
- FastAdmin API calls to `https://api.fastadmin.net` for addon marketplace
- Lottery data scraping to `https://history.macaumarksix.com` (Guzzle HTTP GET)
- Email sending via SMTP (qq.com)

## Internationalization

**Supported Languages:**
- `zh-cn` (Simplified Chinese) - Default
- `en` (English) (`application/config.php` `allow_lang_list`)
- Multi-language: disabled by default (`lang_switch_on: false`)
- Language files in `application/*/lang/zh-cn/`
- Language loading per controller in base classes (`loadlang()` method)
- Recent additions: `D:\code\php\amlhc\application\admin\lang\zh-cn\command.php`, `D:\code\php\amlhc\application\admin\lang\zh-cn\history.php`

## CORS

**Allowed Origins:**
- `localhost`, `127.0.0.1` (`application/config.php` `fastadmin.cors_request_domain`)
- Configurable via `fastadmin.cors_request_domain`
- API module sets CORS headers in `D:\code\php\amlhc\application\api\controller\Common.php` `_initialize()` (line 26-28): exposes `__token__` header for cross-origin token retrieval

## Upload Integration

**Upload Flow:**
1. Client uploads to `ajax/upload` (index module) or `api/common/upload` (API module)
2. `app\common\library\Upload` class handles validation and storage
3. Files stored in `public/uploads/{year}{mon}{day}/{filemd5}{.suffix}`
4. Attachment record created in `fa_attachment` table via `app\common\model\Attachment`
5. CDN URL returned if `cdnurl` is configured

---

*Integration audit: 2026-04-21*
