> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokkoplugins.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Filtros (Filters)

> Puntos de extensión disponibles vía apply_filters para ajustar el comportamiento del plugin

# Filtros

Los filtros permiten **modificar valores** que el plugin usa internamente sin tocar su código. Se conectan con `add_filter()` y deben **devolver** el valor modificado.

<Info>
  Todos los filtros documentados aquí están verificados contra el código fuente (`apply_filters(...)`). Si un filtro no aparece en esta página, el plugin no lo dispara.
</Info>

## Chequeos de salud del servidor (health checks)

Antes de iniciar la sincronización, el plugin verifica memoria, carga (load average) y disco. Estos filtros ajustan los umbrales y permiten desactivar chequeos individuales.

### thi\_server\_health\_check\_enabled

Habilita o deshabilita por completo los chequeos de salud antes de sincronizar.

<CodeGroup>
  ```php Filtro theme={null}
  $enabled = apply_filters('thi_server_health_check_enabled', true);
  ```

  ```php Ejemplo theme={null}
  add_filter('thi_server_health_check_enabled', function($enabled) {
      // Deshabilitar solo en entorno local
      if (defined('WP_DEBUG') && WP_DEBUG) {
          return false;
      }
      return $enabled;
  });
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `true`                            |
| **Tipo de retorno**      | boolean                           |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_allow\_image\_sync\_when\_unhealthy

Permite continuar la sincronización de imágenes aun cuando los chequeos detectan presión de recursos.

<CodeGroup>
  ```php Filtro theme={null}
  $allow = apply_filters('thi_allow_image_sync_when_unhealthy', false, $health_result);
  ```

  ```php Ejemplo theme={null}
  add_filter('thi_allow_image_sync_when_unhealthy', function($allow, $health) {
      // Permitir si solo el disco está bajo (pero memoria y CPU están OK)
      if ($health['disk']['status'] === 'warning' && $health['memory']['status'] === 'ok') {
          return true;
      }
      return $allow;
  }, 10, 2);
  ```
</CodeGroup>

| Propiedad                | Valor                                                              |
| ------------------------ | ------------------------------------------------------------------ |
| **Valor predeterminado** | `false`                                                            |
| **Argumentos**           | `$allow` (bool), `$health_result` (array con detalles por sistema) |
| **Ubicación**            | `includes/ajax/ajax-handlers.php`                                  |

<Warning>
  Devolver `true` en servidores con recursos al límite puede causar timeouts o fallas OOM. Úsalo sólo cuando sepas que los umbrales por defecto son demasiado conservadores para tu entorno.
</Warning>

***

### thi\_server\_health\_check\_memory\_enabled

Habilita o deshabilita específicamente el chequeo de **memoria**.

<CodeGroup>
  ```php Filtro theme={null}
  $enabled = apply_filters('thi_server_health_check_memory_enabled', true);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `true`                            |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_memory\_warning\_threshold

Porcentaje de memoria a partir del cual el chequeo emite un **warning**.

<CodeGroup>
  ```php Filtro theme={null}
  $threshold = apply_filters('thi_memory_warning_threshold', 85.0);
  ```

  ```php Ejemplo theme={null}
  add_filter('thi_memory_warning_threshold', fn() => 75.0);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `85.0` (%)                        |
| **Tipo**                 | float                             |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_memory\_critical\_threshold

Porcentaje de memoria a partir del cual el chequeo bloquea la sincronización.

<CodeGroup>
  ```php Filtro theme={null}
  $threshold = apply_filters('thi_memory_critical_threshold', 95.0);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `95.0` (%)                        |
| **Tipo**                 | float                             |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_server\_health\_check\_load\_enabled

Habilita o deshabilita el chequeo de **load average**.

<CodeGroup>
  ```php Filtro theme={null}
  $enabled = apply_filters('thi_server_health_check_load_enabled', true);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `true`                            |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_load\_warning\_threshold\_normalized

Umbral de advertencia para el load average **normalizado por CPU** (load average / número de núcleos).

<CodeGroup>
  ```php Filtro theme={null}
  $threshold = apply_filters('thi_load_warning_threshold_normalized', 1.2);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `1.2`                             |
| **Tipo**                 | float                             |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_load\_critical\_threshold\_normalized

Umbral crítico para el load average normalizado por CPU.

<CodeGroup>
  ```php Filtro theme={null}
  $threshold = apply_filters('thi_load_critical_threshold_normalized', 2.0);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `2.0`                             |
| **Tipo**                 | float                             |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_server\_health\_check\_load\_hard\_fail

Indica si superar el umbral crítico de load debe **bloquear** la sincronización (hard fail) o solo advertir.

<CodeGroup>
  ```php Filtro theme={null}
  $hard_fail = apply_filters('thi_server_health_check_load_hard_fail', !$is_docker);
  ```
</CodeGroup>

| Propiedad                | Valor                                                                                         |
| ------------------------ | --------------------------------------------------------------------------------------------- |
| **Valor predeterminado** | `true` en hosts normales, `false` cuando se detecta Docker (donde el load puede ser engañoso) |
| **Ubicación**            | `includes/ajax/ajax-handlers.php`                                                             |

***

### thi\_server\_health\_check\_disk\_enabled

Habilita o deshabilita el chequeo de **espacio en disco**.

<CodeGroup>
  ```php Filtro theme={null}
  $enabled = apply_filters('thi_server_health_check_disk_enabled', true);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `true`                            |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_disk\_warning\_gb

GB libres a partir de los cuales el chequeo emite warning de disco.

<CodeGroup>
  ```php Filtro theme={null}
  $gb = apply_filters('thi_disk_warning_gb', 5.0);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `5.0` GB                          |
| **Tipo**                 | float                             |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

### thi\_disk\_critical\_gb

GB libres a partir de los cuales el chequeo falla con error crítico.

<CodeGroup>
  ```php Filtro theme={null}
  $gb = apply_filters('thi_disk_critical_gb', 1.0);
  ```
</CodeGroup>

| Propiedad                | Valor                             |
| ------------------------ | --------------------------------- |
| **Valor predeterminado** | `1.0` GB                          |
| **Tipo**                 | float                             |
| **Ubicación**            | `includes/ajax/ajax-handlers.php` |

***

## Notificaciones y reportes

### thi\_notifications\_enabled

Controla si el plugin envía notificaciones por email (alertas de error + reporte periódico).

<CodeGroup>
  ```php Filtro theme={null}
  $enabled = apply_filters('thi_notifications_enabled', $is_premium);
  ```

  ```php Ejemplo theme={null}
  // Fuerza-habilitar notificaciones aunque no seas premium (solo para staging)
  add_filter('thi_notifications_enabled', '__return_true');
  ```
</CodeGroup>

| Propiedad                | Valor                                                           |
| ------------------------ | --------------------------------------------------------------- |
| **Valor predeterminado** | `true` si el plan tiene premium code, `false` en caso contrario |
| **Ubicación**            | `includes/notifications/notification-functions.php`             |

<Note>
  En el plan Starter las notificaciones por email están deshabilitadas por defecto porque es una característica premium.
</Note>

***

### thi\_error\_alert\_throttle\_seconds

Tiempo mínimo (en segundos) entre dos correos de alerta de error consecutivos para evitar spam.

<CodeGroup>
  ```php Filtro theme={null}
  $seconds = apply_filters('thi_error_alert_throttle_seconds', 1800);
  ```

  ```php Ejemplo theme={null}
  // Throttle más agresivo: una alerta por hora como máximo
  add_filter('thi_error_alert_throttle_seconds', fn() => HOUR_IN_SECONDS);
  ```
</CodeGroup>

| Propiedad                | Valor                                              |
| ------------------------ | -------------------------------------------------- |
| **Valor predeterminado** | `1800` (30 minutos)                                |
| **Ubicación**            | `includes/notifications/class-thi-error-alert.php` |

***

### thi\_sync\_reports\_retention\_days

Días que se conservan los reportes de sincronización antes de ser purgados por el cron diario.

<CodeGroup>
  ```php Filtro theme={null}
  $days = apply_filters('thi_sync_reports_retention_days', 30);
  ```

  ```php Ejemplo theme={null}
  // Conservar 90 días de reportes
  add_filter('thi_sync_reports_retention_days', fn() => 90);
  ```
</CodeGroup>

| Propiedad                | Valor                                              |
| ------------------------ | -------------------------------------------------- |
| **Valor predeterminado** | `30` días                                          |
| **Ejecutado por**        | el evento WP-Cron `thi_daily_sync_reports_cleanup` |
| **Ubicación**            | `includes/sync/class-thi-sync-report-store.php`    |

***

## Buenas prácticas

<Tip>
  * **Devuelve siempre el valor** (modificado o no). Un filtro que no retorna dispara advertencias y rompe comportamiento.
  * Usa prioridades distintas a `10` si quieres garantizar que tu filtro se ejecute después del default del plugin (si cambia en el futuro).
  * No llames operaciones pesadas dentro del callback de un filtro: estos se evalúan en cada request relevante.
</Tip>

```php theme={null}
// ✅ Correcto
add_filter('thi_memory_warning_threshold', function($threshold) {
    return 70.0; // retorna el nuevo valor
});

// ❌ Incorrecto (no retorna nada)
add_filter('thi_memory_warning_threshold', function($threshold) {
    $new = 70.0;
    // missing return
});
```
