# MonsterInsights Licensing System - Technical Documentation

## Overview

The MonsterInsights licensing system manages plugin licenses, automatic updates, and plugin upgrading functionality. It's designed to work with both the Store API for license validation and the WordPress update system for seamless plugin updates.

## Directory Structure

```
includes/admin/licensing/
├── autoupdate.php              # Automatic update management
├── plugin-upgrader.php         # Core upgrader functionality
├── plugin-upgrader-legacy.php  # Legacy support for older WP versions
├── skin.php                    # Upgrader skin for WP 5.3+
└── skin-legacy.php             # Legacy upgrader skin
```

## Core Components

### 1. Auto-Update System (`autoupdate.php`)

The auto-update system manages automatic plugin updates based on license status and user preferences.

#### Key Functions

```php
function monsterinsights_automatic_updates($update, $item) {
    // Handles automatic update decisions based on:
    // - License status
    // - Update type (major/minor)
    // - User preferences
}
```

#### Update Types
1. **Major Updates**
   - Version changes like 7.0 to 8.0
   - Requires explicit opt-in
   - Only available for valid licenses

2. **Minor Updates**
   - Version changes like 7.0 to 7.1
   - Can be automatically installed
   - Available for all license types

### 2. Plugin Upgrader (`plugin-upgrader.php`)

Custom implementation of WordPress's Plugin_Upgrader class with MonsterInsights-specific functionality.

#### Key Features

1. **Secure Package Handling**
   ```php
   public function download_package($package, $check_signatures = false) {
       // Secure download implementation
       // Signature verification
       // Package validation
   }
   ```

2. **Installation Process**
   ```php
   public function install_package($args = array()) {
       // Source validation
       // Destination preparation
       // File copying
       // Cleanup
   }
   ```

3. **Maintenance Mode**
   ```php
   public function maintenance_mode($enable = false) {
       // Handles site state during updates
   }
   ```

### 3. License Integration

The licensing system integrates with both the Store API and WordPress:

1. **Store API Communication**
   - License validation
   - Update checking
   - Package download authorization

2. **WordPress Integration**
   - Hooks into WordPress update system
   - Manages update notifications
   - Handles multisite compatibility

## Implementation Details

### 1. Update Process Flow

```
1. WordPress Update Check
   ↓
2. License Validation (Store API)
   ↓
3. Update Package Verification
   ↓
4. Download & Signature Check
   ↓
5. Package Installation
   ↓
6. Cleanup & Activation
```

### 2. License Validation

```php
// Example license check implementation
function validate_license($license_key) {
    // 1. Check local cache
    // 2. Verify with Store API
    // 3. Cache results
    // 4. Return status
}
```

### 3. Update Settings Management

1. **User Preferences**
   - Enable/disable automatic updates
   - Major vs minor update preferences
   - Network-wide settings

2. **License Levels**
   - Basic
   - Plus
   - Pro
   - Elite

## Security Considerations

### 1. Package Verification
- Signature validation
- Checksum verification
- Source validation

### 2. License Protection
- Encrypted storage
- Secure API communication
- Token management

### 3. Update Security
- Secure download channels
- File permission management
- Backup procedures

## Error Handling

### 1. Common Scenarios

1. **License Issues**
   - Invalid license
   - Expired license
   - Network mismatch

2. **Update Failures**
   - Download errors
   - Verification failures
   - Installation errors

### 2. Error Response

```php
function handle_update_error($error) {
    // Log error
    // Notify user
    // Cleanup temporary files
    // Restore from backup if needed
}
```

## Integration Points

### 1. WordPress Core
- Update system hooks
- Plugin API integration
- Admin interface integration

### 2. Store API

The Store API is powered by Easy Digital Downloads (EDD) on monsterinsights.com:

- **Base URL**: `https://www.monsterinsights.com/`
- **License Endpoints**: `/wp-json/monsterinsights/v1/license/`
- **System**: Built on EDD Software Licensing addon
- **Features**:
  - License key generation and management
  - Automatic renewal processing
  - License validation and activation
  - Download access control
  - Update package delivery

#### EDD Integration Details

1. **License Validation Flow**
   ```
   WordPress Site                    Store (EDD)
        |                               |
        |-- License Key --------------->|
        |                               |
        |<- Validation Response --------|
        |                               |
        |-- Activation Request -------->|
        |                               |
        |<- Activation Status ----------|
   ```

2. **License Data Structure**
   ```php
   array(
       'license'        => 'valid', // License status
       'item_name'     => 'MonsterInsights Pro', // Product name
       'expires'       => '2024-12-31 23:59:59',
       'payment_id'    => '12345',
       'customer_name' => 'John Doe',
       'customer_email'=> 'john@example.com',
       'license_limit' => '5', // Number of allowed activations
       'site_count'    => '2', // Current number of activations
       'activations_left' => '3'
   )
   ```

3. **API Response Handling**
   - Success/error status codes
   - Detailed error messages
   - License status information
   - Site activation details

### 3. Relay API
- Usage tracking
- Performance monitoring
- Error reporting

## License Management

### 1. License Types and Features

1. **Basic License**
   - Single site usage
   - Core features
   - 1 year of updates/support

2. **Plus License**
   - Up to 5 sites
   - Additional features
   - 1 year of updates/support

3. **Pro License**
   - Up to 25 sites
   - All features
   - 1 year of updates/support

4. **Elite License**
   - Unlimited sites
   - All features + priority support
   - 1 year of updates/support

### 2. License States

1. **Valid States**
   - Active: License is valid and in use
   - Inactive: License is valid but not in use
   - Expired: License has expired but can be renewed

2. **Invalid States**
   - Disabled: License has been disabled
   - Revoked: License has been revoked
   - Missing: No license key provided

### 3. Site Activation Management

1. **Activation Process**
   ```php
   function activate_site($license_key, $site_url) {
       // 1. Validate license key
       // 2. Check activation limit
       // 3. Register site URL
       // 4. Store activation token
   }
   ```

2. **Deactivation Process**
   ```php
   function deactivate_site($license_key, $site_url) {
       // 1. Validate current activation
       // 2. Remove site registration
       // 3. Clear local activation data
       // 4. Update activation count
   }
   ```

## Development Guidelines

### 1. Adding New License Features

1. **Define Feature**
   ```php
   function register_license_feature($feature) {
       // Feature registration
       // Capability mapping
       // UI integration
   }
   ```

2. **Implement Checks**
   ```php
   function check_license_feature($feature) {
       // License validation
       // Feature availability
       // User capability check
   }
   ```

### 2. Updating License System

1. **Database Updates**
   - Version tracking
   - Schema changes
   - Data migration

2. **API Changes**
   - Endpoint updates
   - Response handling
   - Error management

## Troubleshooting

### Common Issues

1. **Update Failures**
   - Check file permissions
   - Verify WordPress version
   - Confirm license status

2. **License Problems**
   - Clear license cache
   - Verify site URL
   - Check API connectivity

3. **Integration Issues**
   - Review WordPress hooks
   - Check API responses
   - Verify configuration

## Additional Resources

- [WordPress Update API Documentation](https://developer.wordpress.org/plugins/updates/)
- [MonsterInsights API Documentation](https://github.com/awesomemotive/relay-api/wiki)
- [WordPress Plugin Guidelines](https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/) 