Libraries
The classes in core/lib/: mail, an HTTP client, encryption at rest, IP matching and Cloudflare access rules. Plain PHP, no packages.
What is there
A library belongs to no module. Its namespace is Zero\Lib\ and it loads like every other class — name it in a use line (Class Loading).
| Class | File | Does | Needs |
|---|---|---|---|
Zero\Lib\Mail\Mail |
core/lib/Mail/Mail.php |
Sends, or captures, every message | MAIL_FROM or PRIMARY_DOMAIN; the entity tables |
Zero\Lib\Http\Client |
core/lib/Http/Client.php |
Outbound HTTP over cURL | PHP's curl extension |
Zero\Lib\Crypto |
core/lib/Crypto.php |
AES-256-GCM encryption of a value | APP_ENCRYPTION_KEY; PHP's openssl extension |
Zero\Lib\Net\Cidr |
core/lib/Net/Cidr.php |
Matches an IP against an IP or CIDR range | Nothing |
Zero\Lib\Net\TrustedProxy |
core/lib/Net/TrustedProxy.php |
Says whether a peer is a Cloudflare edge | Nothing |
Zero\Lib\CloudFlare\CloudFlare |
core/lib/CloudFlare/CloudFlare.php |
Blocks, unblocks and lists IP access rules | app/config/cloudflare.ini |
Every message goes through Zero\Lib\Mail\Mail. A module never calls PHP's mail() itself.
use Zero\Lib\Mail\Mail; Mail::sendEmailTo($to, $subject, $message); // from the site's own address Mail::sendEmailTo($to, $subject, $message, null, $replyTo); // with a Reply-To Mail::sendEmailToAdmin($subject, $message); // to NOTIFY_EMAIL Mail::sender(); // the address mail is sent from
| Method | Returns |
|---|---|
sendEmailTo($to, $subject, $message, $from = null, $replyTo = null) |
bool — what mail() returned, or whether the capture file was written. $from and $replyTo default to sender(). |
sendEmailToAdmin($subject, $message) |
bool. When NOTIFY_EMAIL is not defined nothing is sent, a warning is logged and false comes back. |
sender(): string |
MAIL_FROM, or noreply@ + PRIMARY_DOMAIN when that is blank. |
What Mail does that a direct mail() call does not:
- HTML is detected. A message containing
<html,<body,<div,<por<tablegets thetext/html; charset=UTF-8content type. - Each message is recorded as a
Mail Sentevent (Zero\Entity\Event): recipient, subject, sender, Reply-To, length and whether the send succeeded. The body is not kept. The event is an entity row, soMailneeds the entity layer's database. - Capture. When
MAIL_CAPTURE_DIRnames a folder, the message is written there as an.emlfile and nothing is sent.
PRIMARY_DOMAIN=example.com [mail] ; Address mail is sent from; blank means noreply@ + PRIMARY_DOMAIN. MAIL_FROM= ; A folder (absolute, or relative to the site root). When set, mail is written ; there as .eml files and nothing is sent. Blank sends mail. MAIL_CAPTURE_DIR= NOTIFY_EMAIL="you@example.com"
Capture is for a test or staging copy that must not send mail. The files hold whatever the message held, sign-in links included, so the folder is created 0700 and each file 0600. Capturing is logged as a warning and the event records the message as captured, not sent. A folder that cannot be created or written fails closed: nothing is written, nothing is sent, and false comes back.
HTTP client
Zero\Lib\Http\Client wraps cURL. Setters return the client, so they chain; each verb returns a Zero\Lib\Http\Response.
use Zero\Lib\Http\Client;
use Zero\Core\Console;
$client = (new Client())
->setTimeout(3000) // milliseconds; the default is 5000
->setAuth('BEARER', ['token' => $token]);
$response = $client->get('https://api.example.com/items', ['page' => 2]);
if ($response->isSuccess()) { // 2xx
$items = $response->json(); // ?array
} else {
// statusCode is 0 and error holds cURL's message when the request never completed
Console::warn("items: HTTP {$response->statusCode} {$response->error}");
}
$client->post($url, ['name' => 'New']); // array is sent as a JSON body
$client->post($url, ['name' => 'New'], false); // sent as a form body
| Client method | Notes |
|---|---|
get(string $url, array $params = []) |
$params are appended as a query string. |
post(), put(), patch(), delete()(string $url, $data = null, bool $json = true) |
With $json true the body is json_encode($data) (a string is sent as given) and Content-Type: application/json is set. With false it is a URL-encoded form. |
setTimeout(int $ms) |
Whole-request timeout. The connect timeout is the smaller of this and 2000 ms. |
setHeader(string $key, string $value), setHeaders(array $headers) |
Headers stay on the client for every later request, the Content-Type a body set included. |
setAuth(string $type, array $credentials) |
BEARER (token), BASIC (username, password), API_KEY (header_name, key), OAUTH2 (access_token). |
setOption(int $option, $value) |
Any cURL option. Applied last, so it overrides the client's own. |
reset() |
Clears headers and options and restores the default timeout. |
| Response member | Meaning |
|---|---|
$statusCode, $headers, $body | Read-only. $statusCode is 0 and $body is null on a cURL failure. |
$responseTime | Milliseconds, as a float. |
$error, $success | cURL's error message or null; true for a 2xx. |
json(): ?array | The decoded body, or null when it is empty or not JSON. |
text(): ?string | The body as received. |
isSuccess(), isClientError(), isServerError() | 2xx, 4xx, 5xx. |
header(string $name): ?string | Case-insensitive lookup. |
toArray(): array | Everything above, for logging. |
The client throws nothing: a request that fails comes back as a Response to check.
ExternalRequest
Zero\Lib\Http\ExternalRequest::get($url) is an older one-call GET. It follows redirects, waits up to 30 seconds and returns a two-element array, the status code and the body:
use Zero\Lib\Http\ExternalRequest;
[$status, $body] = ExternalRequest::get('https://example.com/feed.json');
Use Client for anything that needs a header, a body, a timeout or a result object.
Crypto
Zero\Lib\Crypto is authenticated encryption at rest: AES-256-GCM. The IV and the GCM tag travel inside the returned string, so one column stores it and no companion column is needed.
use Zero\Lib\Crypto; $stored = Crypto::encrypt($refreshToken); // base64 string, different every call $plain = Crypto::decrypt($stored); // ?string — null when it is not ours or was altered Crypto::isEncrypted($value); // bool, best effort: does this look like an envelope?
| Method | Behaviour |
|---|---|
encrypt(string $plaintext): string |
A fresh 12-byte random IV per call. Returns base64(version . iv . tag . ciphertext). |
decrypt(string $blob): ?string |
null for anything that is not valid base64, is too short, carries another version byte, or fails the tag check. |
isEncrypted(string $s): bool |
Checks shape only (base64, length, version byte). It does not decrypt. |
The key
The key is the constant APP_ENCRYPTION_KEY: 64 hex characters, which is 32 bytes. core/lib/Crypto.php expects it in app/config/crypto.ini; every .ini file in app/config/ becomes constants (Configuration), so no further wiring is needed.
php -r 'echo "APP_ENCRYPTION_KEY=", bin2hex(random_bytes(32)), "\n";' > app/config/crypto.ini
With the constant undefined, blank, or not exactly 64 hex characters, encrypt() and decrypt() throw a RuntimeException. Nothing is ever written unencrypted because a key was missing. Lose the key and the stored values cannot be recovered.
Net: Cidr and TrustedProxy
Zero\Lib\Net\Cidr compares addresses in binary form (inet_pton), so equivalent spellings compare equal and an IPv4 address never matches an IPv6 range. Malformed input matches nothing.
use Zero\Lib\Net\Cidr;
Cidr::matches('10.1.2.3', '10.0.0.0/8'); // true — plain IP or CIDR entry
Cidr::matches('::1', '0:0:0:0:0:0:0:1'); // true — same address, two spellings
Cidr::matchesAny($ip, ['203.0.113.5', '2001:db8::/32']); // true when any entry matches
Cidr::sameIp($ip, $other); // exact address comparison
Cidr::inCidr($ip, '198.51.100.0/24'); // range only; false for an entry with no slash
Zero\Lib\Net\TrustedProxy holds Cloudflare's published edge ranges, compiled into the class as constants.
use Zero\Lib\Net\TrustedProxy; TrustedProxy::isCloudflare($_SERVER['REMOTE_ADDR']); // bool — is this peer a Cloudflare edge? TrustedProxy::ranges(); // string[] — every trusted range, IPv4 then IPv6
You rarely call it directly: Request::clientIp() uses it to decide whether a forwarding header is believed. Security & Logging explains that, and the script that reports when the compiled ranges have drifted from Cloudflare's.
CloudFlare
Zero\Lib\CloudFlare\CloudFlare manages account-level IP access rules through Cloudflare's API. Core uses it for one thing, banning the client of a probe request (Security & Logging).
use Zero\Lib\CloudFlare\CloudFlare;
CloudFlare::block('203.0.113.9', 'credential stuffing'); // bool
CloudFlare::unblock('203.0.113.9'); // bool — finds the rule, deletes it
$rules = CloudFlare::list(['mode' => 'block'], page: 1, perPage: 50);
// ['result' => [...], 'result_info' => [...]], or null on failure
It reads its credentials from app/config/cloudflare.ini each time it is called. All three keys are required:
CLOUDFLARE_API_KEY= CLOUDFLARE_EMAIL= CLOUDFLARE_ACCOUNT_ID=
With the file missing or a key blank, block() and unblock() return false and list() returns null; nothing throws. Every block and unblock, and every failure of one, is written to the ban log with Console::ban().
Your own
| Scope | Folder | Namespace |
|---|---|---|
| One module provides it, others use it | modules/{Name}/lib/ | Zero\Module\{Name}\Lib |
| The site, no one module | app/lib/ | Zero\App\Lib |
Both load by the rule on Class Loading. core/lib/ is the framework's; a site adds nothing there.