Files
prautoblogger/includes/providers/class-cloudflare-image-support.php
peptiderepo fb1451c4dc feat(images): retry Cloudflare NSFW-blocked prompts with a sanitized fallback
Cloudflare's Workers AI FLUX.1 schnell content filter sometimes rejects
peptide-comic prompts as NSFW (HTTP 400, errors[].code === 3030). On
2026-04-20 this produced a silent publish-without-featured-image for
post #650 ("Semaglutide vs Tirzepatide") — the LLM-rewritten scene
tripped the filter and we had no recovery path.

New behaviour: on a 3030 response, the Cloudflare provider throws a
typed PRAutoBlogger_Image_NSFW_Blocked exception. The batch wrapper
catches it and tags the per-slot result with
`error_type: nsfw_blocked`. Image_Pipeline hands the results to a new
PRAutoBlogger_Image_NSFW_Retry helper, which reruns the blocked slot
once with a sanitized fallback prompt (title + style suffix, no LLM
rewrite). On success the retry result replaces the error entry; on a
second block, a WARNING is logged and the pipeline publishes without
that image — same terminal behaviour we had before, just explicit.

Files:

- New providers/class-image-nsfw-blocked.php — typed exception.
- providers/class-cloudflare-image-support.php — is_nsfw_error() +
  throw_if_nsfw() helpers.
- providers/class-cloudflare-image-provider.php — calls throw_if_nsfw
  inside the 4xx branch; batch catches the typed exception and marks
  the result with error_type.
- core/class-image-prompt-builder.php — new public build_fallback_prompt
  shim so the retry layer can reach the rule-based fallback without
  going through the LLM path.
- New core/class-image-nsfw-retry.php — single-shot retry helper.
- core/class-image-pipeline.php — invokes the retry between batch
  completion and per-slot processing.
- admin/class-settings-fields-extended.php — new toggle
  `prautoblogger_image_nsfw_retry` (default on) in the Images section.

Tests:

- CloudflareImageProviderTest — 3030 response throws NSFW exception;
  batch tags the per-slot result with `error_type: nsfw_blocked`.
- ImagePipelineTest — retry succeeds when provider returns a good
  result on the second call; retry is skipped when the setting is off.

Cost impact: worst-case an extra Cloudflare call per NSFW-blocked slot
(~$0.000834). Current incidence ~2% of generations; ~+$0.00002 per
generation amortized. Immaterial.

Uninstall: new option covered by the existing prautoblogger_% LIKE
sweep in uninstall.php.

Part of the v0.8.0 image bundle (issues from thread image-mime-bug).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 01:06:59 +07:00

173 lines
5.5 KiB
PHP

<?php
declare(strict_types=1);
/**
* Small support helpers for the Cloudflare image provider — credential
* lookups, URL building, and structured log lines.
*
* Split out of the provider so the provider stays under the 300-line cap
* and so these tiny pieces are individually testable. Pure functions plus
* one logger forward; no state.
*
* Triggered by: PRAutoBlogger_Cloudflare_Image_Provider only.
* Dependencies: PRAutoBlogger_Encryption (token decryption),
* PRAutoBlogger_Logger (WARN/ERROR forwarding).
*
* @see class-cloudflare-image-provider.php Sole caller.
*/
class PRAutoBlogger_Cloudflare_Image_Support {
/**
* Decrypt the Cloudflare API token from the settings option.
*
* @return string Plaintext token, or empty string if not set / decrypt fails.
*/
public function get_api_token(): string {
$stored = (string) get_option( 'prautoblogger_cloudflare_ai_token', '' );
if ( '' === $stored ) {
return '';
}
// If the token is already encrypted (has "enc:" prefix), decrypt it.
if ( PRAutoBlogger_Encryption::is_encrypted( $stored ) ) {
return (string) PRAutoBlogger_Encryption::decrypt( $stored );
}
// Legacy: token was saved as plaintext before the field was added to
// the encrypted list in sanitize_field(). Encrypt it now so future
// reads go through the normal path, then return the plaintext value.
$cipher = PRAutoBlogger_Encryption::encrypt( $stored );
if ( '' !== $cipher ) {
update_option( 'prautoblogger_cloudflare_ai_token', $cipher );
}
return $stored;
}
/**
* Read the Cloudflare account ID from settings.
*
* @return string Account UUID, or empty string.
*/
public function get_account_id(): string {
return trim( (string) get_option( 'prautoblogger_cloudflare_account_id', '' ) );
}
/**
* Build the Workers AI run URL for a given account + model.
*
* @param string $account_id Cloudflare account UUID.
* @param string $model Fully-qualified Workers AI model id.
* @return string Fully-formed HTTPS URL.
*/
public function build_endpoint_url( string $account_id, string $model ): string {
return sprintf(
'https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s',
rawurlencode( $account_id ),
ltrim( $model, '/' )
);
}
/**
* Emit a WARN line for a retryable failure.
*
* @param int $attempt 1-based attempt number.
* @param string $failure_class Either 'network' or HTTP status code as string.
* @param string $detail Short failure detail for the log.
* @return void
*/
public function log_retryable_failure( int $attempt, string $failure_class, string $detail ): void {
PRAutoBlogger_Logger::instance()->warning(
sprintf(
'Cloudflare image gen %s failure (attempt %d/%d): %s',
$failure_class,
$attempt,
PRAUTOBLOGGER_MAX_RETRIES,
$detail
),
'cloudflare-image'
);
}
/**
* Log an unrecoverable 4xx with triage context. Never logs the full
* secret — only a 4-char token prefix and a 6-char account prefix.
*
* @param int $status HTTP status returned by Cloudflare.
* @param string $api_token Plaintext token.
* @param string $account_id Account UUID.
* @param string $raw Raw response body (truncated to 300 chars in the log).
* @return void
*/
public function log_client_error( int $status, string $api_token, string $account_id, string $raw ): void {
PRAutoBlogger_Logger::instance()->error(
sprintf(
'Cloudflare image gen HTTP %d (token_prefix=%s, token_len=%d, account=%s): %s',
$status,
substr( $api_token, 0, 4 ),
strlen( $api_token ),
substr( $account_id, 0, 6 ),
substr( $raw, 0, 300 )
),
'cloudflare-image'
);
}
/**
* Cloudflare Workers AI error code for NSFW content rejection.
*
* Observed on FLUX.1 schnell on 2026-04-20 when backfilling the post
* "Semaglutide vs Tirzepatide". Documented upstream as
* `AiError: Input prompt contains NSFW content.`
*/
public const ERROR_CODE_NSFW = 3030;
/**
* Return true when the Cloudflare response body contains the NSFW
* content-filter error code (3030).
*
* The body shape is `{"errors":[{"code":3030,"message":"..."}],...}`.
* Parsing is tolerant: any JSON decode failure or missing key returns
* false, so a malformed 4xx never masquerades as NSFW.
*
* @param string $raw Raw response body from Cloudflare.
* @return bool True when at least one error entry carries code 3030.
*/
public function is_nsfw_error( string $raw ): bool {
$decoded = json_decode( $raw, true );
if ( ! is_array( $decoded ) || empty( $decoded['errors'] ) || ! is_array( $decoded['errors'] ) ) {
return false;
}
foreach ( $decoded['errors'] as $err ) {
if ( is_array( $err ) && (int) ( $err['code'] ?? 0 ) === self::ERROR_CODE_NSFW ) {
return true;
}
}
return false;
}
/**
* Throw a typed NSFW exception when the response body signals CF's
* content-filter rejection (code 3030). No-op otherwise.
*
* Centralised so callers stay at one line at the call site and so the
* exception-construction shape can't drift between call sites.
*
* @param string $raw Raw response body.
* @return void
* @throws PRAutoBlogger_Image_NSFW_Blocked When the body contains code 3030.
*/
public function throw_if_nsfw( string $raw ): void {
if ( ! $this->is_nsfw_error( $raw ) ) {
return;
}
throw new PRAutoBlogger_Image_NSFW_Blocked(
sprintf(
/* translators: %s: truncated error body. */
esc_html__( 'Cloudflare Workers AI rejected the prompt as NSFW: %s', 'prautoblogger' ),
esc_html( substr( $raw, 0, 300 ) )
),
$raw
);
}
}