Skip to content

Commit 2373949

Browse files
Copilotswissspidy
andcommitted
Refine validation: use PHP native base64 strict mode and add size constant
- Replace regex validation with PHP's native base64_decode strict mode - Add MAX_IMAGE_SIZE_BASE64 constant for clarity and maintainability - Simplify base64 validation logic to rely on built-in strict validation - Improve error messages for better user feedback Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent f561230 commit 2373949

1 file changed

Lines changed: 11 additions & 8 deletions

File tree

src/AI_Command.php

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@
3030
*/
3131
class AI_Command extends WP_CLI_Command {
3232

33+
/**
34+
* Maximum size for base64-encoded image data (50MB binary = ~67MB base64).
35+
*/
36+
const MAX_IMAGE_SIZE_BASE64 = 70000000; // 50 * 1024 * 1024 * 4 / 3 rounded up
37+
3338
/**
3439
* Generates AI content.
3540
*
@@ -246,20 +251,18 @@ private function generate_image( $builder, $assoc_args ) {
246251
WP_CLI::error( 'Invalid image data received.' );
247252
}
248253

249-
// Validate base64 format before decoding
254+
// Validate and decode base64 data
250255
$base64_data = $data_parts[1];
251-
if ( ! preg_match( '/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $base64_data ) ) {
252-
WP_CLI::error( 'Invalid base64 data format.' );
253-
}
254256

255-
// Check reasonable size limit (e.g., 50MB)
256-
if ( strlen( $base64_data ) > 50 * 1024 * 1024 * 4 / 3 ) {
257-
WP_CLI::error( 'Image data exceeds maximum size limit.' );
257+
// Check reasonable size limit
258+
if ( strlen( $base64_data ) > self::MAX_IMAGE_SIZE_BASE64 ) {
259+
WP_CLI::error( 'Image data exceeds maximum size limit (50MB).' );
258260
}
259261

262+
// Try strict base64 decode - this validates format
260263
$image_data = base64_decode( $base64_data, true );
261264
if ( false === $image_data ) {
262-
WP_CLI::error( 'Failed to decode image data.' );
265+
WP_CLI::error( 'Invalid base64 image data format.' );
263266
}
264267

265268
// Save to file

0 commit comments

Comments
 (0)