# Plugin Verification Scripts - Complete Implementation

## Summary

Enhanced the plugin verification scripts to detect critical issues including:
1. **Component/UI Overlaps** - CSS patterns that cause visual element overlap
2. **Early Function Calls** - Functions called before they are defined
3. **Undefined Functions** - Calls to functions that don't exist
4. **Undefined Arrays & Array Keys** - Array accesses on potentially uninitialized variables

## Changes Made

### 1. Enhanced `check-duplicate-classes.php` (PHP Static Analyzer)

**New Features Added:**

#### A. Undefined Function Detection
- Tracks all function calls in PHP files
- Compares against:
  - Internal PHP functions (extensive list)
  - WordPress/WooCommerce core functions
  - User-defined functions in the codebase
- Reports undefined function calls with file and line number
- Example: `UNDEFINED FUNCTION: 'my_custom_func' called at admin/page.php:42`

#### B. Early Function Call Detection
- Tracks function definitions with line numbers
- Detects when a function is called BEFORE it's defined in the same file
- Helps catch function ordering issues that can cause "Call to undefined function" errors
- Example: `EARLY FUNCTION CALL: 'process_data' called at line 15 but defined at line 85 in includes/helper.php`

#### C. Potential Undefined Array Detection
- Tracks array access patterns: `$array['key']` or `$array[$key]`
- Tracks variable assignments for type inference
- Warns when arrays are accessed without clear initialization
- Suggests using `isset()` or `!empty()` checks
- Example: `POTENTIAL UNDEFINED ARRAY: '$options' accessed as array at functions.php:23`

#### D. CSS Overlap Detection
- Scans all CSS files in the plugin
- Detects problematic CSS patterns:
  - Negative margins (`margin-top: -15px` - can pull elements into overlapping positions)
  - Absolute positioning without z-index (`position: absolute` without proper z-index)
  - Fixed positioning at z-index 0 (`position: fixed; z-index: 0` - overlaps other elements)
  - Elements anchored to both top/bottom or left/right
- Reports file, line number, and description of the issue
- Example: `POTENTIAL CSS OVERLAP in admin/css/admin.css:156`

### 2. Enhanced `validate-wordpress-plugin.sh` (Bash Validator)

**New Section 5.4: Runtime Error Detection**
- Calls the enhanced `check-duplicate-classes.php` analyzer
- Parses and reports:
  - Undefined functions (as ERROR - red)
  - Early function calls (as ERROR - red)
  - Potential undefined arrays (as WARNING - yellow)
  - CSS overlaps (as WARNING - yellow)
- Displays first 5 instances of each issue type

**New Section 9: CSS & UI Overlap Detection**
- Separate CSS analysis section
- Checks for:
  - Negative margins (common overlap cause)
  - Absolute positioning without z-index
  - Fixed positioning at z-index 0
- Shows first 5 instances and notes if more exist
- Reports as warnings (yellow)

**Updated Section Numbering**
- Changed from [1/8] to [1/10] to reflect new sections
- Updated all section headers to use consistent numbering

### 3. Updated `README.md`

**Enhanced Documentation:**
- Updated `check-duplicate-classes.php` documentation with:
  - All new detection capabilities
  - CSS overlap detection patterns
  - Example output showing all new features
  - Updated options and exit codes

## How It Works

### Detection Logic

#### Undefined Functions
```php
// Example code:
$result = some_undefined_function($data);

// Detection:
// 1. Parser tracks function calls: 'some_undefined_function' at line X
// 2. Checks if it's in internal PHP functions list: NO
// 3. Checks if it's in WP/WC functions list: NO
// 4. Checks if defined in codebase: NO
// 5. Reports: UNDEFINED FUNCTION at file:line X
```

#### Early Function Calls
```php
// Example problematic code:
$result = my_function();  // Line 10

function my_function() {  // Line 50
    return "data";
}

// Detection:
// 1. Parser sees 'my_function' defined at line 50
// 2. Parser sees 'my_function' called at line 10
// 3. Reports: EARLY FUNCTION CALL - function called before definition
```

#### CSS Overlaps
```css
/* Problematic CSS 1 - Negative Margin */
.button {
    margin-left: -15px;  /* Pulls element left into overlap */
}

/* Problematic CSS 2 - Absolute No Z-Index */
.modal {
    position: absolute;
    top: 50px;
    /* Missing z-index - may overlap other absolute elements */
}

/* Problematic CSS 3 - Fixed at Z-Index 0 */
.header {
    position: fixed;
    z-index: 0;  /* Overlaps page content at z-index 0 */
}

/* Detection for each case */
```

### False Positive Handling

The implementation includes conservative checks to minimize false positives:
- Skips keywords (`if`, `while`, `for`, etc.) in function detection
- Checks both short names and fully-qualified names with namespaces
- Only reports clear cases (call at least 2 lines before definition)
- Limits CSS overlap reports to 5 instances per file

## Usage Examples

### Check a WordPress Plugin
```bash
# Run full validation with all checks
./scripts/validate-wordpress-plugin.sh /path/to/plugin

# Run just the PHP analyzer with verbose output
php scripts/check-duplicate-classes.php /path/to/plugin --verbose

# Run in strict mode (may have more false positives)
php scripts/check-duplicate-classes.php /path/to/plugin --strict
```

### Example Output

```
========================================================
    STRICT WORDPRESS PLUGIN SECURITY & CODE AUDIT       
========================================================
Scanning: /path/to/plugin

[1/10] Checking for Dangerous/Forbidden Functions...
  ✓ No dangerous functions found

[2/10] Checking for SQL Injection Patterns...
  ✓ No SQL injection risks found

... (other checks)

[5.2/10] Checking for Duplicate Class/Function Declarations...
  ✓ No duplicate class declarations found

[5.4/10] Runtime Error Detection...
  ✗ UNDEFINED FUNCTIONS DETECTED
UNDEFINED FUNCTION: 'custom_helper_function' called at includes/helper.php:45
UNDEFINED FUNCTION: 'process_order_data' called at functions.php:112
  ✗ EARLY FUNCTION CALLS DETECTED
EARLY FUNCTION CALL: 'init_plugin' called at line 15 but defined at line 42 in plugin.php
  ⚠ POTENTIAL UNDEFINED ARRAYS
POTENTIAL UNDEFINED ARRAY: '$field_config' accessed as array at admin/class-admin.php:78
    This array may not be initialized before use.
    Consider using isset() or !empty() check before access.
  ⚠ POTENTIAL CSS OVERLAPS
POTENTIAL CSS OVERLAP in public/css/admin.css:156
    Reason: Negative margin (may cause overlap)
    Context: margin-left: -10px; position: relative;

[9/10] Checking CSS & UI for Overlap Issues...
  ⚠ CSS ISSUE in public/css/admin.css:156
    Negative margins detected (may cause overlap)
    margin-left: -10px; position: relative;
  ✓ No absolute positioning issues detected
  ✓ No fixed positioning issues detected

================================================================================
    AUDIT RESULTS                                       
================================================================================
FAIL: 2 Critical Security/Stability Issues Found.
(Plus 4 warnings requiring review)
```

## Benefits

1. **Prevents Runtime Errors** - Catches issues before deployment
2. **Improves UI Quality** - Detects CSS overlap patterns that cause visual bugs
3. **Better Code Quality** - Enforces proper function ordering and initialization
4. **Maintainability** - Helps developers understand code dependencies
5. **Early Detection** - Catches issues in CI/CD before they reach production

## Limitations

The static analysis has some limitations:
- Cannot fully track scope (functions/methods in different contexts)
- May have false positives for dynamic function calls (`$func()`)
- CSS overlap detection is pattern-based (may miss complex overlap scenarios)
- Cannot verify external dependencies (functions from other plugins/libraries)
- Array key checks are conservative (suggests review rather than errors)

## Best Practices for Developers

1. **Define Functions Before Use**
   ```php
   // Good
   function helper() { return 'data'; }
   echo helper();

   // Bad
   echo helper();  // May fail if not autoloaded
   function helper() { return 'data'; }
   ```

2. **Initialize Arrays Before Access**
   ```php
   // Good
   $options = [];
   $options['key'] = 'value';

   // Or check first
   if (isset($options['key'])) {
       echo $options['key'];
   }

   // Bad
   echo $options['key'];  // Undefined array
   ```

3. **Avoid CSS Overlaps**
   ```css
   /* Good - use proper z-index */
   .modal {
       position: absolute;
       z-index: 1000;
       top: 50%;
       left: 50%;
       transform: translate(-50%, -50%);
   }

   /* Good - use flex/grid instead of negative margins */
   .container {
       display: flex;
       gap: 1rem;
   }

   /* Bad - negative margins cause overlap */
   .sidebar {
       margin-left: -15px;
   }
   ```

## CI/CD Integration

```yaml
# Example GitHub Actions workflow
- name: Validate Plugin
  run: |
    ./scripts/validate-wordpress-plugin.sh ./plugin-dir
  continue-on-error: false

- name: Check for Runtime Issues
  run: |
    php scripts/check-duplicate-classes.php ./plugin-dir --verbose
```

## Testing

To test the enhancements:

```bash
# Test on a real plugin
./scripts/validate-wordpress-plugin.sh /path/to/wordpress-plugin

# Test on a plugin with intentional issues
# Create a test plugin with:
# - Undefined function calls
# - Early function calls
# - Array access without initialization
# - CSS with negative margins
# Run validator and verify all issues are detected
```

## Files Modified

1. `/scripts/check-duplicate-classes.php` - Enhanced with 4 new detection types
2. `/scripts/validate-wordpress-plugin.sh` - Added 2 new sections (5.4 and 9)
3. `/scripts/README.md` - Updated documentation with new features

## Backward Compatibility

All changes are backward compatible:
- Existing checks remain unchanged
- New checks are additive only
- Exit codes maintain previous behavior
- Output format is consistent with existing style
- No breaking changes to script usage or parameters
