# ai-builder/2.2.1/test-blocks.php

AI Builder – Generate pages, blocks, images &amp; translate with AI, version 2.2.1. 508 lines.

- Page: https://pluginprobe.com/plugins/ai-builder/2.2.1/code/test-blocks.php
- Raw: https://pluginprobe.com/plugins/ai-builder/2.2.1/raw/test-blocks.php
- Modified: 2025-10-30T10:51:24+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/ai-builder/2.2.1/code/test-blocks.php#L10-L20`.

```php
<?php
/**
 * Script de test pour valider le format HTML sérialisé des blocs WordPress
 * 
 * Usage:
 * 1. Placez ce fichier à la racine de votre plugin
 * 2. Collez votre contenu HTML dans la variable $test_content ci-dessous
 * 3. Accédez au fichier via votre navigateur ou exécutez-le en ligne de commande
 * 
 * Ou utilisez-le comme page admin WordPress:
 * ?page=test-blocks&content=[VOTRE_CONTENU_ENCODED]
 */

// Charger WordPress si nécessaire (si exécuté en standalone)
if (!function_exists('parse_blocks')) {
    // Ajustez ce chemin selon votre installation
    require_once(__DIR__ . '/../../../wp-load.php');
}

// Fonction pour tester un contenu de bloc
function test_block_content($html_content) {
    $results = [
        'valid' => true,
        'errors' => [],
        'warnings' => [],
        'blocks' => [],
        'total_blocks' => 0
    ];
    
    if (empty($html_content)) {
        $results['valid'] = false;
        $results['errors'][] = 'Le contenu est vide';
        return $results;
    }
    
    // Vérifier que ça commence par un commentaire de bloc WordPress
    $trimmed = trim($html_content);
    if (strpos($trimmed, '<!-- wp:') !== 0) {
        $results['warnings'][] = 'Le contenu ne commence pas par un commentaire de bloc WordPress';
    }
    
    // Parser les blocs
    $parsed_blocks = parse_blocks($html_content);
    
    if (empty($parsed_blocks)) {
        $results['valid'] = false;
        $results['errors'][] = 'Aucun bloc n\'a pu être parsé. Le format est peut-être invalide.';
        return $results;
    }
    
    $results['total_blocks'] = count($parsed_blocks);
    
    // Analyser chaque bloc
    foreach ($parsed_blocks as $index => $block) {
        $block_info = [
            'index' => $index,
            'blockName' => $block['blockName'] ?? 'INCONNU',
            'valid' => true,
            'errors' => [],
            'warnings' => [],
            'attrs' => $block['attrs'] ?? [],
            'innerBlocks_count' => isset($block['innerBlocks']) ? count($block['innerBlocks']) : 0,
            'innerContent_count' => isset($block['innerContent']) ? count($block['innerContent']) : 0
        ];
        
        // Vérifier que le bloc a un nom
        if (empty($block['blockName'])) {
            $block_info['valid'] = false;
            $block_info['errors'][] = 'Le bloc n\'a pas de nom (blockName)';
            $results['valid'] = false;
        }
        
        // Tester la sérialisation/désérialisation
        try {
            $serialized = serialize_block($block);
            if (empty($serialized)) {
                $block_info['valid'] = false;
                $block_info['errors'][] = 'La sérialisation du bloc échoue (retour vide)';
                $results['valid'] = false;
            } else {
                // Vérifier qu'on peut le reparser
                $reparsed = parse_blocks($serialized);
                if (empty($reparsed)) {
                    $block_info['valid'] = false;
                    $block_info['errors'][] = 'Le bloc sérialisé ne peut pas être re-parsé';
                    $results['valid'] = false;
                } elseif ($reparsed[0]['blockName'] !== $block['blockName']) {
                    $block_info['warnings'][] = 'Le blocName change après sérialisation/parsing';
                }
            }
        } catch (Exception $e) {
            $block_info['valid'] = false;
            $block_info['errors'][] = 'Erreur lors de la sérialisation: ' . $e->getMessage();
            $results['valid'] = false;
        }
        
        // Vérifier les attributs JSON (s'ils existent dans le commentaire)
        if (!empty($block['attrs'])) {
            $attrs_json = json_encode($block['attrs']);
            if ($attrs_json === false) {
                $block_info['warnings'][] = 'Les attributs ne peuvent pas être encodés en JSON valide';
            }
        }
        
        // Vérifier la structure innerContent vs innerBlocks pour les blocs conteneurs
        if (!empty($block['innerBlocks'])) {
            if (empty($block['innerContent']) || !is_array($block['innerContent'])) {
                $block_info['warnings'][] = 'Le bloc a des innerBlocks mais pas de innerContent défini';
            } else {
                // innerContent devrait avoir des null là où sont les innerBlocks
                $null_count = count(array_filter($block['innerContent'], function($item) {
                    return $item === null;
                }));
                if ($null_count !== count($block['innerBlocks'])) {
                    $block_info['warnings'][] = "Le nombre de null dans innerContent ({$null_count}) ne correspond pas au nombre d'innerBlocks (" . count($block['innerBlocks']) . ")";
                }
            }
        }
        
        $results['blocks'][] = $block_info;
        if (!$block_info['valid']) {
            $results['errors'][] = "Bloc #{$index} ({$block_info['blockName']}): " . implode(', ', $block_info['errors']);
        }
        if (!empty($block_info['warnings'])) {
            $results['warnings'][] = "Bloc #{$index} ({$block_info['blockName']}): " . implode(', ', $block_info['warnings']);
        }
    }
    
    return $results;
}

// Fonction pour extraire et valider les JSON dans les commentaires
function validate_block_comments($html_content) {
    $errors = [];
    $fixes = [];
    preg_match_all('/<!-- wp:([^\s]+)\s+(\{.*?\})\s*-->/', $html_content, $matches, PREG_SET_ORDER);
    
    foreach ($matches as $index => $match) {
        $block_name = $match[1];
        $json_str = $match[2];
        
        // Décoder le JSON
        $decoded = json_decode($json_str, true);
        if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
            // Essayer de corriger le JSON échappé
            $fixed_json = stripslashes($json_str);
            $decoded_fixed = json_decode($fixed_json, true);
            
            $error_info = [
                'block' => $block_name,
                'position' => strpos($html_content, $match[0]),
                'error' => 'JSON invalide: ' . json_last_error_msg(),
                'json' => $json_str,
                'is_escaped' => false,
                'can_be_fixed' => false,
                'fixed_json' => null
            ];
            
            // Vérifier si le JSON contient des guillemets échappés
            if (strpos($json_str, '\\"') !== false || strpos($json_str, '\\\'') !== false) {
                $error_info['is_escaped'] = true;
                
                if ($decoded_fixed !== null && json_last_error() === JSON_ERROR_NONE) {
                    $error_info['can_be_fixed'] = true;
                    $error_info['fixed_json'] = $fixed_json;
                    $fixes[] = [
                        'block' => $block_name,
                        'original' => $json_str,
                        'fixed' => $fixed_json
                    ];
                }
            }
            
            $errors[] = $error_info;
        }
    }
    
    return ['errors' => $errors, 'fixes' => $fixes];
}

// Fonction pour corriger automatiquement le HTML échappé
function fix_escaped_html($html_content) {
    // Retirer les backslashes des guillemets dans les JSON des commentaires
    $fixed = preg_replace_callback(
        '/<!-- wp:([^\s]+)\s+(\{.*?\})\s*-->/',
        function($matches) {
            $block_name = $matches[1];
            $json_str = $matches[2];
            $fixed_json = stripslashes($json_str);
            return "<!-- wp:{$block_name} {$fixed_json} -->";
        },
        $html_content
    );
    
    return $fixed;
}

// ============================================
// ZONE DE TEST - Collez votre contenu ici
// ============================================

$test_content = '';
// Collez votre HTML sérialisé ici, ou laissez vide pour utiliser le paramètre GET

// Si exécuté dans WordPress, vérifier les paramètres GET
if (isset($_GET['content']) && !empty($_GET['content'])) {
    $test_content = urldecode($_GET['content']);
} elseif (!empty($test_content)) {
    // Utiliser le contenu défini ci-dessus
} else {
    // Exemple de contenu pour test
    $test_content = '<!-- wp:paragraph -->
<p>Test paragraph</p>
<!-- /wp:paragraph -->';
}

?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Testeur de Blocs WordPress</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1 {
            color: #23282d;
            border-bottom: 2px solid #0073aa;
            padding-bottom: 10px;
        }
        h2 {
            color: #0073aa;
            margin-top: 30px;
        }
        .status {
            padding: 15px;
            border-radius: 4px;
            margin: 15px 0;
            font-weight: bold;
        }
        .status.valid {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.invalid {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .errors, .warnings {
            margin: 15px 0;
            padding: 15px;
            border-radius: 4px;
        }
        .errors {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
        }
        .warnings {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
        }
        .error-item, .warning-item {
            margin: 8px 0;
            padding: 8px;
            background: white;
            border-left: 3px solid;
        }
        .error-item {
            border-color: #ff6b6b;
        }
        .warning-item {
            border-color: #4dabf7;
        }
        .block-info {
            margin: 15px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid #0073aa;
        }
        .block-info.invalid {
            border-left-color: #dc3545;
        }
        .block-name {
            font-weight: bold;
            color: #0073aa;
            margin-bottom: 10px;
        }
        code {
            background: #f4f4f4;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
        }
        textarea {
            width: 100%;
            min-height: 300px;
            padding: 10px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            border: 2px solid #ddd;
            border-radius: 4px;
        }
        button {
            background: #0073aa;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
        }
        button:hover {
            background: #005177;
        }
        .json-errors {
            margin-top: 20px;
        }
        .json-error-item {
            background: #fff3cd;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            border-left: 3px solid #ff9800;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 Testeur de Blocs WordPress</h1>
        
        <form method="GET">
            <h2>Collez votre contenu HTML sérialisé ici:</h2>
            <textarea name="content" placeholder="<!-- wp:paragraph -->..."><?php echo htmlspecialchars($test_content); ?></textarea>
            <button type="submit">Tester le contenu</button>
        </form>
    </div>

<?php if (!empty($test_content)): ?>
    <?php
    // Détecter et corriger si nécessaire
    $original_content = $test_content;
    $json_validation = validate_block_comments($test_content);
    $json_errors = $json_validation['errors'];
    $json_fixes = $json_validation['fixes'];
    
    // Si des corrections sont possibles, les appliquer
    $has_escaped_json = false;
    foreach ($json_errors as $error) {
        if ($error['is_escaped'] && $error['can_be_fixed']) {
            $has_escaped_json = true;
            break;
        }
    }
    
    if ($has_escaped_json && !empty($json_fixes)) {
        $test_content = fix_escaped_html($test_content);
    }
    
    $results = test_block_content($test_content);
    ?>
    
    <div class="container">
        <h2>📊 Résultats du Test</h2>
        
        <?php if ($has_escaped_json && !empty($json_fixes)): ?>
            <div class="status valid" style="background: #fff3cd; color: #856404; border-color: #ffeaa7;">
                ⚠️ Correction automatique appliquée : Les guillemets échappés (`\"`) ont été corrigés dans les commentaires JSON
                <br>
                <small><?php echo count($json_fixes); ?> bloc(s) corrigé(s)</small>
            </div>
        <?php endif; ?>

        <div class="status <?php echo $results['valid'] ? 'valid' : 'invalid'; ?>">
            <?php if ($results['valid']): ?>
                ✅ Le contenu est valide <?php echo $has_escaped_json ? '(après correction)' : ''; ?>!
            <?php else: ?>
                ❌ Le contenu contient des erreurs
            <?php endif; ?>
            <br>
            <small>Nombre total de blocs: <?php echo $results['total_blocks']; ?></small>
        </div>

        <?php if (!empty($results['errors'])): ?>
            <div class="errors">
                <h3>❌ Erreurs détectées:</h3>
                <?php foreach ($results['errors'] as $error): ?>
                    <div class="error-item"><?php echo htmlspecialchars($error); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($results['warnings'])): ?>
            <div class="warnings">
                <h3>⚠️ Avertissements:</h3>
                <?php foreach ($results['warnings'] as $warning): ?>
                    <div class="warning-item"><?php echo htmlspecialchars($warning); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($json_errors)): ?>
            <div class="json-errors">
                <h3>📝 Erreurs JSON dans les commentaires:</h3>
                <?php foreach ($json_errors as $json_error): ?>
                    <div class="json-error-item">
                        <strong>Bloc:</strong> <code><?php echo htmlspecialchars($json_error['block']); ?></code><br>
                        <strong>Erreur:</strong> <?php echo htmlspecialchars($json_error['error']); ?><br>
                        <?php if ($json_error['is_escaped']): ?>
                            <strong style="color: #856404;">⚠️ JSON échappé détecté (guillemets avec backslashes)</strong><br>
                            <?php if ($json_error['can_be_fixed']): ?>
                                <strong style="color: #28a745;">✅ Correction automatique possible</strong><br>
                                <strong>JSON original (échappé):</strong><br>
                                <code style="display:block;margin-top:5px;max-height:100px;overflow:auto;background:#ffeaa7;"><?php echo htmlspecialchars($json_error['json']); ?></code>
                                <strong>JSON corrigé:</strong><br>
                                <code style="display:block;margin-top:5px;max-height:100px;overflow:auto;background:#d4edda;"><?php echo htmlspecialchars($json_error['fixed_json']); ?></code>
                            <?php else: ?>
                                <strong>JSON problématique:</strong><br>
                                <code style="display:block;margin-top:5px;max-height:100px;overflow:auto;"><?php echo htmlspecialchars($json_error['json']); ?></code>
                            <?php endif; ?>
                        <?php else: ?>
                            <strong>JSON problématique:</strong><br>
                            <code style="display:block;margin-top:5px;max-height:100px;overflow:auto;"><?php echo htmlspecialchars($json_error['json']); ?></code>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        
        <?php if ($has_escaped_json && !empty($json_fixes)): ?>
            <div class="container" style="margin-top: 20px; background: #d4edda; border: 1px solid #c3e6cb;">
                <h3>✅ Contenu corrigé (à utiliser):</h3>
                <textarea readonly style="min-height: 200px; font-size: 11px;"><?php echo htmlspecialchars($test_content); ?></textarea>
                <p><small>📋 Copiez ce contenu corrigé et utilisez-le à la place de l'original</small></p>
            </div>
        <?php endif; ?>

        <h2>📦 Détails des Blocs</h2>
        <?php foreach ($results['blocks'] as $block): ?>
            <div class="block-info <?php echo $block['valid'] ? '' : 'invalid'; ?>">
                <div class="block-name">
                    Bloc #<?php echo $block['index']; ?>: 
                    <code><?php echo htmlspecialchars($block['blockName']); ?></code>
                    <?php if (!$block['valid']): ?>
                        <span style="color: #dc3545;">❌</span>
                    <?php else: ?>
                        <span style="color: #28a745;">✅</span>
                    <?php endif; ?>
                </div>
                
                <div style="margin-top: 10px; font-size: 0.9em; color: #666;">
                    <strong>Inner Blocks:</strong> <?php echo $block['innerBlocks_count']; ?><br>
                    <strong>Inner Content items:</strong> <?php echo $block['innerContent_count']; ?>
                </div>

                <?php if (!empty($block['errors'])): ?>
                    <div style="margin-top: 10px;">
                        <strong style="color: #dc3545;">Erreurs:</strong>
                        <ul>
                            <?php foreach ($block['errors'] as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?php if (!empty($block['warnings'])): ?>
                    <div style="margin-top: 10px;">
                        <strong style="color: #ff9800;">Avertissements:</strong>
                        <ul>
                            <?php foreach ($block['warnings'] as $warning): ?>
                                <li><?php echo htmlspecialchars($warning); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?php if (!empty($block['attrs'])): ?>
                    <details style="margin-top: 10px;">
                        <summary style="cursor: pointer; color: #0073aa;">Attributs (cliquez pour voir)</summary>
                        <pre style="background: #f4f4f4; padding: 10px; margin-top: 5px; border-radius: 4px; overflow: auto; max-height: 200px;"><?php echo htmlspecialchars(json_encode($block['attrs'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
                    </details>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

</body>
</html>

```
