make(\Illuminate\Contracts\Console\Kernel::class);
$__kernel->bootstrap();
define('AN_STANDALONE', true);
}
/* ===================== Helper + License ===================== */
/** .env reader: config:cache dileo kaj kore */
final class AnEnv
{
private static ?array $file = null;
public static function get(string $key, $default = null)
{
$v = env($key);
if ($v !== null && $v !== '') { return $v; }
if (self::$file === null) {
self::$file = [];
$p = base_path('.env');
if (is_file($p)) {
foreach (preg_split('/\R/', (string) file_get_contents($p)) as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) { continue; }
[$k, $val] = explode('=', $line, 2);
$val = trim($val);
if ($val !== '' && ($val[0] === '"' || $val[0] === "'")) {
$q = $val[0];
$val = substr($val, 1, (strrpos($val, $q) ?: strlen($val)) - 1);
} else {
$val = trim(preg_replace('/\s+#.*$/', '', $val));
}
self::$file[trim($k)] = $val;
}
}
}
$v = self::$file[$key] ?? null;
return ($v !== null && $v !== '') ? $v : $default;
}
}
/** Site er local state (install id, domain, license key) */
final class AnState
{
public static function dir(): string
{
static $d = null;
if ($d) { return $d; }
$c = storage_path('app');
if (!is_dir($c) || !is_writable($c)) { $c = __DIR__; }
return $d = $c;
}
public static function file(): string { return self::dir() . '/.autonews_state.json'; }
public static function load(): array
{
$f = self::file();
if (!is_file($f)) { return []; }
$j = json_decode((string) @file_get_contents($f), true);
return is_array($j) ? $j : [];
}
public static function save(array $s): void
{
@file_put_contents(self::file(), json_encode($s), LOCK_EX);
@chmod(self::file(), 0600);
}
}
/**
* License guard — ekta-i jaygay check (entry, command, AI step shobai eta use kore)
* - Fail-CLOSED: server down / ভুল response / signature mile na => BLOCK
* - Credentials (Groq / Facebook / feeds) shudhu license valid thakle pawa jay
*/
final class AnGuard
{
const SERVER = 'https://mtechsolutionbd.com/license-manager/';
const PUBLIC_KEY = 'BHPC05kz2S1o47qX703fGWxyv5QA5DQLFkOEw0i6STk=';
const VERSION = '2.0';
private static ?array $memo = null;
private static array $cfg = [];
private static function detectDomain(): string
{
$host = $_SERVER['HTTP_HOST'] ?? '';
if ($host === '') { $host = (string) parse_url((string) config('app.url'), PHP_URL_HOST); }
$host = strtolower(trim($host));
$host = preg_replace('/:\d+$/', '', $host);
return preg_replace('/^www\./', '', $host);
}
public static function domain(): string
{
$st = AnState::load();
return !empty($st['domain']) ? $st['domain'] : self::detectDomain();
}
/** @return array{0:bool,1:string,2:string} [allowed, message, status] */
public static function check(): array
{
if (self::$memo && self::$memo['t'] > time() - 30) { return self::$memo['r']; }
$r = self::verify();
self::$memo = ['t' => time(), 'r' => $r];
return $r;
}
private static function verify(): array
{
if (self::PUBLIC_KEY === '' || strpos(self::PUBLIC_KEY, 'PASTE_') === 0) {
return [false, 'AutoNewsKit.php er PUBLIC_KEY boshano hoyni', 'config'];
}
if (!function_exists('sodium_crypto_sign_verify_detached')) {
return [false, 'PHP sodium extension chalu nei (hosting e chalu korte bolo)', 'config'];
}
$st = AnState::load();
if (empty($st['iid'])) { $st['iid'] = bin2hex(random_bytes(16)); }
if (empty($st['domain'])) { $st['domain'] = self::detectDomain(); }
AnState::save($st); // register er age save — server proof chaile iid lagbe
if (empty($st['key'])) {
[$ok, $msg, $status, $key] = self::register($st);
if (!$ok) { return [false, $msg, $status]; }
$st['key'] = $key;
AnState::save($st);
}
return self::remoteVerify($st);
}
private static function register(array $st): array
{
$url = '';
if (PHP_SAPI !== 'cli' && !empty($_SERVER['HTTP_HOST'])) {
$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
$url = ($https ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . ($_SERVER['SCRIPT_NAME'] ?? '');
}
try {
$r = Http::asForm()->timeout(30)->post(self::SERVER, [
'action' => 'register', 'domain' => $st['domain'], 'iid' => $st['iid'],
'name' => (string) config('app.name'), 'url' => $url, 'ver' => self::VERSION,
]);
} catch (\Throwable $e) {
return [false, 'License server e connect hocche na', 'offline', null];
}
$j = $r->json();
if (!$r->successful() || !is_array($j)) { return [false, 'License server error', 'offline', null]; }
if (empty($j['ok']) || empty($j['key'])) {
return [false, (string) ($j['message'] ?? 'Registration failed'), (string) ($j['status'] ?? 'invalid'), null];
}
return [true, 'Registered', (string) ($j['status'] ?? 'pending'), (string) $j['key']];
}
private static function remoteVerify(array $st): array
{
try {
$r = Http::asForm()->timeout(20)->post(self::SERVER, [
'action' => 'verify', 'domain' => $st['domain'], 'key' => $st['key'],
'iid' => $st['iid'], 'ver' => self::VERSION,
]);
} catch (\Throwable $e) {
return [false, 'License server e connect hocche na', 'offline'];
}
if (!$r->successful()) { return [false, 'License server error (' . $r->status() . ')', 'offline']; }
$j = $r->json();
if (!is_array($j)) { return [false, 'License response invalid', 'offline']; }
if (($j['allowed'] ?? null) !== true) {
return [false, (string) ($j['message'] ?? 'Subscription Deactivated'), (string) ($j['status'] ?? 'inactive')];
}
$res = self::readSigned((string) ($j['payload'] ?? ''), (string) ($j['sig'] ?? ''), $st);
if (!$res['ok']) { return [false, $res['err'], 'invalid']; }
self::$cfg = (array) ($res['d']['cfg'] ?? []);
return [true, 'OK, expire: ' . date('Y-m-d', (int) $res['d']['exp']), 'active'];
}
private static function readSigned(string $payload, string $sig, array $st): array
{
$fail = fn(string $m) => ['ok' => false, 'err' => $m, 'd' => null];
$pub = base64_decode(self::PUBLIC_KEY, true);
$raw = base64_decode($sig, true);
if (!$pub || !$raw || strlen($pub) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES) { return $fail('License response signature invalid'); }
if (!sodium_crypto_sign_verify_detached($raw, $payload, $pub)) { return $fail('License response signature mile nai'); }
$d = json_decode((string) base64_decode($payload, true), true);
if (!is_array($d) || empty($d['exp']) || empty($d['ts'])) { return $fail('License data invalid'); }
if (strcasecmp((string) ($d['domain'] ?? ''), $st['domain']) !== 0) { return $fail('License ei domain er jonno na'); }
if (!hash_equals((string) ($d['kh'] ?? ''), hash('sha256', $st['key']))) { return $fail('License key mile nai'); }
if (abs(time() - (int) $d['ts']) > 3600) { return $fail('Server er shomoy mile nai — hosting er clock thik korun'); }
if (time() > (int) $d['exp']) { return $fail('Subscription expire hoye geche'); }
return ['ok' => true, 'err' => '', 'd' => $d];
}
/** License valid na hole kokhono kichu dey na (.env fallback o na) */
public static function cfg(string $name, string $env = ''): string
{
if (!self::check()[0]) { return ''; }
$v = $name !== '' ? trim((string) (self::$cfg[$name] ?? '')) : '';
if ($v !== '') { return $v; }
return $env !== '' ? trim((string) AnEnv::get($env, '')) : '';
}
public static function feeds(): array
{
if (!self::check()[0]) { return []; }
$f = self::$cfg['feeds'] ?? [];
return is_array($f) ? array_values(array_filter(array_map('trim', $f))) : [];
}
}
/** Blocked / pending page (apnar ager WhatsApp wala design) */
final class AnUi
{
public static function blocked(string $domain, string $reason, string $status): string
{
$pending = ($status === 'pending');
$title = $pending ? 'অনুমোদনের অপেক্ষায়' : 'অটো-নিউজ ইঞ্জিন সাময়িক স্থগিত';
$subtitle = $pending
? 'আপনার সাইট সফলভাবে নিবন্ধিত হয়েছে। অ্যাডমিন অনুমোদন দিলেই অটো নিউজ সিস্টেম চালু হবে।'
: ($status === 'offline'
? 'লাইসেন্স সার্ভারের সাথে এই মুহূর্তে সংযোগ করা যাচ্ছে না। কিছুক্ষণ পর আবার চেষ্টা করুন।'
: 'এই ডোমেইনের AI অটোমেশন সাবস্ক্রিপশনটি নিষ্ক্রিয় রয়েছে। সেবাটি পুনরায় সচল করতে দ্রুত লাইসেন্স রিনিউ করুন।');
if ($status === 'unverified') {
$title = 'ডোমেইন যাচাই করা যায়নি';
$subtitle = 'সাইটটি ইন্টারনেট থেকে খোলা যাচ্ছে কিনা নিশ্চিত করে (firewall/Cloudflare এ বাধা না থাকলে) আবার ফাইলটি খুলুন। সমস্যা থাকলে সাপোর্টে যোগাযোগ করুন।';
}
$domain = htmlspecialchars($domain, ENT_QUOTES, 'UTF-8');
$reason = htmlspecialchars($reason, ENT_QUOTES, 'UTF-8');
$waText = urlencode("Hello M Tech Solution Support, I need to activate/reactivate the AI Auto-News Engine for domain: {$domain}. Status: {$reason}.");
$waLink = "https://wa.me/8801999466391?text={$waText}";
return "
Service Suspended
";
}
}
/* ===================== News command (apnar ager code, license gate shoho) ===================== */
class FetchNewsCommand extends Command
{
protected $signature = 'autonews:run {--card-test : Build a sample photo card to public/card-test.jpg and exit}';
protected $description = 'Automated news generator with clean non-crashing photo card and guaranteed comment link';
private $lastEngine = 'plain';
private $engineCache = null;
private $imBase = null;
public function handle()
{
if ($this->option('card-test')) {
return $this->runCardTest();
}
// License gate (server verify + signed response). Fail-closed.
[$allowed, $reason] = AnGuard::check();
if (!$allowed) {
$this->info("Service suspended: {$reason}");
return;
}
$gemini = new GeminiService();
$availableCategories = [];
try {
$cats = Category::all();
foreach ($cats as $cat) {
$name = $cat->category_name ?? $cat->name ?? $cat->title ?? null;
if ($name) { $availableCategories[$cat->id] = $name; }
}
} catch (\Throwable $e) {}
$feeds = AnGuard::feeds() ?: [
'https://www.prothomalo.com/feed',
'https://www.prothomalo.com/feed/bangladesh',
'https://www.prothomalo.com/feed/international',
'https://www.prothomalo.com/feed/economy',
'https://www.prothomalo.com/feed/sports',
'https://www.prothomalo.com/feed/entertainment'
];
$targetItem = null;
$uniqueKey = null;
$cleanLink = null;
foreach ($feeds as $feedUrl) {
try {
$response = Http::withoutVerifying()->timeout(15)->get($feedUrl);
if ($response->successful()) {
$xml = @simplexml_load_string($response->body());
if ($xml && isset($xml->channel->item)) {
foreach ($xml->channel->item as $item) {
$rawLink = trim((string)$item->link);
$clean = strtok($rawLink, '?');
$linkPath = parse_url($clean, PHP_URL_PATH) ?? $clean;
$articleSlug = basename(rtrim($linkPath, '/'));
$lockKey = 'posted_rss_' . md5($articleSlug);
if (Cache::has($lockKey)) continue;
if (Post::where('rss_link', 'LIKE', "%{$articleSlug}%")->exists()) {
Cache::forever($lockKey, true);
continue;
}
$targetItem = $item;
$uniqueKey = $lockKey;
$cleanLink = $clean;
break 2;
}
}
}
} catch (\Throwable $e) { continue; }
}
if (!$targetItem) {
$this->info("All feed items already posted.");
return;
}
Cache::forever($uniqueKey, true);
$rawTitle = trim((string)$targetItem->title);
$rawDescription = strip_tags((string)$targetItem->description);
$articleUrl = (string)$targetItem->link;
$aiNews = $gemini->rewriteNews($rawTitle, $rawDescription, $availableCategories);
if (!$aiNews || empty($aiNews['title']) || empty($aiNews['content'])) {
Cache::forget($uniqueKey);
$this->info("Content generation failed.");
return;
}
$finalTitle = trim($aiNews['title']);
if (empty($finalTitle)) {
$finalTitle = $rawTitle;
}
$finalCategoryId = 55;
if (!empty($aiNews['category_id']) && (isset($availableCategories[$aiNews['category_id']]) || Category::where('id', $aiNews['category_id'])->exists())) {
$finalCategoryId = (int)$aiNews['category_id'];
}
$imageUrl = null;
try {
$pageRes = Http::withoutVerifying()->timeout(12)->withHeaders(['User-Agent' => 'Mozilla/5.0'])->get($articleUrl);
if ($pageRes->successful() && preg_match('/ ]+property=[\'"]og:image[\'"][^>]+content=[\'"]([^\'"]+)[\'"]/i', $pageRes->body(), $m)) {
$imageUrl = html_entity_decode($m[1]);
}
} catch (\Throwable $e) {}
if (!$imageUrl && isset($targetItem->description)) {
if (preg_match('//i', (string)$targetItem->description, $m)) {
$imageUrl = $m[1];
}
}
// Clean website image crop
$webStream = null;
if ($imageUrl) {
try {
$imgRes = Http::withoutVerifying()->timeout(15)->get($imageUrl);
if ($imgRes->successful() && strlen($imgRes->body()) > 2000) {
$rawStream = $imgRes->body();
$src = @imagecreatefromstring($rawStream);
if ($src) {
$w = imagesx($src);
$h = imagesy($src);
// Keep only the top part of the image (default 88%), so the bottom ~12% is cropped off. Change with NEWS_IMAGE_KEEP in .env (e.g. 0.85 = crop more)
$keep = (float) AnEnv::get('NEWS_IMAGE_KEEP', 0.88);
if ($keep < 0.5 || $keep > 1) { $keep = 0.88; }
$cropH = (int)($h * $keep);
$canvas = imagecreatetruecolor($w, $cropH);
imagecopyresampled($canvas, $src, 0, 0, 0, 0, $w, $cropH, $w, $cropH);
imagedestroy($src);
ob_start();
imagejpeg($canvas, null, 92);
$webStream = ob_get_clean();
imagedestroy($canvas);
} else {
$webStream = $rawStream;
}
}
} catch (\Throwable $err) {}
}
// Banner is drawn inside the bottom of the news image (website) and inside the photo area of the Facebook card
$banner = null; // banner no longer downloaded/used on the thumbnail
$plainStream = $webStream;
// Ad banner overlay on the website thumbnail is disabled (banner removed from thumbnail)
// if ($webStream && $banner) {
// $webStream = $this->addBannerOverlay($webStream, $banner);
// }
$savedImageName = null;
if ($webStream) {
$webRoot = dirname(base_path());
$dir1 = $webRoot . '/assets/images/post';
$dir2 = public_path('assets/images/post');
foreach ([$dir1, $dir2] as $dir) {
if (!File::isDirectory($dir)) {
File::makeDirectory($dir, 0777, true, true);
}
}
$filename = time() . Str::random(8) . '.jpg';
File::put($dir1 . '/' . $filename, $webStream);
@chmod($dir1 . '/' . $filename, 0755);
File::put($dir2 . '/' . $filename, $webStream);
@chmod($dir2 . '/' . $filename, 0755);
$savedImageName = $filename;
}
// Database post creation
$post = Post::create([
'title' => $finalTitle,
'slug' => Str::slug($finalTitle) . '-' . Str::random(6),
'description' => $aiNews['content'],
'short_description' => mb_substr(strip_tags($aiNews['content']), 0, 160, 'utf-8'),
'image_big' => $savedImageName,
'image_small' => $savedImageName,
'rss_link' => $cleanLink,
'category_id' => $finalCategoryId,
'language_id' => 1,
'admin_id' => 1,
'user_id' => 0,
'status' => 'true',
'post_type' => 'article',
'is_pending' => 0,
'is_draft' => 0,
'is_feature' => 1,
'is_slider' => 1,
'is_trending' => 1,
'show_right_column' => 0,
'slider_left' => 0,
'slider_right' => 0,
'is_videoGallery' => 0,
'schedule_post' => 0,
]);
// Facebook Auto Post with Clean Non-Crashing Photo Card & Guaranteed Comment Link
try {
$pageId = AnGuard::cfg('fb_page_id', 'FACEBOOK_PAGE_ID');
$pageAccessToken = AnGuard::cfg('fb_token', 'FACEBOOK_PAGE_ACCESS_TOKEN');
if (!empty($pageId) && !empty($pageAccessToken) && !empty($savedImageName)) {
$articleRouteUrl = URL::route('frontend.postBySubcategory.details', [$post->id, $post->slug]);
// Generate professional HD photo card (1440x1440) in memory; branding comes from the database
// Card is built from the plain image; the banner is drawn on the card's photo by buildPhotoCard
$imagePath = storage_path('app/card-src-' . Str::random(8) . '.jpg');
File::put($imagePath, $plainStream ?: $webStream);
$catName = (string) ($availableCategories[$finalCategoryId] ?? '');
$cardBinary = $this->buildNewsCard($imagePath, $finalTitle, $post->created_at, $catName);
if (!$cardBinary) { $cardBinary = $this->buildPhotoCard($imagePath, $finalTitle, $post->created_at, null); }
if (!$cardBinary) { Log::error('AutoNewsKit: photo card could not be built (font / GD / Imagick) - plain image will be posted'); }
// Fallback: if card design fails for any reason, post the plain news image
if (!$cardBinary && file_exists($imagePath)) {
$cardBinary = file_get_contents($imagePath);
}
@unlink($imagePath);
if (!$cardBinary) {
throw new \Exception('Photo card could not be created');
}
// Step 1: Binary Photo Upload to Facebook Page
$photoRes = Http::withoutVerifying()->timeout(45)
->attach('source', $cardBinary, 'photocard.jpg')
->post("https://graph.facebook.com/v18.0/{$pageId}/photos", [
'caption' => $finalTitle . "\n\nবিস্তারিত পড়ুন কমেন্টে 👇",
'access_token' => $pageAccessToken
]);
if ($photoRes->successful()) {
usleep(1500000); // 1.5 seconds delay
// Step 2: Fetch latest post ID from page feed
$feedRes = Http::withoutVerifying()->timeout(15)->get("https://graph.facebook.com/v18.0/{$pageId}/posts", [
'limit' => 1,
'access_token' => $pageAccessToken
]);
$targetPostId = null;
if ($feedRes->successful()) {
$postsData = $feedRes->json('data');
if (!empty($postsData[0]['id'])) {
$targetPostId = $postsData[0]['id'];
}
}
if (!$targetPostId) {
$resData = $photoRes->json();
$photoId = $resData['id'] ?? null;
$targetPostId = $resData['post_id'] ?? ($pageId . '_' . $photoId);
}
// Step 3: Guaranteed Comment Link
if ($targetPostId) {
$commentRes = Http::withoutVerifying()->timeout(20)->post("https://graph.facebook.com/v18.0/{$targetPostId}/comments", [
'message' => "বিস্তারিত পড়ুন: " . $articleRouteUrl,
'access_token' => $pageAccessToken
]);
if (!$commentRes->successful()) {
Log::error("FB Comment API Error: " . $commentRes->body());
}
}
} else {
Log::error("FB Photo Binary Upload Error: " . $photoRes->body());
}
}
} catch (\Throwable $fbErr) {
Log::error("Facebook Exception Error: " . $fbErr->getMessage());
}
echo "";
echo "
Clean Photo Card ebong Comment Link Shothikvabe Complete Hoyeche! ";
echo "
Post ID: {$post->id}
";
echo "
Title: {$post->title}
";
if ($savedImageName) {
echo "
";
}
echo "
";
}
/**
* Telegram reporter er khobor: AI rewrite chhara, sorasori portal e post + Facebook photo card + comment e link.
* (Notun add-on method — handle() ba RSS flow er kono poriborton nei.)
* @return array{ok:bool,id:int,url:string,fb:string,err:string}
*/
public function publishDirect(string $title, string $contentHtml, string $imageBytes, string $sourceKey): array
{
$out = ['ok' => false, 'id' => 0, 'url' => '', 'fb' => '', 'err' => '', 'cat' => ''];
[$allowed, $reason] = AnGuard::check();
if (!$allowed) { $out['err'] = 'license: ' . $reason; return $out; }
$availableCategories = [];
try {
foreach (Category::all() as $cat) {
$name = $cat->category_name ?? $cat->name ?? $cat->title ?? null;
if ($name) { $availableCategories[$cat->id] = $name; }
}
} catch (\Throwable $e) {}
// RSS flow er moto default 55; oi category na thakle prothom category
$catId = (int) AnEnv::get('TG_CATEGORY_ID', 55);
try {
if (!Category::where('id', $catId)->exists()) {
$first = Category::query()->value('id');
if ($first) { $catId = (int) $first; }
}
} catch (\Throwable $e) {}
// AI shudhu category bachbe (lekha bodlay na). Site e na thakle notun category toiri hoy. TG_AI_CATEGORY=0 dile bondho
if ((string) AnEnv::get('TG_AI_CATEGORY', '1') !== '0') {
try {
$aiName = AnTg::pickCategory($title, strip_tags($contentHtml), array_values($availableCategories));
if ($aiName !== '') {
$id = $this->tgMatchCategory($aiName, $availableCategories);
if (!$id) {
$id = $this->tgCreateCategory($aiName, $catId);
if ($id) { $availableCategories[$id] = $aiName; }
}
if ($id) { $catId = $id; }
}
} catch (\Throwable $e) {
Log::error('AutoNewsKit Telegram category: ' . $e->getMessage());
}
}
$out['cat'] = (string) ($availableCategories[$catId] ?? '');
// Chhobi save (RSS flow er moto duita folder e)
$webRoot = dirname(base_path());
$dir1 = $webRoot . '/assets/images/post';
$dir2 = public_path('assets/images/post');
foreach ([$dir1, $dir2] as $dir) {
if (!File::isDirectory($dir)) { File::makeDirectory($dir, 0777, true, true); }
}
$filename = time() . Str::random(8) . '.jpg';
File::put($dir1 . '/' . $filename, $imageBytes);
@chmod($dir1 . '/' . $filename, 0755);
File::put($dir2 . '/' . $filename, $imageBytes);
@chmod($dir2 . '/' . $filename, 0755);
$post = Post::create([
'title' => $title,
'slug' => Str::slug($title) . '-' . Str::random(6),
'description' => $contentHtml,
'short_description' => mb_substr(strip_tags($contentHtml), 0, 160, 'utf-8'),
'image_big' => $filename,
'image_small' => $filename,
'rss_link' => $sourceKey,
'category_id' => $catId,
'language_id' => 1,
'admin_id' => 1,
'user_id' => 0,
'status' => 'true',
'post_type' => 'article',
'is_pending' => 0,
'is_draft' => 0,
'is_feature' => 1,
'is_slider' => 1,
'is_trending' => 1,
'show_right_column' => 0,
'slider_left' => 0,
'slider_right' => 0,
'is_videoGallery' => 0,
'schedule_post' => 0,
]);
$articleRouteUrl = URL::route('frontend.postBySubcategory.details', [$post->id, $post->slug]);
$out['ok'] = true;
$out['id'] = (int) $post->id;
$out['url'] = $articleRouteUrl;
// Facebook photo card + comment e link (post id sorasori response theke, feed theke na — race hobe na)
try {
$pageId = AnGuard::cfg('fb_page_id', 'FACEBOOK_PAGE_ID');
$pageAccessToken = AnGuard::cfg('fb_token', 'FACEBOOK_PAGE_ACCESS_TOKEN');
if (empty($pageId) || empty($pageAccessToken)) { $out['fb'] = 'skip: Facebook Page ID/Token nei'; return $out; }
$imagePath = storage_path('app/card-src-' . Str::random(8) . '.jpg');
File::put($imagePath, $imageBytes);
$catName = (string) ($availableCategories[$catId] ?? '');
$cardBinary = $this->buildNewsCard($imagePath, $title, $post->created_at, $catName);
if (!$cardBinary) { $cardBinary = $this->buildPhotoCard($imagePath, $title, $post->created_at, null); }
if (!$cardBinary) { Log::error('AutoNewsKit Telegram: photo card could not be built - plain image will be posted'); }
if (!$cardBinary && file_exists($imagePath)) { $cardBinary = file_get_contents($imagePath); }
@unlink($imagePath);
if (!$cardBinary) { throw new \Exception('Photo card could not be created'); }
$photoRes = Http::withoutVerifying()->timeout(45)
->attach('source', $cardBinary, 'photocard.jpg')
->post("https://graph.facebook.com/v18.0/{$pageId}/photos", [
'caption' => $title . "\n\nবিস্তারিত পড়ুন কমেন্টে 👇",
'access_token' => $pageAccessToken,
]);
if (!$photoRes->successful()) {
Log::error('FB Photo Binary Upload Error (Telegram): ' . $photoRes->body());
$out['fb'] = 'fail: photo upload';
return $out;
}
$resData = $photoRes->json() ?: [];
$targetPostId = $resData['post_id'] ?? (!empty($resData['id']) ? ($pageId . '_' . $resData['id']) : null);
if ($targetPostId) {
usleep(1000000);
$commentRes = Http::withoutVerifying()->timeout(20)->post("https://graph.facebook.com/v18.0/{$targetPostId}/comments", [
'message' => "বিস্তারিত পড়ুন: " . $articleRouteUrl,
'access_token' => $pageAccessToken,
]);
if (!$commentRes->successful()) {
Log::error('FB Comment API Error (Telegram): ' . $commentRes->body());
$out['fb'] = 'photo ok, comment fail';
return $out;
}
}
$out['fb'] = 'ok';
} catch (\Throwable $fbErr) {
Log::error('Facebook Exception Error (Telegram): ' . $fbErr->getMessage());
$out['fb'] = 'fail: ' . $fbErr->getMessage();
}
return $out;
}
private function tgNorm(string $s): string
{
return preg_replace('/[\s\-_,.]+/u', '', mb_strtolower(trim($s)));
}
/** AI er deya nam er sathe site er category mile ki na (hubohu, na hole ekta-i partial match) */
private function tgMatchCategory(string $name, array $cats): int
{
$n = $this->tgNorm($name);
if ($n === '') { return 0; }
$partial = [];
foreach ($cats as $id => $cn) {
$c = $this->tgNorm((string) $cn);
if ($c === '') { continue; }
if ($c === $n) { return (int) $id; }
if (mb_strlen($n) >= 3 && mb_strlen($c) >= 3 && (mb_strpos($c, $n) !== false || mb_strpos($n, $c) !== false)) {
$partial[] = (int) $id;
}
}
return count($partial) === 1 ? $partial[0] : 0;
}
/** Category na thakle notun toiri: ekta thaka category (default) ke template kore copy, shudhu nam + slug bodle */
private function tgCreateCategory(string $name, int $templateId): int
{
try {
$model = new Category();
$cols = Schema::getColumnListing($model->getTable());
$nameCol = null;
foreach (['category_name', 'name', 'title'] as $c) {
if (in_array($c, $cols, true)) { $nameCol = $c; break; }
}
if (!$nameCol) { return 0; }
$dup = Category::where($nameCol, $name)->first();
if ($dup) { return (int) $dup->getKey(); }
$tpl = Category::where($model->getKeyName(), $templateId)->first() ?: Category::query()->first();
$new = $tpl ? $tpl->replicate() : new Category();
$new->$nameCol = $name;
if (in_array('slug', $cols, true)) {
$slug = trim(preg_replace('/[\s\/\\\\?#%&]+/u', '-', $name), '-');
if ($slug === '' || Category::where('slug', $slug)->exists()) {
$slug = ($slug !== '' ? $slug : 'cat') . '-' . Str::random(4);
}
$new->slug = $slug;
}
$new->save();
return (int) $new->getKey();
} catch (\Throwable $e) {
Log::error('AutoNewsKit Telegram: category create failed: ' . $e->getMessage());
return 0;
}
}
/**
* Bangla font: NEWS_CARD_FONT (.env) first, else storage/fonts/HindSiliguri-{weight}.ttf.
* If the file is missing it is downloaded automatically (once) - a missing font used to make the card
* fail and a plain thumbnail get posted to Facebook.
*/
private function ensureFont(string $weight = 'Bold'): string
{
$env = (string) AnEnv::get('NEWS_CARD_FONT', '');
if ($weight === 'Bold' && $env !== '' && is_file($env)) { return $env; }
$dir = storage_path('fonts');
$f = $dir . '/HindSiliguri-' . $weight . '.ttf';
if (is_file($f) && filesize($f) > 10000) { return $f; }
try {
if (!File::isDirectory($dir)) { File::makeDirectory($dir, 0775, true, true); }
$url = ($weight === 'Bold' && AnEnv::get('NEWS_CARD_FONT_URL'))
? (string) AnEnv::get('NEWS_CARD_FONT_URL')
: 'https://github.com/google/fonts/raw/main/ofl/hindsiliguri/HindSiliguri-' . $weight . '.ttf';
$res = Http::withoutVerifying()->timeout(40)->get($url);
if ($res->successful() && strlen($res->body()) > 10000) {
File::put($f, $res->body());
} else {
Log::warning('Card font download failed (' . $weight . '): HTTP ' . $res->status() . ' - upload ' . $f . ' manually');
}
} catch (\Throwable $e) {
Log::warning('Card font download error: ' . $e->getMessage());
}
if (!is_file($f) && $weight !== 'Bold') { return $this->ensureFont('Bold'); }
return $f;
}
private function fitLines(string $text, int $maxW, int $maxH, int $maxSz, int $minSz, string $font, string $eng, float $lhMul = 1.4): array
{
$lines = [$text]; $lh = (int) round($minSz * 1.333 * $lhMul);
for ($sz = $maxSz; $sz >= $minSz; $sz -= 2) {
$lines = $this->wrapText($text, $sz, $font, $maxW, $eng);
$lh = (int) round($sz * 1.333 * $lhMul);
if (count($lines) * $lh <= $maxH) { return [$lines, $sz, $lh]; }
}
$maxLines = max(1, (int) floor($maxH / max(1, $lh)));
$lines = array_slice($lines, 0, $maxLines);
$lines[count($lines) - 1] = rtrim($lines[count($lines) - 1], " ,;:-") . '...';
return [$lines, $minSz, $lh];
}
/**
* News card (1080x1350, Prothom Alo style) - the SAME design as the Facebook reel-video card:
* "category | date" + logo on top, blue headline, "« বিস্তারিত কমেন্টে »", rounded photo, page name at the bottom.
* No ad banner. Returns JPEG binary or null (no font / no Bengali text engine).
*/
private function buildNewsCard(string $imagePath, string $title, $postDate = null, string $category = ''): ?string
{
$card = null; $src = null;
try {
$fb = $this->ensureFont('Bold');
$fr = $this->ensureFont('Regular');
if (!is_file($fr)) { $fr = $fb; }
if (!is_file($fb)) { Log::warning('News card font missing: ' . $fb); return null; }
$eng = $this->detectTextEngine($fb);
$this->lastEngine = $eng;
if ($eng === 'plain') { Log::warning('News card: no Bengali text engine (GD+Raqm or Imagick needed)'); return null; }
$raw = @file_get_contents($imagePath);
$src = $raw ? @imagecreatefromstring($raw) : false;
if (!$src) { return null; }
$brand = $this->getBranding();
$pageName = trim((string) ($brand['name'] ?? ''));
if ($pageName === '') { $pageName = (string) ($brand['domain'] ?? ''); }
$W = 1080; $H = 1350;
$BG = [242, 242, 238];
$NAVY = [10, 24, 140, 1.0];
$card = imagecreatetruecolor($W, $H);
imagealphablending($card, true);
imagefill($card, 0, 0, imagecolorallocate($card, $BG[0], $BG[1], $BG[2]));
imagefilledellipse($card, 420, -90, 1900, 900, imagecolorallocate($card, 250, 250, 248));
// 1) top row: "category | date" on the left, logo (or page name) on the right
$dateStr = $this->banglaDate($postDate);
$cat = trim($category);
$left = $cat !== '' ? $cat . ' | ' . $dateStr : $dateStr;
for ($sz = 22; $sz > 14; $sz--) { if ($this->tWidth($eng, $left, $sz, $fr) <= 560) { break; } }
$this->tDraw($card, $eng, $left, $sz, $fr, 36, 84, [40, 40, 40, 1.0]);
$override = public_path('assets/images/card-logo.png');
$logoBytes = is_file($override) ? @file_get_contents($override) : ($brand['logo_bytes'] ?? null);
$drawn = false;
if ($logoBytes) {
$info = @getimagesizefromstring($logoBytes);
$li = @imagecreatefromstring($logoBytes);
if ($info && $li && $info[0] > 0 && $info[1] > 0) {
$lh = 72; $lw = (int) round($info[0] * $lh / $info[1]);
if ($lw > 300) { $lw = 300; $lh = (int) round($info[1] * $lw / $info[0]); }
$lx = 1044 - $lw; $ly = 74 - (int) ($lh / 2);
// white-text transparent logos vanish on the light card, so give only those a dark plate
if ($this->isLogoLight($li) && ((imagecolorat($li, 0, 0) >> 24) & 127) > 100) {
$this->fillRound($card, $lx - 16, $ly - 10, $lx + $lw + 15, $ly + $lh + 9, 18, [12, 22, 60]);
}
imagealphablending($card, true);
imagecopyresampled($card, $li, $lx, $ly, 0, 0, $lw, $lh, imagesx($li), imagesy($li));
$drawn = true;
}
if ($li) { imagedestroy($li); }
}
if (!$drawn && $pageName !== '') {
for ($sz = 30; $sz > 16; $sz--) { if ($this->tWidth($eng, $pageName, $sz, $fb) <= 400) { break; } }
$pw = $this->tWidth($eng, $pageName, $sz, $fb);
$this->tDraw($card, $eng, $pageName, $sz, $fb, 1044 - $pw, 86, $NAVY);
}
// 2) headline (blue, centered, up to 3 lines)
[$lines, $ss, $lh2] = $this->fitLines($title, 940, 230, 46, 30, $fb, $eng, 1.32);
$block = count($lines) * $lh2;
$y = 150 + (int) max(0, (230 - $block) / 2) + (int) round($ss * 1.333 * 0.95);
foreach ($lines as $ln) { $this->tDrawCentered($card, $eng, $ln, $ss, $fb, 540, $y, $NAVY); $y += $lh2; }
// 3) « বিস্তারিত কমেন্টে »
$this->tDrawCentered($card, $eng, '« বিস্তারিত কমেন্টে »', 24, $fb, 540, 440, [45, 45, 45, 1.0]);
// 4) rounded photo (no banner, so it can be taller)
$photoTop = 490;
$photoH = max(300, min(1190, $photoTop + 700) - $photoTop);
$px = 36; $pw2 = $W - 72;
$this->fillRound($card, $px + 4, $photoTop + 8, $px + $pw2 + 3, $photoTop + $photoH + 7, 38, [222, 222, 217]);
$sw = imagesx($src); $sh = imagesy($src);
$ratio = max($pw2 / $sw, $photoH / $sh);
$cw = (int) round($pw2 / $ratio); $ch = (int) round($photoH / $ratio);
imagecopyresampled($card, $src, $px, $photoTop, (int) (($sw - $cw) / 2), (int) (($sh - $ch) * 0.3), $pw2, $photoH, $cw, $ch);
imagedestroy($src); $src = null;
$this->trimCorners($card, $px, $photoTop, $px + $pw2 - 1, $photoTop + $photoH - 1, 36, $BG);
// 5) bottom: page name
if ($pageName !== '') {
$this->tDrawCentered($card, $eng, $pageName, 22, $fb, 540, 1300, [90, 90, 90, 1.0]);
}
ob_start();
imagejpeg($card, null, 93);
$out = ob_get_clean();
return $out ?: null;
} catch (\Throwable $e) {
Log::error('News card error: ' . $e->getMessage());
return null;
} finally {
if ($card) { @imagedestroy($card); }
if ($src) { @imagedestroy($src); }
}
}
/** Downloads the banner (NEWS_BANNER_URL in .env, default below). Returns a GD image or null. */
private function loadBanner()
{
try {
$bannerUrl = AnEnv::get('NEWS_BANNER_URL', 'https://news1.mtechsolutionbd.com/public/ads/1999tk.jpeg');
$res = Http::withoutVerifying()->timeout(15)->get($bannerUrl);
if (!$res->successful() || strlen($res->body()) < 500) {
Log::warning('Banner download failed: ' . $bannerUrl);
return null;
}
$banner = @imagecreatefromstring($res->body());
return $banner ?: null;
} catch (\Throwable $e) {
Log::error('Banner load error: ' . $e->getMessage());
return null;
}
}
/** Draws the banner inside the bottom of the news image (same image size). Returns JPEG bytes; the original on any problem. */
private function addBannerOverlay(string $imageBytes, $banner): string
{
$img = null;
try {
$img = @imagecreatefromstring($imageBytes);
if (!$img) { return $imageBytes; }
$this->drawBannerOnBottom($img, $banner, 0, 0, imagesx($img), imagesy($img));
ob_start();
imagejpeg($img, null, 92);
$out = ob_get_clean();
return $out ?: $imageBytes;
} catch (\Throwable $e) {
Log::error('Banner overlay error: ' . $e->getMessage());
return $imageBytes;
} finally {
if ($img) { @imagedestroy($img); }
}
}
/**
* Draws the banner as a full-width strip flush with the bottom of the rectangle ($x,$y,$w,$h)
* of $canvas, so there is no gap on either side. The banner keeps its aspect ratio. Strip height
* is limited to NEWS_BANNER_MAX_HEIGHT of the image height (default 0.18 = 18%). When the banner
* is too tall for the full width within that limit, it is scaled down, centered, and the two
* sides are filled with the banner's own edge colors so the strip still looks continuous.
*/
private function drawBannerOnBottom($canvas, $banner, int $x, int $y, int $w, int $h): void
{
$bw = imagesx($banner); $bh = imagesy($banner);
if ($bw < 1 || $bh < 1) { return; }
$pct = (float)AnEnv::get('NEWS_BANNER_MAX_HEIGHT', 0.18);
$pct = max(0.08, min(0.35, $pct));
$maxH = max(1, (int)round($h * $pct));
$nw = $w;
$nh = max(1, (int)round($bh * ($w / $bw)));
if ($nh > $maxH) {
$nh = $maxH;
$nw = max(1, (int)round($bw * ($nh / $bh)));
}
$dx = $x + (int)(($w - $nw) / 2);
$dy = $y + $h - $nh;
imagealphablending($canvas, true);
if ($nw < $w) {
// Fill both sides with the banner's average edge color (leftmost / rightmost columns), stretched
$take = min(6, $bw);
$sides = [
[0, $x, $dx - $x],
[$bw - $take, $dx + $nw, ($x + $w) - ($dx + $nw)],
];
foreach ($sides as [$srcX, $padX, $padW]) {
if ($padW < 1) { continue; }
$strip = imagecreatetruecolor(1, $nh);
imagecopyresampled($strip, $banner, 0, 0, $srcX, 0, 1, $nh, $take, $bh);
imagecopyresampled($canvas, $strip, $padX, $dy, 0, 0, $padW, $nh, 1, $nh);
imagedestroy($strip);
}
}
imagecopyresampled($canvas, $banner, $dx, $dy, 0, 0, $nw, $nh, $bw, $bh);
}
/**
* Branded news photo card (1440x1440): red/blue gradient, logo + Bengali date on top,
* rounded white-framed photo, headline, "details in comments" pill and site footer.
* Site name / logo / domain come from the database. Needs a Bengali TTF font
* (default storage/fonts/HindSiliguri-Bold.ttf). Bengali text is drawn with GD+Raqm
* or, if GD cannot shape Bengali, through Imagick. Returns JPEG binary or null.
*/
private function buildPhotoCard(string $imagePath, string $title, $postDate = null, $banner = null): ?string
{
try {
$font = $this->ensureFont('Bold');
if (!is_file($font)) {
Log::warning('Photo card font missing: ' . $font);
return null;
}
$raw = @file_get_contents($imagePath);
$src = $raw ? @imagecreatefromstring($raw) : false;
if (!$src) { return null; }
$eng = $this->detectTextEngine($font); // gd | imagick | plain
$this->lastEngine = $eng;
$canBangla = $eng !== 'plain';
Log::info('Photo card text engine: ' . $eng);
$brand = $this->getBranding();
$W = 1440; $H = 1440;
$m = 120;
$border = 12;
$photoY = 215;
$photoH = $canBangla ? 665 : 985;
$card = imagecreatetruecolor($W, $H);
imagealphablending($card, true);
// 1) Background gradient (red -> blue), built small and scaled up smoothly
$gw = 96; $gh = 96;
$g = imagecreatetruecolor($gw, $gh);
$red = [206, 16, 42]; $blue = [14, 38, 118];
for ($y = 0; $y < $gh; $y++) {
for ($x = 0; $x < $gw; $x++) {
$u = $x / ($gw - 1);
$v = $y / ($gh - 1);
$w = $u * 0.75 + (1 - abs($v - 0.45) * 2) * 0.35 - 0.12;
$w = max(0, min(1, $w));
$w = $w * $w * (3 - 2 * $w);
$r = (int)round($red[0] + ($blue[0] - $red[0]) * $w);
$gr = (int)round($red[1] + ($blue[1] - $red[1]) * $w);
$b = (int)round($red[2] + ($blue[2] - $red[2]) * $w);
imagesetpixel($g, $x, $y, imagecolorallocate($g, $r, $gr, $b));
}
}
imagecopyresampled($card, $g, 0, 0, 0, 0, $W, $H, $gw, $gh);
imagedestroy($g);
$WHITE = [255, 255, 255, 1.0];
$NAVY = [12, 22, 60, 1.0];
$SHADOW = [0, 0, 0, 0.35];
// 2) Header: logo (or site name) left, date right
$logoImg = null;
$override = public_path('assets/images/card-logo.png');
$logoBytes = is_file($override) ? @file_get_contents($override) : ($brand['logo_bytes'] ?? null);
if ($logoBytes) { $logoImg = @imagecreatefromstring($logoBytes); }
$headerMidY = 100;
if ($logoImg) {
$lw = imagesx($logoImg); $lh = imagesy($logoImg);
$th = 112; $tw = (int)round($lw * ($th / $lh));
if ($tw > 620) { $tw = 620; $th = (int)round($lh * ($tw / $lw)); }
if ($this->isLogoLight($logoImg)) {
imagecopyresampled($card, $logoImg, 70, 48, 0, 0, $tw, $th, $lw, $lh);
$headerMidY = 48 + (int)($th / 2);
} else {
$this->fillRound($card, 60, 36, 60 + $tw + 40 - 1, 36 + $th + 32 - 1, 22, [255, 255, 255]);
imagecopyresampled($card, $logoImg, 80, 52, 0, 0, $tw, $th, $lw, $lh);
$headerMidY = 36 + (int)(($th + 32) / 2);
}
imagedestroy($logoImg);
} else {
$name = $brand['name'] ?? '';
if ($name === '' || (!$canBangla && !preg_match('/^[\x20-\x7E]+$/', $name))) {
$name = $brand['domain'] ?? 'News';
}
$nw = $this->tWidth($eng, $name, 36, $font);
$this->fillRound($card, 60, 52, 60 + $nw + 60 - 1, 52 + 96 - 1, 22, [255, 255, 255]);
$this->tDraw($card, $eng, $name, 36, $font, 90, 52 + 66, $NAVY);
$headerMidY = 100;
}
$dateStr = $canBangla
? $this->banglaDate($postDate)
: ($postDate instanceof \DateTimeInterface ? $postDate->format('d M Y') : date('d M Y'));
$dw = $this->tWidth($eng, $dateStr, 32, $font);
$dx = $W - 70 - $dw;
$dy = $headerMidY + 14;
$this->tDraw($card, $eng, $dateStr, 32, $font, $dx + 2, $dy + 3, $SHADOW);
$this->tDraw($card, $eng, $dateStr, 32, $font, $dx, $dy, $WHITE);
// 3) White rounded frame + cover-cropped photo with rounded corners
$fx1 = $m - $border; $fy1 = $photoY - $border;
$fx2 = $W - $m + $border - 1; $fy2 = $photoY + $photoH + $border - 1;
$this->fillRound($card, $fx1, $fy1, $fx2, $fy2, 40, [255, 255, 255]);
$pw = $W - 2 * $m;
$sw = imagesx($src); $sh = imagesy($src);
$ratio = max($pw / $sw, $photoH / $sh);
$cw = (int)round($pw / $ratio);
$ch = (int)round($photoH / $ratio);
$sx = (int)(($sw - $cw) / 2);
$sy = (int)(($sh - $ch) * 0.3);
imagecopyresampled($card, $src, $m, $photoY, $sx, $sy, $pw, $photoH, $cw, $ch);
imagedestroy($src);
if ($banner) {
// Banner sits inside the bottom of the photo; drawn before the corners are rounded
$this->drawBannerOnBottom($card, $banner, $m, $photoY, $pw, $photoH);
}
$this->trimCorners($card, $m, $photoY, $m + $pw - 1, $photoY + $photoH - 1, 30, [255, 255, 255]);
// 4) Headline (centered, auto-fit up to 3 lines)
$afterPhoto = $fy2 + 1;
if ($canBangla) {
$regionTop = $afterPhoto + 26;
$regionH = 258;
$maxW = $W - 220;
$lines = [];
$size = 54;
for ($size = 54; $size >= 34; $size -= 2) {
$lines = $this->wrapText($title, $size, $font, $maxW, $eng);
$lineH = (int)round($size * 1.333 * 1.36);
if (count($lines) <= 3 && count($lines) * $lineH <= $regionH) { break; }
}
$lineH = (int)round($size * 1.333 * 1.36);
if (count($lines) > 3) {
$lines = array_slice($lines, 0, 3);
$lines[2] = rtrim($lines[2], " ,।-:;") . '…';
}
$block = count($lines) * $lineH;
$y = $regionTop + (int)max(0, ($regionH - $block) / 2) + (int)round($size * 1.333 * 1.0);
foreach ($lines as $line) {
$this->tDrawCentered($card, $eng, $line, $size, $font, $W / 2 + 2, $y + 3, $SHADOW);
$this->tDrawCentered($card, $eng, $line, $size, $font, $W / 2, $y, $WHITE);
$y += $lineH;
}
}
// 5) "Details in comments" pill
$ctaText = $canBangla ? 'বিস্তারিত কমেন্টে' : 'DETAILS IN COMMENTS';
$ctaW = $this->tWidth($eng, $ctaText, 26, $font) + 110;
$ctaH = 72;
$ctaY = $canBangla ? 1195 : 1235;
$ctaX = (int)(($W - $ctaW) / 2);
$this->fillRound($card, $ctaX, $ctaY, $ctaX + $ctaW - 1, $ctaY + $ctaH - 1, 36, [255, 255, 255]);
$this->tDrawCentered($card, $eng, $ctaText, 26, $font, $W / 2, $ctaY + 50, $NAVY);
// 6) Footer pill: Facebook-style icon + website (from database)
$site = strtoupper(preg_replace('/^www\./i', '', $brand['domain'] ?? ''));
if ($site === '') { $site = strtoupper($brand['name'] ?? ''); }
if ($site !== '') {
$stw = $this->tWidth($eng, $site, 30, $font);
$icon = 60; $gap = 20; $padX = 36;
$fW = $padX + $icon + $gap + $stw + $padX;
$fH = 96;
$fX = (int)(($W - $fW) / 2);
$fY = 1295;
$this->fillRound($card, $fX, $fY, $fX + $fW - 1, $fY + $fH - 1, 48, [255, 255, 255]);
$ix = $fX + $padX; $iy = $fY + (int)(($fH - $icon) / 2);
$this->fillRound($card, $ix, $iy, $ix + $icon - 1, $iy + $icon - 1, 14, [24, 119, 242]);
$this->tDrawCentered($card, $eng, 'f', 36, $font, $ix + $icon / 2 + 4, $iy + $icon - 8, $WHITE);
$this->tDraw($card, $eng, $site, 30, $font, $ix + $icon + $gap, $fY + 64, $NAVY);
}
ob_start();
imagejpeg($card, null, 95);
$binary = ob_get_clean();
imagedestroy($card);
return $binary ?: null;
} catch (\Throwable $e) {
Log::error('Photo card build error: ' . $e->getMessage());
return null;
}
}
/** `php artisan news:auto-generate --card-test` : builds public/card-test.jpg with a sample Bengali headline. */
private function runCardTest()
{
$src = null;
try {
$p = Post::whereNotNull('image_big')->orderByDesc('id')->first();
if ($p) {
$cand = public_path('assets/images/post/' . $p->image_big);
if (is_file($cand)) { $src = $cand; }
}
} catch (\Throwable $e) {}
if (!$src) {
$im = imagecreatetruecolor(1200, 800);
imagefilledrectangle($im, 0, 0, 1200, 800, imagecolorallocate($im, 90, 110, 140));
$src = storage_path('app/card-test-src.jpg');
imagejpeg($im, $src, 90);
imagedestroy($im);
}
$bin = $this->buildNewsCard($src, 'বাড়ি ঘরের পরিবেশ রক্ষার্থে কি কি করা উচিত.?', now(), 'বাণিজ্য');
if (!$bin) { $bin = $this->buildPhotoCard($src, 'বাড়ি ঘরের পরিবেশ রক্ষার্থে কি কি করা উচিত.?', now(), null); }
if (!$bin) {
$this->error('Card build failed - see storage/logs/laravel.log');
return;
}
$out = public_path('card-test.jpg');
file_put_contents($out, $bin);
$this->info('Text engine used: ' . $this->lastEngine . ' (gd / imagick = Bengali OK, plain = Bengali NOT supported)');
$this->info('Saved: ' . $out . ' -> open /card-test.jpg in the browser');
}
/**
* Pick a text engine that really shapes Bengali. Tested by measuring "র্ক":
* with shaping the reph sits above ক, so the width is much smaller than র + ক.
* Force one with NEWS_CARD_ENGINE=gd|imagick in .env (default: auto).
*/
private function detectTextEngine(string $font): string
{
if ($this->engineCache !== null) { return $this->engineCache; }
$pref = strtolower((string)AnEnv::get('NEWS_CARD_ENGINE', 'auto'));
$candidates = $pref === 'auto' ? ['gd', 'imagick'] : [$pref];
foreach ($candidates as $e) {
if ($e === 'imagick' && !(extension_loaded('imagick') && class_exists('Imagick') && class_exists('ImagickDraw'))) { continue; }
if ($e === 'gd' && !function_exists('imagettfbbox')) { continue; }
try {
$a = $this->tWidth($e, 'র্ক', 40, $font);
$b = $this->tWidth($e, 'র', 40, $font);
$c = $this->tWidth($e, 'ক', 40, $font);
if ($a > 0 && $a < 0.8 * ($b + $c)) {
return $this->engineCache = $e;
}
} catch (\Throwable $t) {
Log::warning('Text engine test failed (' . $e . '): ' . $t->getMessage());
}
}
return $this->engineCache = 'plain';
}
private function imBase()
{
if ($this->imBase === null) {
$this->imBase = new \Imagick();
$this->imBase->newImage(1, 1, new \ImagickPixel('white'));
}
return $this->imBase;
}
private function imDraw(string $font, float $px, array $rgba = [0, 0, 0, 1.0]): \ImagickDraw
{
$d = new \ImagickDraw();
$d->setFont($font);
$d->setFontSize($px);
$d->setTextEncoding('UTF-8');
$d->setFillColor(new \ImagickPixel(sprintf('rgba(%d,%d,%d,%.3f)', $rgba[0], $rgba[1], $rgba[2], $rgba[3])));
return $d;
}
/** Text width in pixels for the given engine. $size is in "GD points" (1pt = 1.333px). */
private function tWidth(string $eng, string $text, int $size, string $font): int
{
if ($eng === 'imagick') {
$m = $this->imBase()->queryFontMetrics($this->imDraw($font, $size * 1.333), $text, false);
return (int)ceil($m['textWidth']);
}
$b = imagettfbbox($size, 0, $font, $text);
return (int)abs($b[2] - $b[0]);
}
/** Draw text with its origin at ($x, baseline $y). $rgba = [r,g,b,alpha 0..1]. */
private function tDraw($img, string $eng, string $text, int $size, string $font, $x, $y, array $rgba): void
{
$x = (int)round($x); $y = (int)round($y);
if ($eng === 'imagick') {
$px = $size * 1.333;
$draw = $this->imDraw($font, $px, $rgba);
$m = $this->imBase()->queryFontMetrics($draw, $text, false);
$padX = (int)ceil($px * 0.3);
$padY = (int)ceil($px * 0.6);
$asc = (int)ceil($m['ascender']);
$w = (int)ceil($m['textWidth']) + 2 * $padX;
$h = (int)ceil(max($m['textHeight'], $m['ascender'] + abs($m['descender']))) + 2 * $padY;
$canvas = new \Imagick();
$canvas->newImage($w, $h, new \ImagickPixel('transparent'));
$canvas->setImageFormat('png');
$base = $padY + $asc;
$canvas->annotateImage($draw, $padX, $base, 0, $text);
$blob = $canvas->getImageBlob();
$canvas->clear();
$glyph = @imagecreatefromstring($blob);
if ($glyph) {
imagealphablending($img, true);
imagecopy($img, $glyph, $x - $padX, $y - $base, 0, 0, $w, $h);
imagedestroy($glyph);
}
return;
}
$alpha = (int)round((1 - $rgba[3]) * 127);
$col = imagecolorallocatealpha($img, $rgba[0], $rgba[1], $rgba[2], max(0, min(127, $alpha)));
imagettftext($img, $size, 0, $x, $y, $col, $font, $text);
}
private function tDrawCentered($img, string $eng, string $text, int $size, string $font, $cx, $y, array $rgba): void
{
$w = $this->tWidth($eng, $text, $size, $font);
$this->tDraw($img, $eng, $text, $size, $font, $cx - $w / 2, $y, $rgba);
}
/** Word-wrap text to a pixel width using the real font metrics. */
private function wrapText(string $text, int $size, string $font, int $maxWidth, string $eng): array
{
$words = preg_split('/\s+/u', trim($text), -1, PREG_SPLIT_NO_EMPTY);
$lines = [];
$current = '';
foreach ($words as $word) {
$test = $current === '' ? $word : $current . ' ' . $word;
if ($this->tWidth($eng, $test, $size, $font) > $maxWidth && $current !== '') {
$lines[] = $current;
$current = $word;
} else {
$current = $test;
}
}
if ($current !== '') { $lines[] = $current; }
return $lines;
}
/** Read portal name, logo and domain from the database (tolerant to column naming). */
private function getBranding(): array
{
$out = ['name' => null, 'domain' => null, 'logo_bytes' => null];
$first = function (?object $row, array $cols) {
if (!$row) { return null; }
foreach ($cols as $c) {
if (isset($row->$c) && is_string($row->$c) && trim($row->$c) !== '') { return trim($row->$c); }
}
return null;
};
$gs = null;
foreach (['generalsettings', 'general_settings', 'settings'] as $t) {
try {
if (Schema::hasTable($t)) {
$gs = DB::table($t)->first();
if ($gs) { break; }
}
} catch (\Throwable $e) {}
}
$logoRow = null;
try {
if (Schema::hasTable('logos')) {
$logoRow = DB::table('logos')->where('language_id', 1)->first() ?: DB::table('logos')->first();
}
} catch (\Throwable $e) {}
$out['name'] = $first($gs, ['site_name', 'website_title', 'site_title', 'website_name', 'title', 'name', 'app_name']);
if (!$out['name']) { $out['name'] = config('app.name'); }
$domain = $first($gs, ['website', 'site_url', 'url', 'domain']);
if (!$domain) { $domain = config('app.url'); }
$domain = preg_replace('#^https?://#i', '', trim((string)$domain));
$out['domain'] = rtrim(explode('/', $domain)[0], '/');
$logoFile = $first($logoRow, ['logo', 'image', 'file', 'photo']) ?? $first($gs, ['logo', 'header_logo', 'site_logo']);
if ($logoFile) { $out['logo_bytes'] = $this->loadLogoBytes($logoFile); }
return $out;
}
private function loadLogoBytes(string $file): ?string
{
try {
if (preg_match('#^https?://#i', $file)) {
$res = Http::withoutVerifying()->timeout(10)->get($file);
return $res->successful() ? $res->body() : null;
}
$file = ltrim($file, '/');
$bases = [public_path(), dirname(base_path())];
$subs = ['', 'assets/images/', 'assets/images/logo/', 'assets/images/logos/', 'assets/img/', 'assets/', 'uploads/', 'storage/', 'images/'];
foreach ($bases as $base) {
foreach ($subs as $sub) {
$path = rtrim($base, '/') . '/' . $sub . $file;
if (is_file($path)) { return @file_get_contents($path) ?: null; }
}
}
} catch (\Throwable $e) {}
return null;
}
/** True if the logo is mostly light/white (then it is drawn directly on the gradient). */
private function isLogoLight($im): bool
{
$w = imagesx($im); $h = imagesy($im);
$sum = 0; $n = 0;
for ($i = 0; $i < 24; $i++) {
for ($j = 0; $j < 24; $j++) {
$c = imagecolorat($im, (int)($i * ($w - 1) / 23), (int)($j * ($h - 1) / 23));
if ((($c >> 24) & 127) > 100) { continue; }
$sum += 0.299 * (($c >> 16) & 255) + 0.587 * (($c >> 8) & 255) + 0.114 * ($c & 255);
$n++;
}
}
return $n > 0 && ($sum / $n) > 190;
}
private function banglaDate($dt = null): string
{
$months = ['জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'];
$digits = ['0' => '০', '1' => '১', '2' => '২', '3' => '৩', '4' => '৪', '5' => '৫', '6' => '৬', '7' => '৭', '8' => '৮', '9' => '৯'];
$d = $dt instanceof \DateTimeInterface ? $dt : new \DateTime();
return strtr($d->format('j'), $digits) . ' ' . $months[(int)$d->format('n') - 1] . ' ' . strtr($d->format('Y'), $digits);
}
/** Anti-aliased filled rounded rectangle (x2/y2 inclusive). */
private function fillRound($img, int $x1, int $y1, int $x2, int $y2, int $r, array $rgb): void
{
$col = imagecolorallocate($img, $rgb[0], $rgb[1], $rgb[2]);
imagefilledrectangle($img, $x1 + $r, $y1, $x2 - $r, $y2, $col);
imagefilledrectangle($img, $x1, $y1 + $r, $x1 + $r - 1, $y2 - $r, $col);
imagefilledrectangle($img, $x2 - $r + 1, $y1 + $r, $x2, $y2 - $r, $col);
$this->paintCorners($img, $x1, $y1, $x2, $y2, $r, $rgb, false);
}
/** Anti-aliased rounding of an already drawn rectangle: pixels outside the arc become $rgb. */
private function trimCorners($img, int $x1, int $y1, int $x2, int $y2, int $r, array $rgb): void
{
$this->paintCorners($img, $x1, $y1, $x2, $y2, $r, $rgb, true);
}
private function paintCorners($img, int $x1, int $y1, int $x2, int $y2, int $r, array $rgb, bool $outside): void
{
$corners = [
[$x1, $y1, $x1 + $r, $y1 + $r],
[$x2 - $r + 1, $y1, $x2 + 1 - $r, $y1 + $r],
[$x1, $y2 - $r + 1, $x1 + $r, $y2 + 1 - $r],
[$x2 - $r + 1, $y2 - $r + 1, $x2 + 1 - $r, $y2 + 1 - $r],
];
foreach ($corners as [$ox, $oy, $cx, $cy]) {
for ($i = 0; $i < $r; $i++) {
for ($j = 0; $j < $r; $j++) {
$X = $ox + $i; $Y = $oy + $j;
$dist = sqrt(pow($X + 0.5 - $cx, 2) + pow($Y + 0.5 - $cy, 2));
$cov = max(0.0, min(1.0, $r - $dist + 0.5));
$a = $outside ? (1.0 - $cov) : $cov;
if ($a <= 0) { continue; }
$cur = imagecolorat($img, $X, $Y);
$nr = (int)round((($cur >> 16) & 255) * (1 - $a) + $rgb[0] * $a);
$ng = (int)round((($cur >> 8) & 255) * (1 - $a) + $rgb[1] * $a);
$nb = (int)round(($cur & 255) * (1 - $a) + $rgb[2] * $a);
imagesetpixel($img, $X, $Y, ($nr << 16) | ($ng << 8) | $nb);
}
}
}
}
}
/* ===================== Groq service (apnar ager code) ===================== */
class GeminiService
{
protected string $apiKey;
protected string $endpoint = "https://api.groq.com/openai/v1/chat/completions";
// Groq-এর বর্তমান মডেল (llama3-70b-8192 ও llama-3.3-70b-versatile বন্ধ হয়ে গেছে)
// নতুন মডেল দরকার হলে: https://console.groq.com/docs/deprecations
protected array $supportedModels = [
'openai/gpt-oss-120b',
'openai/gpt-oss-20b',
];
public function __construct()
{
$this->apiKey = trim(AnGuard::cfg('groq_key', 'GROQ_API_KEY') ?: AnGuard::cfg('', 'GEMINI_API_KEY'));
}
public function rewriteNews(string $rawTitle, string $rawDescription, array $availableCategories = []): ?array
{
// License gate AI step e-o (entry/command bypass korleo ekhane atkabe)
[$allowed, $reason] = AnGuard::check();
if (!$allowed) {
return null;
}
if (empty($this->apiKey)) {
echo "এরর: এই সাইটের জন্য Groq API Key সেট করা নেই (License Manager এ দিন)!
";
return null;
}
$categoryPromptText = "";
if (!empty($availableCategories)) {
$catList = [];
foreach ($availableCategories as $id => $name) {
$catList[] = "ID: {$id} => {$name}";
}
$categoryPromptText = "উপলব্ধ ক্যাটাগরিসমূহ:\n" . implode("\n", $catList) . "\n\nনির্দেশনা: সংবাদের সাথে সবচেয়ে মানানসই ক্যাটাগরি আইডিটি 'category_id' ফিল্ডে পূর্ণসংখ্যা হিসেবে দাও।";
}
$prompt = "তুমি বাংলাদেশের একটি শীর্ষস্থানীয় জাতীয় দৈনিক পত্রিকার প্রধান বার্তা সম্পাদক।
নিচের তথ্যের ওপর ভিত্তি করে সম্পূর্ণ ইউনিক, বস্তুনিষ্ঠ এবং প্রাতিষ্ঠানিক প্রমিত বাংলায় ৪০০-৫০০ শব্দের পূর্ণাঙ্গ জাতীয় সংবাদ প্রতিবেদন তৈরি করো।
{$categoryPromptText}
সম্পাদকীয় নির্দেশনা:
১. শব্দ সংখ্যা ও বিস্তার: প্রতিবেদনটি অবশ্যই অন্তত ৪০০ থেকে ৫০০ শব্দের বিস্তারিত প্রতিবেদন হতে হবে।
২. অনুচ্ছেদ বিন্যাস: মোট ৪টি স্পষ্ট অনুচ্ছেদ তৈরি করো এবং প্রতিটি অনুচ্ছেদ দিয়ে শুরু এবং
দিয়ে শেষ করো:
- ১ম অনুচ্ছেদ: সংবাদের মূল ঘটনা ও তাৎক্ষণিক গুরুত্ব।
- ২য় অনুচ্ছেদ: ঘটনার নেপথ্যের পটভূমি।
- ৩য় অনুচ্ছেদ: সংশ্লিষ্টদের বক্তব্য, প্রতিক্রিয়া ও জনজীবনে প্রভাব।
- ৪র্থ অনুচ্ছেদ: কর্তৃপক্ষের বর্তমান পদক্ষেপ ও ভবিষ্যৎ প্রেক্ষাপট।
৩. কোনো প্রকার ইংরেজি শব্দ বা বাড়তি মন্তব্য করবে না।
৪. আউটপুট ফরম্যাট: কোনো অতিরিক্ত ভূমিকা বা ব্যাখ্যা ছাড়া শুধুমাত্র এই JSON অবজেক্ট দাও:
{
\"category_id\": 55,
\"title\": \"আকর্ষণীয় নতুন বাংলা শিরোনাম\",
\"content\": \"প্রথম অনুচ্ছেদ...
দ্বিতীয় অনুচ্ছেদ...
তৃতীয় অনুচ্ছেদ...
চতুর্থ অনুচ্ছেদ...
\"
}
শিরোনাম: {$rawTitle}
তথ্য: {$rawDescription}";
$lastError = '';
foreach ($this->supportedModels as $model) {
// প্রথমে JSON mode দিয়ে, ব্যর্থ হলে (400) JSON mode ছাড়া আবার চেষ্টা
foreach ([true, false] as $useJsonMode) {
try {
$payload = [
'model' => $model,
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'temperature' => 0.3,
'max_completion_tokens' => 4096,
];
if (str_starts_with($model, 'openai/gpt-oss')) {
$payload['reasoning_effort'] = 'low'; // কম token খরচ, দৈনিক লিমিট দেরিতে শেষ হবে
}
if ($useJsonMode) {
$payload['response_format'] = ['type' => 'json_object'];
}
$response = Http::withoutVerifying()
->timeout(60)
->withHeaders([
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json',
])
->post($this->endpoint, $payload);
if (!$response->successful()) {
$lastError .= "Model: {$model} | JSON mode: " . ($useJsonMode ? 'on' : 'off') . " | Status: " . $response->status() . " | Response: " . $response->body() . "\n";
// 400 হলে JSON mode ছাড়া আবার চেষ্টা; 429/404 হলে পরের মডেলে যাও
if ($response->status() === 400 && $useJsonMode) {
continue;
}
break;
}
$data = $response->json();
$content = $data['choices'][0]['message']['content'] ?? null;
if ($content) {
$clean = trim(preg_replace('/^```json|```$/m', '', $content));
$decoded = json_decode($clean, true);
if (!$decoded) {
$start = strpos($clean, '{');
$end = strrpos($clean, '}');
if ($start !== false && $end !== false && $end > $start) {
$decoded = json_decode(substr($clean, $start, $end - $start + 1), true);
}
}
if ($decoded && !empty($decoded['title']) && !empty($decoded['content'])) {
return $decoded;
}
$lastError .= "Model: {$model} | JSON invalid/empty: " . mb_substr($content, 0, 200) . "\n";
} else {
$lastError .= "Model: {$model} | Empty response\n";
}
break;
} catch (\Throwable $e) {
$lastError .= "Model: {$model} | Exception: " . $e->getMessage() . "\n";
break;
}
}
}
echo "";
echo "Groq API Error Details: " . nl2br(htmlspecialchars($lastError));
echo "
";
return null;
}
}
/* ===================== Telegram reporter group -> sorasori post (notun add-on) ===================== */
/**
* License Manager theke "Telegram" chalu thakle-i kaj kore. Chalu na thakle kichui kore na (purono flow ager moto).
* Reporter group e ekta message: chhobi + caption (prothom line = shironam, baki = bistarito) -> AI chhara sorasori post.
*/
final class AnTg
{
private static function api(string $token, string $method, array $params = [], int $timeout = 20): array
{
$url = "https://api.telegram.org/bot{$token}/{$method}";
try {
$r = Http::asForm()->timeout($timeout)->post($url, $params);
} catch (\Throwable $e) {
try {
$r = Http::withoutVerifying()->asForm()->timeout($timeout)->post($url, $params);
} catch (\Throwable $e2) {
return ['ok' => false, 'description' => 'connect: ' . str_replace($token, '***', $e2->getMessage())];
}
}
$j = $r->json();
return is_array($j) ? $j : ['ok' => false, 'description' => 'HTTP ' . $r->status()];
}
/** AI shudhu category bachbe (lekha bodlay na). Kono kaj na korle '' dey => default category */
public static function pickCategory(string $title, string $body, array $existing): string
{
$key = trim(AnGuard::cfg('groq_key', 'GROQ_API_KEY'));
if ($key === '') { return ''; }
$existing = array_slice(array_values(array_unique(array_filter(array_map('trim', $existing)))), 0, 150);
$list = $existing ? implode(', ', $existing) : '(এখনো কোনো ক্যাটাগরি নেই)';
$prompt = "তুমি একটি বাংলা সংবাদ পোর্টালের সম্পাদক। নিচের খবরটি কোন বিভাগের (ক্যাটাগরির) অন্তর্গত তা ঠিক করো। খবরের লেখা বদলাবে না, শুধু ক্যাটাগরির নাম বলবে।\n\n"
. "সাইটে এখন যে ক্যাটাগরিগুলো আছে: {$list}\n\n"
. "নিয়ম:\n১. তালিকার কোনোটি মানানসই হলে হুবহু সেই নামটিই দাও (বানান বা শব্দ বদলাবে না)।\n"
. "২. কোনোটিই মানানসই না হলে বাংলায় একটি সংক্ষিপ্ত, প্রচলিত সংবাদ-বিভাগের নাম দাও (যেমন: রাজনীতি, অর্থনীতি, খেলা, বিনোদন, আন্তর্জাতিক, প্রযুক্তি, শিক্ষা, স্বাস্থ্য, ধর্ম, অপরাধ, আইন-আদালত, কৃষি, লাইফস্টাইল, মতামত)।\n"
. "৩. কোনো ব্যাখ্যা ছাড়া শুধু এই JSON দাও: {\"category\": \"নাম\"}\n\n"
. "শিরোনাম: {$title}\nবিবরণ: " . mb_substr($body, 0, 700);
foreach (['openai/gpt-oss-20b', 'openai/gpt-oss-120b'] as $model) {
foreach ([true, false] as $json) {
try {
$payload = [
'model' => $model,
'messages' => [['role' => 'user', 'content' => $prompt]],
'temperature' => 0,
'max_completion_tokens' => 1024,
];
if (str_starts_with($model, 'openai/gpt-oss')) { $payload['reasoning_effort'] = 'low'; }
if ($json) { $payload['response_format'] = ['type' => 'json_object']; }
$res = Http::withoutVerifying()->timeout(30)
->withHeaders(['Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json'])
->post('https://api.groq.com/openai/v1/chat/completions', $payload);
if (!$res->successful()) {
if ($res->status() === 400 && $json) { continue; }
break;
}
$name = self::cleanCategory((string) ($res->json('choices.0.message.content') ?? ''));
if ($name !== '') { return $name; }
break;
} catch (\Throwable $e) {
break;
}
}
}
return '';
}
private static function cleanCategory(string $content): string
{
$clean = trim(preg_replace('/^```json|```$/m', '', $content));
$d = json_decode($clean, true);
if (!is_array($d)) {
$s = strpos($clean, '{');
$e = strrpos($clean, '}');
if ($s !== false && $e !== false && $e > $s) { $d = json_decode(substr($clean, $s, $e - $s + 1), true); }
}
$n = is_array($d) ? trim((string) ($d['category'] ?? '')) : '';
$n = preg_replace('/^[\s"\x27«»“”]+|[\s"\x27«»“”]+$/u', '', $n);
if ($n === '' || mb_strlen($n) < 2 || mb_strlen($n) > 40) { return ''; }
if (preg_match('/^[\d\s]+$/u', $n) || preg_match('/[<>{}\[\]\/\\\\=@#]|https?:/iu', $n)) { return ''; }
return $n;
}
/** Telegram ei URL e khobor pathabe. Shudhu license-e registered domain er URL (Host header spoof rukhte) */
private static function hookUrl(): string
{
$st = AnState::load();
if (PHP_SAPI !== 'cli') {
$host = strtolower(preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? '')));
if ($host !== '' && preg_replace('/^www\./', '', $host) === AnGuard::domain()) {
$url = 'https://' . $host . ($_SERVER['SCRIPT_NAME'] ?? '/AutoNewsKit.php') . '?tg=1';
if (($st['tg_url'] ?? '') !== $url) {
$st['tg_url'] = $url;
AnState::save($st);
}
return $url;
}
}
return (string) ($st['tg_url'] ?? '');
}
/** @return array{0:bool,1:string} */
public static function ensureWebhook(bool $force = false): array
{
try {
if (!AnGuard::check()[0]) { return [false, 'license']; }
if (AnGuard::cfg('tg_on') !== '1') { return [false, 'off']; }
$token = AnGuard::cfg('tg_token');
$secret = AnGuard::cfg('tg_secret');
if ($token === '' || $secret === '') { return [false, 'Bot token / secret License Manager e deya nei']; }
$url = self::hookUrl();
if ($url === '') { return [false, 'Site er URL pawa jayni - ekbar browser e AutoNewsKit.php?status kholun']; }
$sig = hash('sha256', $url . '|' . $token . '|' . $secret);
$st = AnState::load();
if (!$force && ($st['tg_sig'] ?? '') === $sig && time() - (int) ($st['tg_sig_ts'] ?? 0) < 43200) {
return [true, 'webhook set'];
}
$res = self::api($token, 'setWebhook', [
'url' => $url,
'secret_token' => $secret,
'allowed_updates' => json_encode(['message']),
'drop_pending_updates' => empty($st['tg_sig']) ? 'true' : 'false',
'max_connections' => 5,
]);
if (!empty($res['ok'])) {
$st = AnState::load();
$st['tg_sig'] = $sig;
$st['tg_sig_ts'] = time();
AnState::save($st);
return [true, 'webhook set'];
}
return [false, str_replace($token, '***', (string) ($res['description'] ?? 'setWebhook failed'))];
} catch (\Throwable $e) {
return [false, 'error'];
}
}
/** ?status page e dekhanor jonno */
public static function statusHtml(): string
{
if (!AnGuard::check()[0] || AnGuard::cfg('tg_on') !== '1') {
return 'Telegram: bondho (License Manager theke chalu korle cholbe)
';
}
[$ok, $msg] = self::ensureWebhook(true);
$html = 'Telegram: ' . ($ok ? '✔ ' : '✖ ') . htmlspecialchars($msg) . ' ';
$token = AnGuard::cfg('tg_token');
if ($ok && $token !== '') {
$info = self::api($token, 'getWebhookInfo', [], 15);
$r = $info['result'] ?? [];
$html .= 'pending: ' . (int) ($r['pending_update_count'] ?? 0);
if (!empty($r['last_error_message'])) {
$html .= ' | last error: ' . htmlspecialchars((string) $r['last_error_message']);
}
$html .= ' ';
}
return $html . '
';
}
private static function reply(string $token, string $chat, int $mid, string $text): void
{
self::api($token, 'sendMessage', [
'chat_id' => $chat, 'text' => $text, 'reply_to_message_id' => $mid,
'allow_sending_without_reply' => 'true', 'disable_web_page_preview' => 'true',
], 15);
}
private static function fetchPhoto(string $token, string $fileId): ?string
{
$r = self::api($token, 'getFile', ['file_id' => $fileId]);
$path = (string) ($r['result']['file_path'] ?? '');
if ($path === '') { return null; }
$url = "https://api.telegram.org/file/bot{$token}/{$path}";
try {
$resp = Http::timeout(40)->get($url);
} catch (\Throwable $e) {
try { $resp = Http::withoutVerifying()->timeout(40)->get($url); } catch (\Throwable $e2) { return null; }
}
if (!$resp->successful()) { return null; }
$raw = $resp->body();
if (strlen($raw) < 2000) { return null; }
$src = @imagecreatefromstring($raw);
if (!$src) { return null; }
$w = imagesx($src);
$h = imagesy($src);
$max = 1600;
if ($w > $max) {
$nh = (int) round($h * $max / $w);
$c = imagecreatetruecolor($max, $nh);
imagecopyresampled($c, $src, 0, 0, 0, 0, $max, $nh, $w, $h);
imagedestroy($src);
$src = $c;
}
ob_start();
imagejpeg($src, null, 92);
$jpg = ob_get_clean();
imagedestroy($src);
return $jpg !== '' ? $jpg : null;
}
/** Telegram webhook er entry. Sob somoy 200 dey (nahole Telegram bar bar retry kore purono khobor joma kore) */
public static function webhook(bool $licenseOk): void
{
header('Content-Type: text/plain; charset=utf-8');
http_response_code(200);
$secret = $licenseOk ? AnGuard::cfg('tg_secret') : '';
if (!$licenseOk || AnGuard::cfg('tg_on') !== '1' || $secret === '') {
echo 'ignored';
return;
}
$got = (string) ($_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '');
if (!hash_equals($secret, $got)) {
http_response_code(403);
echo 'forbidden';
return;
}
$u = json_decode((string) file_get_contents('php://input'), true);
// Telegram ke ekdom 200 diye din, baki kaj pichone cholbe
ignore_user_abort(true);
@set_time_limit(180);
echo 'ok';
if (function_exists('fastcgi_finish_request')) { @fastcgi_finish_request(); } else { @flush(); }
if (!is_array($u) || !isset($u['message']) || !is_array($u['message'])) { return; }
$m = $u['message'];
$token = AnGuard::cfg('tg_token');
$want = AnGuard::cfg('tg_chat');
$chatId = (string) ($m['chat']['id'] ?? '');
$mid = (int) ($m['message_id'] ?? 0);
if ($token === '' || $chatId === '' || $mid === 0) { return; }
// /id : group er Chat ID jante (setup er somoy)
$text = trim((string) ($m['text'] ?? ''));
if ($text !== '' && preg_match('#^/id(@\w+)?$#iu', $text)) {
self::reply($token, $chatId, $mid, "Chat ID: {$chatId}\nএটা License Manager এর Telegram ট্যাবে বসান।");
return;
}
if ($want === '' || $chatId !== $want) { return; }
if (!empty($m['from']['is_bot'])) { return; }
if (time() - (int) ($m['date'] ?? 0) > 1800) { return; } // 30 minute er purono khobor post hobe na
// Shudhu "chhobi + caption" wala message. Text-only / caption chhara chhobi: chupchap bad
$caption = trim((string) ($m['caption'] ?? ''));
if ($caption === '' || mb_strlen($caption) < 15) { return; }
$fileId = '';
if (!empty($m['photo']) && is_array($m['photo'])) {
$bestArea = -1;
foreach ($m['photo'] as $p) {
$a = (int) ($p['width'] ?? 0) * (int) ($p['height'] ?? 0);
if (!empty($p['file_id']) && $a >= $bestArea) { $bestArea = $a; $fileId = (string) $p['file_id']; }
}
} elseif (!empty($m['document']['file_id']) && strpos((string) ($m['document']['mime_type'] ?? ''), 'image/') === 0) {
$fileId = (string) $m['document']['file_id'];
}
if ($fileId === '') { return; }
// ekoi message dubar na (Telegram retry / album)
if (!Cache::add('an_tg_' . md5($chatId . ':' . $mid), 1, 259200)) { return; }
$notify = (string) AnEnv::get('TG_REPLY', '1') !== '0';
try {
$lines = array_values(array_filter(array_map('trim', preg_split('/\R/u', $caption)), fn($l) => $l !== ''));
$title = (string) array_shift($lines);
if (mb_strlen($title) > 140) {
array_unshift($lines, $title);
$title = mb_substr($title, 0, 137) . '...';
}
if (!$lines) { $lines = [$title]; }
$html = '';
foreach ($lines as $l) { $html .= '' . htmlspecialchars($l, ENT_QUOTES, 'UTF-8') . '
'; }
$img = self::fetchPhoto($token, $fileId);
if (!$img) {
if ($notify) { self::reply($token, $chatId, $mid, '⚠️ ছবি নামানো যায়নি, আবার পাঠান।'); }
return;
}
$cmd = new FetchNewsCommand();
$res = $cmd->publishDirect($title, $html, $img, 'telegram:' . $chatId . ':' . $mid);
if ($notify) {
if (!empty($res['ok'])) {
$fb = ($res['fb'] ?? '') === 'ok' ? ' | Facebook ✓' : '';
self::reply($token, $chatId, $mid, '✅ পোস্ট হয়েছে' . $fb . (!empty($res['cat']) ? ' | ক্যাটাগরি: ' . $res['cat'] : '') . "\n" . $res['url']);
} else {
self::reply($token, $chatId, $mid, '⚠️ পোস্ট হয়নি: ' . ($res['err'] ?? 'unknown'));
}
}
} catch (\Throwable $e) {
Log::error('AutoNewsKit Telegram error: ' . $e->getMessage());
if ($notify) { self::reply($token, $chatId, $mid, '⚠️ পোস্ট করতে সমস্যা হয়েছে। আবার পাঠান।'); }
}
}
}
/* ===================== Entry point ===================== */
final class AnEntry
{
public static function go($kernel): void
{
$web = PHP_SAPI !== 'cli';
// License manager ei URL e call kore proof nei (domain asholei ei site er kina)
if ($web && isset($_GET['an_proof'])) {
$st = AnState::load();
$nonce = preg_replace('/[^a-f0-9]/', '', (string) $_GET['an_proof']);
header('Content-Type: application/json');
echo json_encode(['proof' => hash('sha256', $nonce . ($st['iid'] ?? ''))]);
return;
}
if ($web) {
header('Content-Type: text/html; charset=utf-8');
header('X-Robots-Tag: noindex');
try {
$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
app('url')->forceRootUrl(($https ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']);
} catch (\Throwable $e) {}
}
[$ok, $reason, $status] = AnGuard::check();
// Telegram webhook (reporter group) — license + Telegram service chalu thakle-i kaj kore, nahole chupchap 200
if ($web && isset($_GET['tg'])) {
AnTg::webhook($ok);
return;
}
if ($web && isset($_GET['status'])) {
echo ' '
. 'AutoNewsKit status Domain: ' . htmlspecialchars(AnGuard::domain()) . '
'
. ($ok ? '✔ ' : '✖ ') . htmlspecialchars($reason) . '
' . AnTg::statusHtml() . '';
return;
}
if (!$ok) {
if ($web) {
http_response_code($status === 'offline' ? 503 : 403);
echo AnUi::blocked(AnGuard::domain(), $reason, $status);
} else {
fwrite(STDOUT, "Service suspended: {$reason}\n");
}
return;
}
// Telegram service chalu thakle webhook nijei thik rakhe (na thakle kichui kore na)
AnTg::ensureWebhook();
// ekshathe duita cholbe na + spam atkano (45 sekend cool-down)
$lock = @fopen(AnState::dir() . '/.autonews.lock', 'c');
if ($lock && !flock($lock, LOCK_EX | LOCK_NB)) {
echo $web ? 'Already running... ektu pore try korun.
' : "Already running\n";
return;
}
$st = AnState::load();
if (!empty($st['last_run']) && time() - (int) $st['last_run'] < 45) {
echo $web ? 'Ekhon ektu agei cholechhe. ৪৫ sekend pore abar try korun.
' : "Cooldown\n";
return;
}
$st['last_run'] = time();
AnState::save($st);
@set_time_limit(300);
@ignore_user_abort(true);
$kernel->registerCommand(new FetchNewsCommand());
$params = isset($_GET['card-test']) ? ['--card-test' => true] : [];
$kernel->call('autonews:run', $params);
$out = trim($kernel->output());
if ($out !== '') {
echo $web ? '' . htmlspecialchars($out) . ' ' : $out . "\n";
}
}
}
if (defined('AN_STANDALONE')) {
AnEntry::go($__kernel);
}