API Reference
Complete API reference for the wpzylos-security package.
Namespace: WPZylos\Framework\Security
Nonce
WordPress nonce wrapper with plugin-scoped action names. All action names are automatically prefixed via $context->hook().
Full class: WPZylos\Framework\Security\Nonce
Constructor
public function __construct(ContextInterface $context)
| Parameter | Type | Description |
|---|---|---|
$context | ContextInterface | Plugin context (provides hook prefix) |
create
Create a nonce token.
public function create(string $action): string
| Parameter | Type | Description |
|---|---|---|
$action | string | Action name (auto-prefixed) |
Returns: string — Nonce token.
verify
Verify a nonce.
public function verify(string $nonce, string $action): bool|int
| Parameter | Type | Description |
|---|---|---|
$nonce | string | Nonce to verify |
$action | string | Action name (auto-prefixed) |
Returns: false if invalid, 1 if generated < 12 hours ago, 2 if generated < 24 hours ago.
field
Create nonce hidden field HTML for forms.
public function field(
string $action,
string $name = '_wpnonce',
bool $referrer = true,
bool $echo = true
): string
| Parameter | Type | Default | Description |
|---|---|---|---|
$action | string | — | Action name (auto-prefixed) |
$name | string | '_wpnonce' | Hidden field name attribute |
$referrer | bool | true | Include referer hidden field |
$echo | bool | true | Echo the HTML output |
Returns: string — Hidden input HTML.
url
Append a nonce to a URL as a query parameter.
public function url(string $url, string $action, string $name = '_wpnonce'): string
| Parameter | Type | Default | Description |
|---|---|---|---|
$url | string | — | Base URL |
$action | string | — | Action name (auto-prefixed) |
$name | string | '_wpnonce' | Query parameter name |
Returns: string — URL with nonce appended.
checkAdminReferer
Check admin referer with nonce verification.
public function checkAdminReferer(string $action, string $name = '_wpnonce'): bool|int
| Parameter | Type | Default | Description |
|---|---|---|---|
$action | string | — | Action name (auto-prefixed) |
$name | string | '_wpnonce' | Query argument name |
Returns: false if failed, 1 or 2 if valid.
checkAjaxReferer
Check AJAX referer with nonce verification.
public function checkAjaxReferer(
string $action,
string $name = '_wpnonce',
bool $die = true
): bool|int
| Parameter | Type | Default | Description |
|---|---|---|---|
$action | string | — | Action name (auto-prefixed) |
$name | string | '_wpnonce' | Query argument name |
$die | bool | true | Die on verification failure |
Returns: bool|int
Gate
Capability-based authorization gate. Provides a fluent API for checking WordPress user capabilities.
Full class: WPZylos\Framework\Security\Gate
Constructor
No constructor parameters.
$gate = new Gate();
can
Check if the current user has a capability.
public function can(string $capability, mixed ...$args): bool
| Parameter | Type | Description |
|---|---|---|
$capability | string | WordPress capability name |
...$args | mixed | Optional arguments (e.g., post ID) |
Returns: bool
cannot
Check if the current user lacks a capability. Inverse of can().
public function cannot(string $capability, mixed ...$args): bool
userCan
Check if a specific user has a capability.
public function userCan(int $userId, string $capability, mixed ...$args): bool
| Parameter | Type | Description |
|---|---|---|
$userId | int | User ID to check |
$capability | string | Capability name |
...$args | mixed | Optional arguments |
Returns: bool
isAdmin
Check if the current user is an administrator (manage_options).
public function isAdmin(): bool
canManagePlugin
Check if the current user can manage the plugin.
public function canManagePlugin(string $capability = 'manage_options'): bool
| Parameter | Type | Default | Description |
|---|---|---|---|
$capability | string | 'manage_options' | Override capability |
canEdit
Check if the current user can edit posts (edit_posts).
public function canEdit(): bool
canPublish
Check if the current user can publish posts (publish_posts).
public function canPublish(): bool
canDelete
Check if the current user can delete posts (delete_posts).
public function canDelete(): bool
authorize
Abort with wp_die() if the current user lacks a capability.
public function authorize(
string $capability,
string $message = 'You are not authorized to perform this action.',
int $statusCode = 403
): void
| Parameter | Type | Default | Description |
|---|---|---|---|
$capability | string | — | Required capability |
$message | string | 'You are not authorized...' | Error message |
$statusCode | int | 403 | HTTP status code |
isLoggedIn
Check if the current user is logged in.
public function isLoggedIn(): bool
isGuest
Check if the current user is not logged in.
public function isGuest(): bool
userId
Get the current user ID.
public function userId(): int
Returns: int — User ID, or 0 if not logged in.
canAny
Check if the current user has any of the given capabilities.
public function canAny(array $capabilities, mixed ...$args): bool
| Parameter | Type | Description |
|---|---|---|
$capabilities | string[] | List of capabilities |
...$args | mixed | Optional arguments |
canAll
Check if the current user has all of the given capabilities.
public function canAll(array $capabilities, mixed ...$args): bool
| Parameter | Type | Description |
|---|---|---|
$capabilities | string[] | List of capabilities |
...$args | mixed | Optional arguments |
Sanitizer
Input sanitizer using WordPress sanitization functions.
Full class: WPZylos\Framework\Security\Sanitizer
Constructor
No constructor parameters.
text
Sanitize a single-line text field.
public function text(string $value): string
Wraps sanitize_text_field().
textarea
Sanitize multiline text.
public function textarea(string $value): string
Wraps sanitize_textarea_field().
html
Sanitize HTML content (post-level allowed tags).
public function html(string $value): string
Wraps wp_kses_post().
email
Sanitize an email address.
public function email(string $value): string
Wraps sanitize_email(). Returns empty string if invalid.
url
Sanitize a URL.
public function url(string $value, ?array $protocols = null): string
| Parameter | Type | Default | Description |
|---|---|---|---|
$value | string | — | URL to sanitize |
$protocols | ?array | ['http', 'https'] | Allowed protocols |
Wraps esc_url_raw().
int
Sanitize to integer.
public function int(mixed $value): int
absint
Sanitize to absolute (positive) integer.
public function absint(mixed $value): int
Wraps WordPress absint().
float
Sanitize to float.
public function float(mixed $value): float
bool
Sanitize to boolean.
public function bool(mixed $value): bool
Uses filter_var() with FILTER_VALIDATE_BOOLEAN.
slug
Sanitize a slug.
public function slug(string $value): string
Wraps sanitize_title().
key
Sanitize a key (lowercase alphanumeric, dashes, underscores).
public function key(string $value): string
Wraps sanitize_key().
filename
Sanitize a file name.
public function filename(string $value): string
Wraps sanitize_file_name().
htmlClass
Sanitize a CSS class name.
public function htmlClass(string $value): string
Wraps sanitize_html_class().
array
Sanitize each element of an array using a specified type.
public function array(array $values, string $type = 'text'): array
| Parameter | Type | Default | Description |
|---|---|---|---|
$values | array | — | Input array |
$type | string | 'text' | Sanitizer type to apply |
sanitize
Sanitize a single value by type name.
public function sanitize(mixed $value, string $type): mixed
Supported types: text, textarea, html, email, url, int, integer, absint, float, bool, boolean, slug, key, filename, htmlClass. Unknown types default to text.
Returns null if input is null.
sanitizeMany
Sanitize multiple values using a field-to-type map.
public function sanitizeMany(array $values, array $typeMap): array
| Parameter | Type | Description |
|---|---|---|
$values | array<string, mixed> | Input values |
$typeMap | array<string, string> | Field name => sanitizer type |
Returns: array<string, mixed> — Only fields present in both $values and $typeMap are included.
RateLimiter
Rate limiter using WordPress transients. Provides request throttling for AJAX, REST, and form submissions. Compatible with object cache.
Full class: WPZylos\Framework\Security\RateLimiter
Constructor
public function __construct(
ContextInterface $context,
int $maxAttempts = 60,
int $decaySeconds = 60
)
| Parameter | Type | Default | Description |
|---|---|---|---|
$context | ContextInterface | — | Plugin context |
$maxAttempts | int | 60 | Maximum attempts before limiting |
$decaySeconds | int | 60 | Time window in seconds |
hit
Record a hit for a key.
public function hit(string $key): int
| Parameter | Type | Description |
|---|---|---|
$key | string | Rate limit key (e.g., user ID, IP) |
Returns: int — Current hit count after this hit.
tooManyAttempts
Check if the rate limit has been exceeded.
public function tooManyAttempts(string $key): bool
Returns: true if hits >= maxAttempts.
remaining
Get the number of remaining attempts.
public function remaining(string $key): int
Returns: int — Remaining attempts (minimum 0).
availableIn
Get seconds until the rate limit resets.
public function availableIn(string $key): int
Returns: int — Seconds until reset. 0 if not currently limited.
clear
Clear the rate limit for a key.
public function clear(string $key): bool
Returns: true if cleared successfully.
attempt
Attempt an action with automatic rate limiting.
public function attempt(
string $key,
callable $callback,
?callable $onLimited = null
): mixed
| Parameter | Type | Description |
|---|---|---|
$key | string | Rate limit key |
$callback | callable | Executed if within limits |
$onLimited | ?callable | Executed if rate limited, receives seconds to wait |
Returns: Result of $callback, result of $onLimited, or null if limited with no handler.
forUser
Generate a rate limit key scoped to the current user.
public function forUser(string $action): string
Falls back to forIp() if the user is not logged in.
Returns: string — Key in format user_{id}_{action} or IP-based key.
forIp
Generate a rate limit key scoped to the current IP address.
public function forIp(string $action): string
IP detection priority: HTTP_CF_CONNECTING_IP (Cloudflare) → HTTP_X_FORWARDED_FOR → HTTP_X_REAL_IP → REMOTE_ADDR. Falls back to 127.0.0.1.
Returns: string — Key in format ip_{md5(ip)}_{action}.
UploadSecurity
Secure file upload handler. Wraps WordPress upload functions with nonce verification, capability checks, MIME validation, and file size limits.
Full class: WPZylos\Framework\Security\UploadSecurity
Constructor
public function __construct(
ContextInterface $context,
Nonce $nonce,
Gate $gate,
array $allowedMimes = [],
int $maxSize = 5242880
)
| Parameter | Type | Default | Description |
|---|---|---|---|
$context | ContextInterface | — | Plugin context |
$nonce | Nonce | — | Nonce manager |
$gate | Gate | — | Capability gate |
$allowedMimes | array<string, string> | See below | Extension => MIME map |
$maxSize | int | 5242880 (5 MB) | Maximum file size in bytes |
Default MIME types (when $allowedMimes is empty):
| Extensions | MIME Type |
|---|---|
jpg|jpeg|jpe | image/jpeg |
gif | image/gif |
png | image/png |
webp | image/webp |
pdf | application/pdf |
doc | application/msword |
docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
handle
Handle a single file upload securely.
public function handle(
array $file,
string $nonceAction,
string $capability = 'upload_files'
): array|\WP_Error
| Parameter | Type | Default | Description |
|---|---|---|---|
$file | array | — | $_FILES array entry (name, type, tmp_name, error, size) |
$nonceAction | string | — | Nonce action name |
$capability | string | 'upload_files' | Required WordPress capability |
Security checks performed (in order):
- Nonce verification
- Capability check
- PHP upload error check
- File size validation
- Extension/MIME validation via
wp_check_filetype_and_ext() - Real MIME verification via
finfo_file()(when available)
Returns: array{file: string, url: string, type: string} on success, \WP_Error on failure.
Possible WP_Error codes: nonce_failed, permission_denied, upload_error, file_too_large, invalid_type, mime_mismatch, upload_failed.
handleMultiple
Handle multiple file uploads.
public function handleMultiple(
array $files,
string $nonceAction,
string $capability = 'upload_files'
): array
Normalizes the $_FILES multi-upload array structure and calls handle() for each file.
Returns: array<int, array|\WP_Error> — Array of results, one per file.
allowMimes
Set allowed MIME types (fluent).
public function allowMimes(array $mimes): static
| Parameter | Type | Description |
|---|---|---|
$mimes | array<string, string> | Extension => MIME type map |
Returns: static — The same instance for chaining.
maxSize
Set maximum file size (fluent).
public function maxSize(int $bytes): static
| Parameter | Type | Description |
|---|---|---|
$bytes | int | Maximum size in bytes |
Returns: static — The same instance for chaining.
generateFilename
Generate a unique, sanitized filename.
public function generateFilename(string $dir, string $name, string $ext): string
| Parameter | Type | Description |
|---|---|---|
$dir | string | Upload directory path |
$name | string | Original filename (without extension) |
$ext | string | File extension (with dot) |
Uses sanitize_file_name() and wp_unique_filename().
SecurityServiceProvider
Registers all security services with the application container.
Full class: WPZylos\Framework\Security\SecurityServiceProvider
Extends: WPZylos\Framework\Core\ServiceProvider
register
public function register(ApplicationInterface $app): void
Registers 10 container bindings (5 class singletons + 5 string aliases):
| # | Binding Key | Resolves To |
|---|---|---|
| 1 | Nonce::class | new Nonce($app->context()) |
| 2 | 'nonce' | Alias → Nonce::class |
| 3 | Gate::class | new Gate() |
| 4 | 'gate' | Alias → Gate::class |
| 5 | Sanitizer::class | new Sanitizer() |
| 6 | 'sanitizer' | Alias → Sanitizer::class |
| 7 | RateLimiter::class | new RateLimiter($app->context()) |
| 8 | 'rate-limiter' | Alias → RateLimiter::class |
| 9 | UploadSecurity::class | new UploadSecurity() |
| 10 | 'upload-security' | Alias → UploadSecurity::class |
All bindings are singletons — the same instance is returned on every make() call.
Middleware
AuthMiddleware
Authentication middleware that checks user capabilities before allowing requests to proceed.
Full class: WPZylos\Framework\Security\Middleware\AuthMiddleware (final)
Constructor
public function __construct(Gate $gate, string|array $capability, string $mode = 'any')
| Parameter | Type | Default | Description |
|---|---|---|---|
$gate | Gate | — | Authorization gate instance |
$capability | string|string[] | — | Required capability or capabilities |
$mode | string | 'any' | 'any' or 'all' |
handle
public function handle(mixed $request, callable $next): mixed
Calls wp_die() with a 403 response if the user is not authorized.
any (static factory)
Create middleware requiring any of the given capabilities.
public static function any(Gate $gate, string|array $capability): self
all (static factory)
Create middleware requiring all of the given capabilities.
public static function all(Gate $gate, array $capabilities): self
NonceMiddleware
Nonce verification middleware for CSRF protection.
Full class: WPZylos\Framework\Security\Middleware\NonceMiddleware (final)
Constructor
public function __construct(Nonce $nonce, string $action, string $field = '_wpnonce')
| Parameter | Type | Default | Description |
|---|---|---|---|
$nonce | Nonce | — | Nonce manager instance |
$action | string | — | Nonce action name (auto-prefixed) |
$field | string | '_wpnonce' | Field name containing the nonce |
handle
public function handle(mixed $request, callable $next): mixed
Extracts the nonce from POST, GET, or a request object's input() method. Calls wp_die() with 403 on failure.
for (static factory)
public static function for(Nonce $nonce, string $action, string $field = '_wpnonce'): self
Helper Functions
Global escape helper functions for use in templates. All are wrapped in function_exists() guards to prevent conflicts.
wpzylos_e
Escape for HTML output.
function wpzylos_e(string $text): string
Wraps esc_html().
wpzylos_ea
Escape for HTML attribute output.
function wpzylos_ea(string $text): string
Wraps esc_attr().
wpzylos_eu
Escape URL for output.
function wpzylos_eu(string $url): string
Wraps esc_url().
wpzylos_ej
Escape for JavaScript.
function wpzylos_ej(string $text): string
Wraps esc_js().
wpzylos_kses
Filter HTML to allowed tags.
function wpzylos_kses(string $html, string $context = 'post'): string
| Context | Function Used |
|---|---|
'post' (default) | wp_kses_post() |
'data' | wp_kses_data() |
'strip' | wp_kses() with empty allowed tags |
wpzylos_e_json
Encode and escape JSON for safe HTML embedding.
function wpzylos_e_json(
mixed $data,
int $flags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
): string
Throws: \JsonException on encoding failure.