true, CURLOPT_USERPWD => $user . ':' . $pass, CURLOPT_HTTPHEADER => $headers, CURLOPT_CUSTOMREQUEST => $method, ]); if ($json !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, $json); } $response = curl_exec($ch); if ($response === false) { $error = curl_error($ch); curl_close($ch); throw new Exception('Listmonk API request failed: ' . $error); } $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); } else { $context = stream_context_create([ 'http' => [ 'method' => $method, 'header' => "Content-Type: application/json\r\nAuthorization: Basic " . base64_encode($user . ':' . $pass) . "\r\n", 'content' => $json ?? '', 'timeout' => 10, 'ignore_errors' => true, ], ]); $response = @file_get_contents($url, false, $context); $code = 0; if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) { $code = (int)$m[1]; } if ($response === false) { throw new Exception('Listmonk API request failed.'); } } if ($code < 200 || $code >= 300) { throw new Exception('Listmonk API request failed. HTTP ' . $code . ': ' . $response); } $decoded = json_decode((string)$response, true); return is_array($decoded) ? $decoded : []; } function listmonkCreateCampaign( string $articleId, string $articleUrl, string $title, string $excerpt, string $newsletterTitle = 'Mistakes, Views & Luck', bool $sendImmediately = false ): array { $base = 'http://127.0.0.1:9000'; $user = 'mvlog'; $pass = '1VLUsqSyIQ4xboEd2tmQvgCjWJJk0F3Q'; $listId = 3; // MVLog Readers $templateId = 5; // Your Listmonk template ID $ogImageUrl = 'https://bubulescu.org/out-dir/' . rawurlencode($articleId) . '_og.jpg'; $safeTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); $safeExcerpt = nl2br(htmlspecialchars($excerpt, ENT_QUOTES, 'UTF-8')); $safeArticleUrl = htmlspecialchars($articleUrl, ENT_QUOTES, 'UTF-8'); $safeOgImageUrl = htmlspecialchars($ogImageUrl, ENT_QUOTES, 'UTF-8'); $body = ' ' . $safeTitle . '

' . $safeTitle . '

' . $safeExcerpt . '

Read the story

'; $payload = [ 'name' => $newsletterTitle, 'subject' => $title, 'lists' => [$listId], 'from_email' => 'MVLog ', 'type' => 'regular', 'content_type' => 'html', 'body' => $body, 'template_id' => $templateId, 'messenger' => 'email', 'status' => 'draft', 'headers' => [ ['Reply-To' => 'mvlog@bubulescu.org'] ], ]; $decoded = listmonkApiRequest($base, $user, $pass, 'POST', '/api/campaigns', $payload); if ($sendImmediately) { $campaignId = $decoded['data']['id'] ?? $decoded['id'] ?? null; if (!$campaignId) { throw new Exception('Listmonk campaign create succeeded but campaign ID was not returned.'); } $sendResponse = listmonkApiRequest($base, $user, $pass, 'PUT', '/api/campaigns/' . rawurlencode((string)$campaignId) . '/status', [ 'status' => 'running', ]); $decoded['send_response'] = $sendResponse; } return $decoded; }