# mbstring Fix Summary

**Date:** 2026-01-15  
**Issue:** FAQPage schema generation uses `mb_*` functions without `function_exists` checks  
**Status:** ✅ Fixed

## Problem Identified

The FAQPage schema generation code in `v2/config/blog-schema-generator.php` (lines 433-434) was using `mb_check_encoding()` and `mb_convert_encoding()` without checking if the `mbstring` extension is available.

**Original Code (PROBLEMATIC):**

```php
// Step 6: Ensure UTF-8 encoding
if (!mb_check_encoding($answer_text, 'UTF-8')) {
    $answer_text = mb_convert_encoding($answer_text, 'UTF-8', 'UTF-8');
}
```

**Issue:**

- If `mbstring` extension is not available in production, these function calls would cause fatal errors
- This is a recurring issue that has caused production failures before
- The error would be silent if error reporting is disabled, causing FAQPage schema to fail silently

## Solution Implemented

Added `function_exists` checks with fallback logic:

**Fixed Code:**

```php
// Step 6: Ensure UTF-8 encoding
// Use function_exists check to avoid production errors if mbstring extension is not available
if (function_exists('mb_check_encoding') && function_exists('mb_convert_encoding')) {
    if (!mb_check_encoding($answer_text, 'UTF-8')) {
        $answer_text = mb_convert_encoding($answer_text, 'UTF-8', 'UTF-8');
    }
} else {
    // Fallback: Use iconv if available, otherwise skip encoding check
    if (function_exists('iconv')) {
        $answer_text = iconv('UTF-8', 'UTF-8//IGNORE', $answer_text);
    }
    // If neither mbstring nor iconv available, continue with string as-is
    // The preg_replace in Step 7 will clean up any invalid characters
}
```

## Fallback Strategy

1. **Primary:** Use `mbstring` functions if available
2. **Fallback 1:** Use `iconv` if `mbstring` is not available
3. **Fallback 2:** Continue with string as-is if neither is available
4. **Safety Net:** The `preg_replace` in Step 7 removes invalid control characters

## Testing

Created comprehensive test scripts:

1. **`test-without-mbstring.php`** - Tests schema generation without mbstring
2. **`test-mbstring-fallback.php`** - Tests fallback logic
3. **`verify-mbstring-fix.php`** - Verifies the fix works correctly

All tests pass ✅

## Files Modified

- `v2/config/blog-schema-generator.php` (lines 432-444)
  - Added `function_exists` checks
  - Added fallback logic using `iconv`
  - Added comments explaining the fallback strategy

## Production Readiness

✅ **Code is production-ready:**

- Handles missing `mbstring` extension gracefully
- Falls back to `iconv` if available
- Continues processing even if no encoding functions are available
- No breaking changes - existing functionality preserved

## Related Patterns

The codebase already has similar patterns in `v2/config/blog-template-helpers.php`:

- `_has_mbstring()` function to check mbstring availability
- Fallback functions for `mb_strlen`, `mb_substr`, etc.
- Consistent use of `function_exists` checks before calling `mb_*` functions

## Prevention

To prevent similar issues in the future:

1. **Always check** `function_exists()` before calling `mb_*` functions
2. **Use fallbacks** when mbstring is not available
3. **Test locally** without mbstring extension if possible
4. **Follow existing patterns** in `blog-template-helpers.php`

## Comprehensive Prevention Measures

**Implemented comprehensive prevention system:**

### Cursor Rules

- **`.cursor/rules/php-extensions.mdc`** - Complete PHP extension dependency patterns and rules
- **`.cursor/rules/global.mdc`** - Added PHP Extension Dependencies section
- **`.cursor/rules/blog-production.mdc`** - Added PHP extension requirements for blog system

### Documentation

- **`docs/development/PHP_EXTENSION_DEPENDENCIES.md`** - Comprehensive guide covering all PHP extensions
- **`docs/development/PHP_EXTENSION_FALLBACK_PATTERNS.md`** - Standardized fallback patterns with copy-paste code
- **`docs/development/PRODUCTION_DEPLOYMENT_CHECKLIST.md`** - Pre-deployment validation checklist

### Validation Scripts

- **`v2/scripts/dev-helpers/check-php-extensions.php`** - Extension validator script
- **`v2/scripts/dev-helpers/pre-deployment-check.php`** - Comprehensive pre-deployment validator
- **`v2/api/php-extensions-diagnostics.php`** - Web-accessible diagnostic endpoint

### Helper Functions

- **`v2/helpers/php-extensions.php`** - Standardized extension helper functions

### Composer Configuration

- **`composer.json`** - Declares extension requirements (`ext-mbstring`, `ext-iconv`, `ext-json`, `ext-curl`)

### Code Patterns

All new code must follow these patterns:

1. **Check before use:**

   ```php
   if (function_exists('mb_strlen')) {
       $length = mb_strlen($text, 'UTF-8');
   } else {
       $length = strlen($text);
   }
   ```

2. **Provide fallbacks:**

   ```php
   if (function_exists('mb_convert_encoding')) {
       $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
   } elseif (function_exists('iconv')) {
       $text = iconv('UTF-8', 'UTF-8//IGNORE', $text);
   }
   ```

3. **Log fallback usage:**
   ```php
   if (!extension_loaded('mbstring')) {
       error_log('WARNING: mbstring not available, using fallback');
   }
   ```

### Pre-Deployment Checklist

Before every deployment:

- [ ] Run `php v2/scripts/dev-helpers/check-php-extensions.php`
- [ ] Run `php v2/scripts/dev-helpers/pre-deployment-check.php`
- [ ] Verify `composer install --no-dev` succeeds
- [ ] Test fallback logic locally (if possible)
- [ ] Review code for extension checks
- [ ] Verify production environment extensions

## Related Documentation

- `.cursor/rules/php-extensions.mdc` - Cursor rules for PHP extensions
- `docs/development/PHP_EXTENSION_DEPENDENCIES.md` - Comprehensive extension guide
- `docs/development/PHP_EXTENSION_FALLBACK_PATTERNS.md` - Fallback patterns
- `docs/development/PRODUCTION_DEPLOYMENT_CHECKLIST.md` - Deployment checklist
- `docs/development/COMPOSER_EXTENSION_REQUIREMENTS.md` - Composer requirements

## Next Steps

1. ✅ Code fixed and tested
2. ✅ Ready for production deployment
3. ✅ Comprehensive prevention measures implemented
4. ✅ Documentation created
5. ✅ Validation scripts created
6. ⏭️ Deploy and verify FAQPage schema appears in production
7. ⏭️ Run audit to identify other extension usage
8. ⏭️ Standardize extension checks across codebase
