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)
ParameterTypeDescription
$contextContextInterfacePlugin context (provides hook prefix)

create

Create a nonce token.

public function create(string $action): string
ParameterTypeDescription
$actionstringAction name (auto-prefixed)

Returns: string — Nonce token.

verify

Verify a nonce.

public function verify(string $nonce, string $action): bool|int
ParameterTypeDescription
$noncestringNonce to verify
$actionstringAction 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
ParameterTypeDefaultDescription
$actionstringAction name (auto-prefixed)
$namestring'_wpnonce'Hidden field name attribute
$referrerbooltrueInclude referer hidden field
$echobooltrueEcho 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
ParameterTypeDefaultDescription
$urlstringBase URL
$actionstringAction name (auto-prefixed)
$namestring'_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
ParameterTypeDefaultDescription
$actionstringAction name (auto-prefixed)
$namestring'_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
ParameterTypeDefaultDescription
$actionstringAction name (auto-prefixed)
$namestring'_wpnonce'Query argument name
$diebooltrueDie 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
ParameterTypeDescription
$capabilitystringWordPress capability name
...$argsmixedOptional 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
ParameterTypeDescription
$userIdintUser ID to check
$capabilitystringCapability name
...$argsmixedOptional 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
ParameterTypeDefaultDescription
$capabilitystring'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
ParameterTypeDefaultDescription
$capabilitystringRequired capability
$messagestring'You are not authorized...'Error message
$statusCodeint403HTTP 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
ParameterTypeDescription
$capabilitiesstring[]List of capabilities
...$argsmixedOptional arguments

canAll

Check if the current user has all of the given capabilities.

public function canAll(array $capabilities, mixed ...$args): bool
ParameterTypeDescription
$capabilitiesstring[]List of capabilities
...$argsmixedOptional 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
ParameterTypeDefaultDescription
$valuestringURL 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
ParameterTypeDefaultDescription
$valuesarrayInput array
$typestring'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
ParameterTypeDescription
$valuesarray<string, mixed>Input values
$typeMaparray<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
)
ParameterTypeDefaultDescription
$contextContextInterfacePlugin context
$maxAttemptsint60Maximum attempts before limiting
$decaySecondsint60Time window in seconds

hit

Record a hit for a key.

public function hit(string $key): int
ParameterTypeDescription
$keystringRate 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
ParameterTypeDescription
$keystringRate limit key
$callbackcallableExecuted if within limits
$onLimited?callableExecuted 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_FORHTTP_X_REAL_IPREMOTE_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
)
ParameterTypeDefaultDescription
$contextContextInterfacePlugin context
$nonceNonceNonce manager
$gateGateCapability gate
$allowedMimesarray<string, string>See belowExtension => MIME map
$maxSizeint5242880 (5 MB)Maximum file size in bytes

Default MIME types (when $allowedMimes is empty):

ExtensionsMIME Type
jpg|jpeg|jpeimage/jpeg
gifimage/gif
pngimage/png
webpimage/webp
pdfapplication/pdf
docapplication/msword
docxapplication/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
ParameterTypeDefaultDescription
$filearray$_FILES array entry (name, type, tmp_name, error, size)
$nonceActionstringNonce action name
$capabilitystring'upload_files'Required WordPress capability

Security checks performed (in order):

  1. Nonce verification
  2. Capability check
  3. PHP upload error check
  4. File size validation
  5. Extension/MIME validation via wp_check_filetype_and_ext()
  6. 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
ParameterTypeDescription
$mimesarray<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
ParameterTypeDescription
$bytesintMaximum 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
ParameterTypeDescription
$dirstringUpload directory path
$namestringOriginal filename (without extension)
$extstringFile 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 KeyResolves To
1Nonce::classnew Nonce($app->context())
2'nonce'Alias → Nonce::class
3Gate::classnew Gate()
4'gate'Alias → Gate::class
5Sanitizer::classnew Sanitizer()
6'sanitizer'Alias → Sanitizer::class
7RateLimiter::classnew RateLimiter($app->context())
8'rate-limiter'Alias → RateLimiter::class
9UploadSecurity::classnew 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')
ParameterTypeDefaultDescription
$gateGateAuthorization gate instance
$capabilitystring|string[]Required capability or capabilities
$modestring'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')
ParameterTypeDefaultDescription
$nonceNonceNonce manager instance
$actionstringNonce action name (auto-prefixed)
$fieldstring'_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
ContextFunction 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.