daycry/maintenancemode

Maintenance mode for Codeigniter 4

v2.0.0 2025-08-04 22:38 UTC

This package is auto-updated.

Last update: 2025-08-04 22:39:15 UTC


README

Donate

๐Ÿ”ง Maintenance Mode for CodeIgniter 4

A powerful, modern and highly configurable maintenance mode library for CodeIgniter 4 with intelligent caching, modern UI, and advanced features.

Build status Coverage status Downloads GitHub release (latest by date) GitHub stars GitHub license

โœจ Features

  • ๐Ÿš€ High Performance: Intelligent cache-based storage system (10x faster than file-based)
  • ๐ŸŽจ Modern UI: Responsive, dark-mode compatible maintenance page with auto-refresh
  • ๐Ÿ”’ Multiple Bypass Methods: IP whitelist, cookies, and secret URL bypass
  • ๐Ÿ“Š Comprehensive Logging: Complete audit trail of maintenance events
  • โš™๏ธ Highly Configurable: Extensive configuration options for all scenarios
  • ๐ŸŒ Scalable: Works perfectly in distributed environments
  • ๐Ÿ”„ Backward Compatible: 100% compatible with existing implementations
  • ๐Ÿ“ฑ Mobile-Friendly: Fully responsive design with accessibility features

๐Ÿ“ฆ Installation

Install via Composer:

composer require daycry/maintenancemode

โš™๏ธ Configuration

1. Publish Configuration

php spark mm:publish

This creates app/Config/Maintenance.php with all available options.

2. Basic Configuration

<?php
// app/Config/Maintenance.php

public bool $useCache = true;                    // Use cache instead of files (recommended)
public bool $enableLogging = true;              // Log maintenance events
public string $defaultMessage = 'We are currently performing maintenance...';
public bool $allowSecretBypass = true;          // Enable secret URL bypass
public string $secretBypassKey = 'your-secret-key';

3. Cache Configuration (Recommended)

For optimal performance, configure your cache in app/Config/Cache.php:

// Redis (recommended for production)
public array $redis = [
    'handler' => 'redis',
    'host'    => '127.0.0.1',
    'port'    => 6379,
    // ... other settings
];

// Or use any other cache driver (Memcached, File, etc.)

Commands Available

php spark mm:down
php spark mm:status
php spark mm:up

Use it

Method 1 (Recommended)

Create new event in app/Config/Events.php

Events::on( 'pre_system', 'Daycry\Maintenance\Controllers\Maintenance::check' );

Method 2

edit application/Config/Filters.php and add the new line in $aliases array:

public $aliases = [
    'maintenance' => \Daycry\Maintenance\Filters\Maintenance::class,
    ...
]

and add "maintenance" in $globals['before'] array:

public $globals = [
    'before' => [
        'maintenance',
        ...
    ],
    'after'  => [
        ...
    ],
];

๐ŸŽฏ Enhanced Commands

Activate Maintenance Mode

# Basic activation
php spark mm:down

# With custom message
php spark mm:down --message="We'll be back in 30 minutes!"

# With IP whitelist (multiple IPs supported)
php spark mm:down --allow=192.168.1.100,203.0.113.0

# With automatic expiry (30 minutes)
php spark mm:down --duration=30

# With secret bypass key
php spark mm:down --secret=my-secret-123

Check Status

php spark mm:status

This displays a comprehensive status table with:

  • ๐Ÿ”ด/๐ŸŸข Current status indicator
  • ๐Ÿ“ Storage method (cache/file)
  • ๐Ÿ“Š Configuration summary
  • ๐ŸŒ Allowed IPs and bypass keys
  • ๐Ÿ” Real-time bypass detection
  • ๐Ÿšฆ Current access status
  • ๐Ÿ’ก Practical usage tips

Enhanced Bypass Detection

The status command now shows real-time bypass information:

๐Ÿ” Current Bypass Status:
   ๐Ÿ”‘ Config Secret available (add ?maintenance_secret=your-key to URL)
   โœ… Data Secret (via URL parameter) 
   ๐ŸŒ IP Address bypass configured (current IP 192.168.1.200 not in allowed list)
   ๐Ÿช Cookie bypass configured (cookie not set or invalid)

๐Ÿšฆ Access Status from CLI:
   โœ… Access ALLOWED: CLI access (always allowed)

๐Ÿ’ก Tips:
   โ€ข Add your IP: php spark mm:down --allow=192.168.1.200
   โ€ข Use secret: php spark mm:down --secret=your-key  
   โ€ข Access URL: https://yoursite.com?maintenance_secret=your-key

Key Features:

  • โœ… Active bypass detection: Shows which bypass methods are currently working
  • ๐Ÿ” Real-time status: Indicates if current user would have access
  • ๐Ÿ’ก Practical guidance: Provides specific commands to enable access
  • ๐ŸŽฏ Priority indication: Shows bypass method priority order
  • ๐Ÿ“ฑ Current IP display: Shows your current IP for whitelist setup

Deactivate Maintenance Mode

php spark mm:up

Migrate Storage Method

Switch between file and cache storage without losing configuration:

# Migrate from files to cache
php spark mm:migrate --to=cache

# Migrate from cache to files  
php spark mm:migrate --to=file

๐Ÿ” Bypass Detection & Monitoring

Real-time Status Checking

The enhanced mm:status command provides comprehensive bypass detection:

php spark mm:status

What it shows:

  • ๐ŸŸข Active bypass methods: Currently working bypass options
  • ๐Ÿ”ด Inactive bypass methods: Configured but not currently active
  • ๐ŸŽฏ Current access status: Whether you would have access right now
  • ๐Ÿ’ก Actionable tips: Specific commands to enable access
  • ๐Ÿ“Š Configuration overview: All bypass methods configured

Bypass Method Priority

The system checks bypass methods in this priority order:

  1. ๐Ÿฅ‡ Config Secret (app/Config/Maintenance.php)
  2. ๐Ÿฅˆ Data Secret (set when activating maintenance)
  3. ๐Ÿฅ‰ IP Address (IP whitelist)
  4. ๐Ÿ… Cookie (automatically generated)

Practical Examples

Scenario 1: Developer wants access

# Check current status
php spark mm:status

# Example output shows:
# ๐ŸŒ IP Address bypass configured (current IP 192.168.1.200 not in allowed list)
# ๐Ÿ’ก Add your IP: php spark mm:down --allow=192.168.1.200

# Add your IP to allowed list
php spark mm:down --allow=192.168.1.200

Scenario 2: Share access via secret URL

# Check secret information
php spark mm:status

# Example output shows:
# ๐Ÿ”‘ Secret Bypass Information:
# URL: https://yoursite.com?maintenance_secret=abc123

# Share this URL with authorized users

Scenario 3: Troubleshooting access issues

# Check why access is blocked
php spark mm:status

# Example output shows:
# โŒ Access BLOCKED: No valid bypass method
# ๐Ÿ’ก Tips:
#   โ€ข Add your IP: php spark mm:down --allow=YOUR_IP
#   โ€ข Use secret: php spark mm:down --secret=your-key

๐Ÿš€ Advanced Usage

1. Multiple Bypass Methods

IP-based Bypass:

// Allow specific IPs to bypass maintenance
$config->allowedIps = ['192.168.1.100', '203.0.113.0'];

Secret URL Bypass:

https://yoursite.com/any-page?maintenance_secret=your-secret-key

Cookie-based Bypass:

// Set cookie programmatically
setcookie('maintenance_bypass', 'your-secret-key', time() + 3600);

2. Custom Error Pages

Override the default maintenance page by creating:

app/Views/errors/html/error_503.php

The modern template includes:

  • ๐ŸŽจ Responsive design with CSS variables
  • ๐Ÿ”„ Auto-refresh functionality
  • ๐ŸŒ™ Dark mode support
  • โ™ฟ Accessibility features
  • ๐Ÿ“ฑ Mobile optimization

3. Programmatic Control

use Daycry\MaintenanceMode\Libraries\MaintenanceStorage;

$storage = new MaintenanceStorage();

// Check if maintenance is active
if ($storage->isActive()) {
    // Get maintenance data
    $data = $storage->getData();
    echo "Message: " . $data['message'];
}

// Activate programmatically
$storage->save([
    'message' => 'Custom maintenance message',
    'allowedIps' => ['192.168.1.100'],
    'time' => time(),
    'secret' => 'custom-secret'
]);

// Deactivate
$storage->remove();

4. Event Handling

// In your BaseController or specific controllers
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
    parent::initController($request, $response, $logger);
    
    // Add custom logic before maintenance check
    Events::on('pre_maintenance_check', function () {
        // Your custom logic here
    });
}

๐Ÿ“Š Performance Comparison

Storage Method Average Response Time Memory Usage Scalability
Cache (Redis) ~0.5ms Low โญโญโญโญโญ
Cache (Memcached) ~0.8ms Low โญโญโญโญโญ
Cache (File) ~2ms Medium โญโญโญ
File Storage ~5ms Medium โญโญ

Recommendation: Use Redis cache for production environments with high traffic.

๐Ÿ”ง Configuration Reference

Complete configuration options in app/Config/Maintenance.php:

<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class Maintenance extends BaseConfig
{
    // Storage Configuration
    public bool $useCache = true;                // Use cache vs files
    public string $cacheKey = 'maintenance_mode'; // Cache key name
    public int $cacheTTL = 86400;               // Cache TTL (24 hours)
    
    // File Storage
    public string $driver = 'file';             // Storage driver
    public string $filePath = WRITEPATH . 'maintenance/maintenance.json';
    
    // UI & Messages
    public string $defaultMessage = 'We are currently performing maintenance. Please try again later.';
    public int $httpCode = 503;                 // HTTP status code
    public int $autoRefreshSeconds = 30;        // Auto-refresh interval
    
    // Security & Access
    public array $allowedIps = [];              // IP whitelist
    public bool $allowSecretBypass = true;      // Enable secret bypass
    public string $secretBypassKey = '';        // Default secret key
    public string $bypassCookieName = 'maintenance_bypass';
    
    // Logging & Monitoring
    public bool $enableLogging = true;          // Log maintenance events
    public string $logLevel = 'info';           // Log level
    
    // Advanced Features
    public bool $showRetryAfter = true;         // Show Retry-After header
    public int $retryAfter = 3600;             // Retry-After value (1 hour)
}

๐Ÿšฆ Filter Integration

Add the maintenance filter to your routes:

// app/Config/Routes.php

$routes->group('/', ['filter' => 'maintenance'], static function ($routes) {
    $routes->get('/', 'Home::index');
    $routes->get('about', 'Pages::about');
    // Add other routes that should be checked
});

// Or apply globally in app/Config/Filters.php
public array $globals = [
    'before' => [
        'maintenance' => ['except' => ['admin/*', 'api/*']]
    ]
];

๐Ÿงช Testing

Run the test suite:

# Run all tests
composer test

# Run with coverage
composer test:coverage

# Run specific test
./vendor/bin/phpunit tests/Maintenance/CommandsTest.php

๐Ÿ” Troubleshooting

Common Issues

1. Cache not working:

# Check cache configuration
php spark cache:info

# Clear cache
php spark cache:clear

# Test cache connection
php spark mm:status

2. IP bypass not working:

# Check your real IP
php spark mm:down --allow=$(curl -s ifconfig.me)

# Or check current IP in logs
tail -f writable/logs/log-*.php | grep maintenance

3. Migration issues:

# Force migration with cleanup
php spark mm:migrate --to=cache --force

# Check file permissions
ls -la writable/maintenance/

Debug Mode

Enable debug logging:

// app/Config/Maintenance.php
public string $logLevel = 'debug';
public bool $enableLogging = true;

๐Ÿค Contributing

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/amazing-feature
  3. Run tests: composer test
  4. Commit your changes: git commit -m 'Add amazing feature'
  5. Push to the branch: git push origin feature/amazing-feature
  6. Open a Pull Request

๐Ÿ“ Changelog

v2.0.0 (Latest)

  • โœจ New: Cache-based storage system with 10x performance improvement
  • โœจ New: Modern responsive maintenance page with dark mode
  • โœจ New: Migration command for seamless storage switching
  • โœจ New: Enhanced CLI commands with validation and better UX
  • โœจ New: Comprehensive logging and monitoring
  • ๐Ÿ”ง Enhanced: Expanded configuration with 12+ new options
  • ๐Ÿ”ง Enhanced: Better error handling and validation
  • ๐Ÿ› Fixed: Multiple IP handling and secret bypass improvements

v1.x.x

  • Basic file-based maintenance mode
  • Simple CLI commands
  • Basic IP filtering

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ’ก Support

Made with โค๏ธ for the CodeIgniter 4 community