Files
dewemoji-api/app/controllers/Emojis.php
2025-08-30 14:36:00 +07:00

178 lines
5.9 KiB
PHP

<?php
// app/controllers/Emojis.php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__.'/../helpers/auth.php';
require_once __DIR__.'/../helpers/filters.php';
require_once __DIR__.'/../helpers/usage.php';
// Plan + whitelist
$planInfo = resolve_plan();
$isPro = $planInfo['pro'];
$isWl = $planInfo['whitelist'];
$acct = $planInfo['account'];
$key = $planInfo['key'];
$planName = $isPro ? 'pro' : ($isWl ? 'whitelist' : 'free');
// Caps
$maxLimit = $isPro ? 50 : 20;
$maxPages = $isPro ? 20 : 5;
if ($isWl) { $maxLimit = 100; $maxPages = 1000; }
// Params
$qParam = trim((string)($_GET['q'] ?? ''));
$catParam = trim((string)($_GET['category'] ?? ''));
$subParam = trim((string)($_GET['subcategory'] ?? ''));
$page = max((int)($_GET['page'] ?? 1), 1);
$limit = min(max((int)($_GET['limit'] ?? $maxLimit), 1), $maxLimit);
// Category map (slugs → labels)
$CATEGORY_MAP = [
'all'=>'all','smileys'=>'Smileys & Emotion','people'=>'People & Body','animals'=>'Animals & Nature','food'=>'Food & Drink','travel'=>'Travel & Places','activities'=>'Activities','objects'=>'Objects','symbols'=>'Symbols','flags'=>'Flags'
];
$catLabel = '';
if ($catParam !== '' && strtolower($catParam) !== 'all') {
$catLabel = $CATEGORY_MAP[strtolower($catParam)] ?? $catParam;
}
$subSlug = $subParam !== '' ? dw_slugify($subParam) : '';
$q = $qParam; $cat = $catLabel; $sub = $subSlug;
// Usage (Free counted, Pro/WL unlimited)
$limitDaily = $isWl ? null : ($isPro ? null : (int)cfg('free_daily_limit', 50));
$bucket = bucket_id($key);
$ymd = day_key();
$usage = usage_load($bucket, $ymd);
if ($limitDaily !== null) $usage['limit'] = $limitDaily;
$signature = sig_query($q, $cat, $sub);
$sigKey = $signature.'|p1'; // only page 1 increments
$atCap = false;
if ($limitDaily !== null && $page === 1 && !isset($usage['seen'][$sigKey])) {
if ($usage['used'] >= $limitDaily) {
$atCap = true;
} else {
$usage['used'] = (int)$usage['used'] + 1;
$usage['seen'][$sigKey] = 1;
usage_save($bucket, $ymd, $usage);
}
}
if ($page > $maxPages) {
echo json_encode(['items'=>[],'page'=>$page,'limit'=>$limit,'total'=>0,'plan'=>$planName,'message'=>'Page limit reached for your plan.']);
exit;
}
// Soft cap
if ($atCap) {
header('X-Dewemoji-Plan: '.$planName);
if ($limitDaily === null) {
header('X-RateLimit-Limit: unlimited'); header('X-RateLimit-Remaining: unlimited');
} else {
header('X-RateLimit-Limit: '.$usage['limit']); header('X-RateLimit-Remaining: 0');
}
header('X-RateLimit-Reset: '.strtotime('tomorrow 00:00:00 UTC'));
echo json_encode([
'items'=>[],'page'=>$page,'limit'=>$limit,'total'=>0,'plan'=>$planName,
'usage'=>[
'used'=>(int)$usage['used'],
'limit'=>$limitDaily,
'remaining'=> $limitDaily===null ? null : max(0, $limitDaily - (int)$usage['used']),
'window'=>'daily',
'window_ends_at'=>gmdate('c', strtotime('tomorrow 00:00:00 UTC')),
'count_basis'=>'distinct_query'
],
'message'=>'Daily free limit reached. Upgrade to Pro for unlimited usage.'
]);
exit;
}
// Load data
$DATA_PATHS = [
__DIR__.'/../data/emojis.json',
__DIR__.'/../../data/emojis.json', // fallback if you keep old path
];
$json = null;
foreach ($DATA_PATHS as $p) { if (is_file($p)) { $json = file_get_contents($p); break; } }
if ($json === null) { http_response_code(500); echo json_encode(['error'=>'data_not_found']); exit; }
$data = json_decode($json, true) ?: [];
$items = $data['emojis'] ?? [];
// Filter
$items = array_values(array_filter($items, function($e) use ($q,$cat,$sub) {
if ($cat !== '') {
if (dw_slugify($e['category'] ?? '') !== dw_slugify($cat)) return false;
}
if ($sub !== '') {
if (dw_slugify($e['subcategory'] ?? '') !== $sub) return false;
}
if ($q !== '') {
$hay = strtolower(implode(' ', [
$e['emoji'] ?? '', $e['name'] ?? '', $e['slug'] ?? '',
$e['category'] ?? '', $e['subcategory'] ?? '',
implode(' ', $e['keywords_en'] ?? []),
implode(' ', $e['keywords_id'] ?? []),
implode(' ', $e['aliases'] ?? []),
implode(' ', $e['shortcodes'] ?? []),
]));
foreach (preg_split('/\s+/', strtolower($q)) as $tok) {
if ($tok !== '' && strpos($hay, $tok) === false) return false;
}
}
return true;
}));
$total = count($items);
$offset = ($page - 1) * $limit;
$items = array_slice($items, $offset, $limit);
// Shape + tone
$items = array_map(function($raw) use ($planName, $isPro) {
$e = filterEmoji($raw, $planName, true);
$e['supports_skin_tone'] = dw_supports_skin_tone($raw) || dw_supports_skin_tone($e);
$e['skin_tone_modifiers'] = dw_skin_tone_modifiers();
if ($e['supports_skin_tone'] && !empty($e['emoji'])) {
$base = dw_strip_tone($e['emoji']);
if ($base !== '') {
$e['emoji_base'] = $base;
if ($isPro) { $e['variants'] = dw_build_tone_variants($base); }
}
}
return $e;
}, $items);
// ETag (exclude dynamic usage)
$etag = '"'.sha1(json_encode([$page,$limit,$q,$cat,$sub,$planName,$total,$items])).'"';
header('ETag: '.$etag);
header('Cache-Control: public, max-age=120');
if (($_SERVER['HTTP_IF_NONE_MATCH'] ?? '') === $etag) { http_response_code(304); exit; }
// Rate-limit headers
header('X-Dewemoji-Plan: '.$planName);
if ($limitDaily === null) {
header('X-RateLimit-Limit: unlimited'); header('X-RateLimit-Remaining: unlimited');
} else {
header('X-RateLimit-Limit: '.$usage['limit']);
header('X-RateLimit-Remaining: '.max(0, $usage['limit'] - (int)$usage['used']));
}
header('X-RateLimit-Reset: '.strtotime('tomorrow 00:00:00 UTC'));
// Response
echo json_encode([
'items'=>$items,
'page'=>$page,
'limit'=>$limit,
'total'=>$total,
'plan'=>$isPro ? 'pro' : 'free',
'usage'=>[
'used'=>(int)$usage['used'],
'limit'=>$limitDaily,
'remaining'=> $limitDaily===null ? null : max(0, $limitDaily - (int)$usage['used']),
'window'=>'daily',
'window_ends_at'=>gmdate('c', strtotime('tomorrow 00:00:00 UTC')),
'count_basis'=>'distinct_query'
],
], JSON_UNESCAPED_UNICODE);