# Phlo Manual

Auto-generated reference of every built-in object and function in the Phlo runtime. Source: the engine's `resources/` plus its core `phlo.php`.

## Core

### %binary

One executable with the web server, PHP and the app in it, for a machine that has nothing installed

Advice: php www/app.php binary::make /path/to/frankenphp dist/myapp, on a machine with Go and with a release setting in data/app.json. You name the FrankenPHP: a static one stays as it is, and one linked against shared libraries brings them along with its loader and its PHP extensions. The result writes nothing next to itself but its data directory (--data), where creds.ini and your database belong; run ./myapp cli migration::run yourself after an update, and name what in data/ belongs to the app in prop %binary.data. Files in www/ go in the executable and are read-only there, so what people upload belongs in data.

- File: `resources/binary.phlo`
- `binary->ini:array` (line 10)
- `binary->data:array` (line 12)
- `binary::run(string $command):string` (line 14)
- `binary::libraries(string $file, string $lib):void` (line 21)
- `binary::extensions(string $frankenphp, string $stage):array` (line 28)
- `binary::settings(array $extensions):string` (line 46)
- `binary::entry:string` (line 65)
- `binary::make(string $frankenphp, string $output = 'dist/app'):string` (line 71)

### %cookies

Cookies data object

Advice: Reads and writes a cookie as a property. Every cookie it sets is httponly, samesite Lax and secure on an https request, so a script cannot read it and it does not travel to another site. That also means a value you need in the browser does not belong here. lifetimeDays sets how long they last; unsetting the property removes the cookie on the visitor's side too.

- File: `resources/cookies.phlo`
- `cookies->controller` (line 8)
- `cookies->lifetimeDays:int` (line 10)
- `cookies->objSet($key, $value, array $options = []):bool` (line 12)
- `cookies->__unset($key):void` (line 20)

### %feed

An Atom feed from a list of items, for a blog, a changelog or anything people follow in a reader

Advice: feed::atom($title, $items) writes the feed and feed::output() serves it. An item has title, link and updated (a timestamp or anything strtotime reads), and optionally summary, content (HTML), id and author. Keep id stable: a reader uses it to tell a new item from a changed one, and it defaults to the link, so a link that changes makes an item new again. Addresses have to be absolute, so write them with %req->base. Point to it from the head of a page with a link rel=alternate.

- File: `resources/feed.phlo`
- `feed::atom(string $title, iterable $items, ?string $link = null, ?string $subtitle = null):string` (line 8)
- `feed::output(string $title, iterable $items, ?string $link = null, ?string $subtitle = null)` (line 37)

### %lang

Language and translation resource

Advice: %lang prints the current app language through its view, so it drops straight into a link or an attribute. It is the translation layer behind nl() and en(): a phrase is hashed, looked up in langs/<lang>.ini, and, with an AI resource enabled and a key for the engine its model goes to, translated in the background when it is missing, so the first visitor reads the source text and the next one reads the translation; without either the file is yours to fill by hand, and the translator never overwrites a line you write there, while a translation a library ships in its langs/ replaces its line at every build. Editing a source phrase changes its hash and orphans the old translation. A view writes {nl: ...} and {en: ...}; source text in another language needs one line of its own in the app, function de($text, ...$args):string => %lang->translation('de', $text, ...$args). lang.address puts the language in the address, and locale writes numbers, money and dates the way a language does.

- File: `resources/lang.phlo`
- `function nl($text, ...$args):string` (line 9)
- `function en($text, ...$args):string` (line 10)
- `lang::asyncBatch($from, $to, $json):void` (line 12)
- `lang->view` (line 19)
- `lang->model:string` (line 21)
- `lang->instructions` (line 22)
- `lang::fileCache:array` (line 23)
- `lang->batchLines:int` (line 28)
- `lang->batchChars:int` (line 29)
- `lang->pending:array` (line 34)
- `lang->pendingChars:array` (line 35)
- `lang->collect($from, $to, array $missing):void` (line 40)
- `lang->flush($key):bool` (line 57)
- `lang->flushAll:void` (line 65)
- `lang->dispatch($from, $to, $json):bool` (line 71)
- `lang->translator:bool` (line 75)
- `lang->__destruct` (line 81)
- `lang->file($lang):string` (line 89)
- `lang->escape($value):string` (line 91)
- `lang->unescape($value):string` (line 92)
- `lang->lineValue($line, $eq):string` (line 94)
- `lang->readAll($file):array` (line 100)
- `lang->search($file, $hash):?string` (line 116)
- `lang->lookup($hash):?string` (line 162)
- `lang->save($lang, $pairs):void` (line 177)
- `lang->transContext:string` (line 192)
- `lang->browser:?string` (line 194)
- `lang->cookie:?string` (line 195)
- `lang->detect($text, $fallback = 'en'):string` (line 196)
- `lang->hash($from, $text):string` (line 206)
- `lang->translation($from, $text, ...$args):string` (line 207)
- `lang->translate($from, $to, $text):string` (line 226)
- `lang->translateBatch($from, $to, $texts):array` (line 235)

### %lang_address

The language in the address: /pricing, /fr/tarifs, and a link to any page in any language

Advice: Enabled, the address decides the page's language before any route matches. The first of %app->langs has no prefix, the others do, and a route is written once, with its source path. %app->slugs translates paths as source => [lang => slug]. link() writes the address of a page in any language; %req->route is the path the routes match, and %req->path stays what the browser asked for. An async request to an address without a prefix, such as an upload, keeps the language of the page it came from; a navigation, which phlo.js marks with X-Phlo-Navigate (app.navigate, an async link or GET form, location), speaks the language of its own address, and so does app.fetch, which sends neither header. List it before any resource that reads %req->route in its own beforeRoute, such as CSRF.

- File: `resources/lang.address.phlo`
- `lang_address::default:string` (line 9)
- `lang_address::beforeRoute` (line 12)
- `lang_address::prefix(string $part):bool` (line 19)
- `lang_address->slug(string $path, string $lang):?string` (line 21)
- `lang_address->source(string $path, string $lang):string` (line 25)
- `lang_address->link(string $path, ?string $lang = null):string` (line 36)

### %lastmod

Build-time stamp of when each page's source last changed, read at runtime for sitemap lastmod and for showing a date to the reader

Advice: Call lastmod::stamp from a build hook, so the dates are read where the sources are: a release node carries no .phlo sources. A date is the day of the last commit that changed the page's source, because a deploy or a CI checkout rewrites every mtime and every page would claim the day it was deployed; a source outside git or not committed yet gets none, and so does one whose last change lies beyond a shallow clone, so stamp in CI after a checkout with the full history (fetch-depth: 0). A source changed but not committed keeps the day of its last commit. The dates land in lastmod.json beside the generated PHP, so stamp the build you ship and let that file go with the release. Pages in %app->pages resolve by convention; declare prop %lastmod.sources as uri => file path for the rest. A page that resolves to nothing simply gets no lastmod, which is the right answer: a crawler that catches a site inventing them stops trusting the field domain-wide.

- File: `resources/lastmod.phlo`
- `lastmod::file($dir = null):string` (line 11)
- `lastmod->sources:array` (line 15)
- `lastmod::resolve($uri):?string` (line 18)
- `lastmod::day($file):?string` (line 27)
- `lastmod::uriOf($page):string` (line 35)
- `lastmod::stamp($dir = null):array` (line 37)
- `lastmod->map:array` (line 46)
- `lastmod->for($uri):?string` (line 48)

### %locale

Numbers, money and dates the way a language writes them

Advice: %locale->number(), money() and date() write in the page's language, or the one you pass, from a table in this file, so the result is the same on every server, with intl or without. A language outside the table writes as English; add one with a %locale.table modifier. money() writes euros in the language's own way and any other currency with its code in front.

- File: `resources/locale.phlo`
- `locale::table` (line 8)
- `locale->of(?string $lang = null):array` (line 18)
- `locale->number(int|float $value, int $decimals = 0, ?string $lang = null):string` (line 20)
- `locale->money(int|float $amount, string $currency = 'EUR', ?string $lang = null):string` (line 22)
- `locale->date(int|string $time, ?string $lang = null):string` (line 27)

### %mail

Send mail with text, HTML and attachments over sendmail, SMTP, Resend, Microsoft Graph or a log file, now or in the background

Advice: mail::send(to:, subject:, text: or html:) goes out through the transport in the [mail] section of creds.ini: sendmail by default (the local MTA), smtp (host, port, user, password; TLS on 465, STARTTLS when the server offers it), resend or graph, which go through the Resend and MicrosoftGraph connectors with the same fields, or log, which appends the whole message to data/mail.log so development sends nothing. Give from: per message or as from in [mail]. A view of your own is the template: html: $this->welcome. mail::later() takes the same arguments and sends in the background, which needs phlo.async; what a send could not deliver waits in data/mail/ for mail::retry() from a cron line. A message is claimed before it goes, so two runs never send it twice, and a claim older than the retry's hour belongs to a process that stopped and is sent again. Every header value is folded onto one line, so input cannot add a header of its own, and HTML without text gets a text part derived from it. It returns true when the transport took the message; an SMTP server that refuses throws with its answer.

- File: `resources/mail.phlo`
- `mail::send(string|array $to, string $subject, ?string $text = null, ?string $html = null, ?string $from = null, ?string $replyTo = null, array $cc = [], array $bcc = [], array $attachments = []):bool` (line 10)
- `mail::line($value):string` (line 32)
- `mail::address(string $value):string` (line 34)
- `mail::encode(string $value):string` (line 36)
- `mail::mime(?string $text, ?string $html, array $attachments):array` (line 41)
- `mail::plain(?string $html):string` (line 49)
- `mail::multipart(string $kind, array $parts):string` (line 51)
- `mail::smtp(array $config, string $from, array $recipients, string $message):bool` (line 58)
- `mail::resend(string $from, array $to, array $cc, array $bcc, ?string $replyTo, string $subject, ?string $text, ?string $html, array $attachments):bool` (line 98)
- `mail::graph(string $from, array $to, array $cc, array $bcc, ?string $replyTo, string $subject, ?string $text, ?string $html, array $attachments):bool` (line 105)
- `mail::later(...$args):bool` (line 123)
- `mail::sendWaiting(string $file):bool` (line 131)
- `mail::retry(int $olderThan = 3600):int` (line 150)

### %manifest

PWA web app manifest: declare the body, get the manifest.json route, head link and correct serving

Advice: Set the body from your app (prop %manifest.body => arr(...)) and put %manifest->head in your head view, because that head view is the only thing that links the manifest from a page. %manifest itself is the manifest document, the way %seo is the sitemap. Apps with multiple manifest variants keep their own routes and serve each body through manifest::output().

- File: `resources/manifest.phlo`
- `route GET manifest.json` (line 8)
- `manifest->body` (line 13)
- `manifest->maxAge:int` (line 14)
- `manifest::encode($body):string` (line 16)
- `manifest::output($body, $maxAge = null):void` (line 18)
- `manifest->view` (line 23)
- `manifest->head` (line 25)

### %manual

Self-writing manual at /manual: app description, source reflection and recent commits, plus an optional AI summary

Advice: Nothing to configure: include the resource and the page describes the app it runs in. It reads data/app.md, reflects the live source and reads git log, so it never goes stale. A product layer under paths.resources appears as its own section once it carries a layer.json in its repo root and a heading in its README; without that file a layer stays out of sight, which is how the framework itself stays out. The page is standalone (inline css, no javascript, no layout) and every render that changes the content is stored as data/manual.html without its session token, so the last state survives without the app. The markdown of data/app.md is rendered server-side, so the page needs no runtime and no namespace configuration. The AI summary is optional and keyed on data/app.md, so it costs nothing per visit; without the AI resource or a key the rest of the page still works. Put the route behind your auth gate and add manual to release.exclude, since a manual carrying the source does not belong on a customer server.

- File: `resources/manual.phlo`
- `manual::instruction` (line 9)
- `manual->translate:bool` (line 11)
- `manual->labels:array` (line 12)
- `manual->label($key):string` (line 31)
- `manual::appInfo:string` (line 33)
- `manual::commits(string $path, int $limit = 12):array` (line 35)
- `manual::repos:array` (line 58)
- `manual::commitList(int $limit = 20):array` (line 79)
- `manual::head:string` (line 91)
- `manual::routes:array` (line 96)
- `manual::routeGroups:array` (line 98)
- `manual::nodesByFile:array` (line 108)
- `manual::fileRow(string $file):obj` (line 129)
- `manual::sources:array` (line 141)
- `manual::dirLabel(string $dir):string` (line 170)
- `manual::cacheFile:string` (line 183)
- `manual::cached:?obj` (line 185)
- `manual::configured:bool` (line 192)
- `manual::appName:string` (line 197)
- `manual::model:string` (line 199)
- `manual::summary:obj` (line 204)
- `manual::pageFile:string` (line 227)
- `manual::store(string $body, string $page):bool` (line 229)
- `route both GET manual` (line 236)
- `manual->page` (line 247)
- `manual->summaryBlock` (line 260)
- `manual->summaryText($row)` (line 267)
- `manual->infoBlock` (line 273)
- `manual->infoText(string $html)` (line 279)
- `manual->filesBlock` (line 287)
- `manual->filesTable(array $groups)` (line 293)
- `manual->fileNodes($file)` (line 304)
- `manual->routesBlock` (line 328)
- `manual->routesTable(array $groups)` (line 334)
- `manual->routeRow(array $route)` (line 345)
- `manual->routeLine(string $method, string $path, string $summary)` (line 353)
- `manual->commitsBlock` (line 362)
- `manual->commitsList(array $commits)` (line 368)

### %markdown

Markdown to HTML on the server: headings, lists with tasks, quotes, tables, code, links and images

Advice: markdown::html($md) escapes the text before it adds any markup, so what a visitor wrote stays text and only the markdown becomes HTML; links and images go only to http, https, mailto, a path or an anchor, a bare http or https address becomes a link, and a fenced block names its language as a class (```php is code.language-php) for a highlighter. $top moves the headings down, so # in a comment can be an h3 under the page's own headings. It covers what people write in a note or a README, not every corner of CommonMark: no raw HTML passes. For markdown that arrives in the browser, use DOM/markdown.

- File: `resources/markdown.phlo`
- `markdown::html(string $md, int $top = 1):string` (line 9)
- `markdown::block(obj $block, int $top):string` (line 11)
- `markdown::blocks(string $md):array` (line 23)
- `markdown::marker(string $line):?obj` (line 109)
- `markdown::breaks(?obj $here, obj $marker):bool` (line 114)
- `markdown::para(array &$para, array &$blocks):void` (line 116)
- `markdown::cells(string $line):array` (line 122)
- `markdown::items(array $lines, int $indent):array` (line 124)
- `markdown::inline(string $text):string` (line 154)
- `markdown::format(string $text):string` (line 163)
- `markdown::autolink(string $html):string` (line 173)
- `markdown::autolinkOne(array $m):string` (line 175)

### %mcp

The app as an MCP server: the models you name become tools for an AI agent, under the rules they already have

Advice: Enabled, POST /mcp speaks the Model Context Protocol without sessions: 2026-07-28, and 2025-11-25 and earlier for older clients. Nothing is reachable until you name it: prop %mcp.models = ['order' => 'Orders of the shop'] gives list, get, create, change and delete tools, and %mcp.tools adds your own. A call goes through the model as a form in the CMS does: its scope, canView, canCreate, canChange, canDelete, objRefusal, field rules and hooks all apply, a field with change: false cannot be written, and a field with mcp: false is neither shown nor written. A client signs in with Authorization: Bearer, by default the token in the [mcp] section of creds; prop %mcp.canUse takes over for a token per user, and is the place to set who the request acts for, because a scope reads that. With security/CSRF enabled, add mcp to %CSRF.except: the token does that job here. It has no OAuth, so a client that insists on it needs a gateway in front.

- File: `resources/mcp.phlo`
- `mcp->models:array` (line 10)
- `mcp->tools:array` (line 12)
- `mcp->instructions` (line 13)
- `mcp->origins:array` (line 15)
- `mcp->canUse` (line 17)
- `mcp->bearer:string` (line 18)
- `mcp::beforeRoute` (line 21)
- `mcp->cors:bool` (line 29)
- `mcp::versions` (line 39)
- `mcp->modern` (line 40)
- `route POST mcp` (line 42)
- `route GET mcp` (line 68)
- `route DELETE mcp` (line 69)
- `mcp->notHere` (line 71)
- `mcp->reply($id, $result)` (line 77)
- `mcp->fail($id, int $code, string $message, ?int $status = null, ?array $data = null)` (line 78)
- `mcp->refused(string $method, array $params):?array` (line 82)
- `mcp->call($id, string $name, $arguments)` (line 98)
- `mcp->describe(string $name):array` (line 115)
- `mcp->catalog:array` (line 121)
- `mcp->may(string $model, string $rule, $record = null):bool` (line 142)
- `mcp->readable(string $model):array` (line 147)
- `mcp->writable(string $model, string $mode):array` (line 148)
- `mcp->schema(array $properties, array $required = []):array` (line 150)
- `mcp->schemas(array $fields):array` (line 151)
- `mcp->fieldSchema($field):array` (line 153)
- `mcp->listInput(string $model):array` (line 167)
- `mcp->row($record):array` (line 180)
- `mcp->find(string $model, array $args)` (line 188)
- `mcp->visible(string $model, $record)` (line 195)
- `mcp->written(string $model, $record):array` (line 198)
- `mcp->list(string $model, array $args):array` (line 200)
- `mcp->fill(string $model, $record, array $args, string $mode):void` (line 220)
- `mcp->invalid(string $model, array $values):void` (line 232)
- `mcp->create(string $model, array $args):array` (line 236)
- `mcp->change(string $model, array $args):array` (line 247)
- `mcp->delete(string $model, array $args):array` (line 258)
- `mcp->custom(array $tool, array $input, array $args):array` (line 266)

### %offline

An app that keeps working without a line: pages from a service worker, and posts in a queue that go out when the line is back

Advice: Put %offline in your head view and name what may wait: prop %offline.queue for the posts, prop %offline.shell and prop %offline.pages for what stays readable. A post can arrive twice, because an answer can get lost after the work is done, so wrap the work of such a route in offline::once(fn() => ...) and add the table from its comment to your migrations. Set prop %offline.owner on an app with accounts: another owner on the device empties the cached pages and leaves the queue waiting for the person it belongs to. A refusal (4xx or an error answer) moves a post aside for app.offline.retry or app.offline.drop, and a 5xx stops the queue until it works again, because the order matters. A cached page can be read by whoever holds the device, so list only what you can stand behind.

- File: `resources/offline.phlo`
- `offline->shell:array` (line 11)
- `offline->pages:array` (line 13)
- `offline->queue:array` (line 15)
- `offline->assets:array` (line 17)
- `offline->owner:string` (line 19)
- `offline->patience:int` (line 21)
- `offline->version:string` (line 23)
- `offline->view` (line 25)
- `route GET offline.json` (line 28)
- `offline::beforeRoute` (line 35)
- `offline->update:array` (line 43)
- `offline::once(callable $work, $db = null)` (line 50)
- `offline::at:int` (line 57)
- `offline::purge(int $olderThanSeconds = 2592000, $db = null):int` (line 59)

### %payload

POST, PUT, PATCH, QUERY and file-upload data object

Advice: Everything a request carried in its body, whichever way it was sent: JSON, a form, or multipart with files, including PUT and PATCH, which PHP itself leaves for you to unpack. An uploaded file arrives as a file resource rather than a temp path. It is raw input from outside, so read it, never trust it: what you save belongs behind field validation.

- File: `resources/payload.phlo`
- `payload->controller` (line 9)

### %qr

QR codes as SVG, without a library: for a link, a ticket, a label or the secret of an authenticator app

Advice: qr::svg($text) gives an inline SVG that scales with its container and takes the colour of the text around it. The level says how much damage a code survives: L, M (the default), Q or H; a higher level makes a larger code. A scanner needs the white margin around it, so leave $margin alone unless the page around it is already white. Text longer than a code can hold is an error, 2953 bytes at level L at the very most, and a phone camera gives up well before that.

- File: `resources/qr.phlo`
- `qr::eccPerBlock` (line 8)
- `qr::blocks` (line 14)
- `qr::svg(string $text, string $level = 'M', int $margin = 4, string $color = 'currentColor'):string` (line 21)
- `qr::matrix(string $text, string $level = 'M', ?int $mask = null):array` (line 38)
- `qr::capacity(int $version, string $level):int` (line 56)
- `qr::rawModules(int $version):int` (line 58)
- `qr::version(int $bytes, string $level):int` (line 69)
- `qr::data(string $text, int $version, string $level):array` (line 74)
- `qr::gfMultiply(int $x, int $y):int` (line 85)
- `qr::divisor(int $degree):array` (line 94)
- `qr::remainder(array $data, array $divisor):array` (line 108)
- `qr::codewords(array $data, int $version, string $level):array` (line 119)
- `qr::set(array &$modules, array &$function, int $x, int $y, bool $dark):void` (line 143)
- `qr::functionPatterns(array &$modules, array &$function, int $version, string $level):void` (line 148)
- `qr::alignment(int $version):array` (line 183)
- `qr::format(array &$modules, array &$function, int $mask, string $level):void` (line 192)
- `qr::place(array &$modules, array $function, array $data):void` (line 209)
- `qr::masked(array $modules, array $function, int $mask, string $level):array` (line 228)
- `qr::penalty(array $modules):int` (line 251)

### %seo

Multilingual SEO: sitemap.xml, robots.txt, hreflang + head meta (description/OG/Twitter/canonical)

Advice: Serves sitemap.xml and robots.txt itself and writes the head meta, so a page needs no SEO markup of its own. It reads from the app: pages for the sitemap, slugs for translated URLs, description, image and structuredData for the head, so filling those is the whole job. Give them as plain text: the resource escapes everything it writes. Every language of a page points at the others with hreflang, in the sitemap and, when lang reads the address, in the head; a lastmod resource, when there is one, dates the sitemap.

- File: `resources/seo.phlo`
- `route GET sitemap.xml` (line 9)
- `route GET robots.txt` (line 11)
- `seo->robots:string` (line 13)
- `seo->address(string $uri, string $lang):string` (line 23)
- `seo->defaultLang:string` (line 24)
- `seo->here:string` (line 26)
- `seo->alternates:bool` (line 27)
- `seo->uri($page):string` (line 32)
- `seo->field($page, $key):mixed` (line 34)
- `seo->lastmod($page):?string` (line 44)
- `seo->locale:string` (line 53)
- `seo->ogTitle:string` (line 59)
- `seo->ogDescr` (line 60)
- `seo->ogImageFile:string` (line 61)
- `seo->ogImage:string` (line 62)
- `seo->canonical:string` (line 63)
- `seo->ogType:string` (line 64)
- `seo->sitemapPages:array` (line 65)
- `seo->sitemapLangs:array` (line 66)
- `seo->siteName:string` (line 67)
- `seo->twitterCard:bool` (line 68)
- `seo->structuredData` (line 73)
- `seo->schemaData:?array` (line 75)
- `seo->noIndex:bool` (line 92)
- `seo->noLink:bool` (line 94)
- `seo->view` (line 96)
- `seo->page($page)` (line 104)
- `seo->xlink($lang, $uri)` (line 118)
- `seo->link($lang, $uri)` (line 119)
- `seo->head` (line 121)

### %session

Session data object

Advice: The session as an object: read a key, write a key, done. Call objRegenerateId() the moment someone logs in or changes role, so a token from before cannot be reused. Sessions are per browser, so anything that must survive a device belongs in a model. Each app keeps its sessions in a directory of its own, so another app's garbage collection cannot end them, and the cookie is httponly, Lax and secure on https. Override objOptions to steer it: a flow that returns to you with a cross-site POST, such as an OIDC provider posting its callback, needs cookie_samesite None with cookie_secure true, because a Lax cookie is not sent on that request and the state you stored is then unreadable.

- File: `resources/session.phlo`
- `session::objOptions:array` (line 8)
- `session::objDefaults:array` (line 13)
- `session->controller` (line 26)
- `session->__set($key, $value)` (line 29)
- `session->__unset($key)` (line 30)
- `session->__isset($key):bool` (line 31)
- `session->objRegenerateId($deleteOld = true):void` (line 33)

### %stream

Raw data stream beside the JSON command channel: stream() emits text or binary chunks under any content type, app.stream() consumes them via fetch dispatching on the response type

Advice: The channel beside the command stream, for what is not JSON: an image, a PDF, a zip, a file to download. Give it a content type, and a name when it should arrive as a download rather than be shown. On the page app.stream() picks its handling from the type that came back, so a caller does not have to know in advance what it is getting.

- File: `resources/stream.phlo`
- `function stream($data = null, string $type = 'application/octet-stream', ?string $name = null):void` (line 9)

### %tasks

Cron runner for %app->tasks. One cron entry per app triggers this every minute.

Advice: Everything scheduled in one place: %app->tasks holds what runs and when, and one cron entry per app triggers this every minute. A task takes a lock, so a run that lasts longer than its interval does not start over itself. Timing is per minute, so anything finer belongs in a daemon rather than here.

- File: `resources/tasks.phlo`
- `tasks::dir:string` (line 8)
- `tasks::run:void` (line 10)
- `tasks::saveRun($name, $do, $schedule, $return)` (line 25)
- `tasks::due($name, $task, $now):bool` (line 31)
- `tasks::fire($do)` (line 49)
- `tasks::lastRun($name):int` (line 59)
- `tasks::markRun($name, $ts):int|false` (line 64)
- `tasks::lock($name):bool` (line 66)
- `tasks::unlock($name):bool` (line 73)

### %useragent

User agent information

Advice: Reads operating system, browser and device out of the user agent string. That string is a claim, not a fact: it can be turned off, faked or shortened, so use it for statistics and never as a condition for something that matters. What a browser can do is worth asking the browser itself.

- File: `resources/useragent.phlo`
- `useragent->source:?string` (line 8)
- `useragent->os:string` (line 10)
- `useragent->osV:string` (line 26)
- `useragent->osFull:string` (line 37)
- `useragent->name:string` (line 47)
- `useragent->version:string` (line 64)
- `useragent->full:string` (line 75)
- `useragent->device:string` (line 84)

### %visitors

Visitor tracking via heartbeat

Advice: Counts visitors from the page itself with a heartbeat, so time on page and who is online now are real rather than guessed from page loads. It keeps a token instead of an IP for recognition, and without consent that token and the row id are a pseudonym of the day: keyed with a random key kept in data/visitors.key (0600, keep it out of git) and replaced the next day, so the counts per day hold and the cookie ties no two days together. It is a pseudonym, not anonymity: what a row holds besides, a hash of the user agent, the screen size, the page, the referrer and the time, can still link days. Without a writable data/ nothing is stored for a visitor without consent. Without a token cookie a visitor is a browser tab: eight letters from Math.random() in window.name; bots are filtered out before anything is written. A heartbeat every few seconds is a write per visitor, so watch the table on a busy site and prune it.

- File: `resources/visitors.phlo`
- `visitors::table:string` (line 10)
- `visitors::columns` (line 11)
- `visitors::history:array` (line 13)
- `visitors::online:int` (line 14)
- `visitors::lastHour:int` (line 15)
- `visitors::dayKey(?string $day = null):?string` (line 19)
- `visitors::heldKey(string $file, string $day):?string` (line 34)
- `visitors::visitorToken(bool $consent, string $who, ?string $key = null):string` (line 36)
- `visitors::isBot(?string $ua):bool` (line 38)
- `visitors::parseReferrer(string $url):string` (line 43)
- `route PUT heartbeat` (line 50)

### %websocket

Server-side WebSocket handler via phloWS

Advice: Enable this class only when websockets are configured for the host

- File: `resources/websocket.phlo`
- `websocket::connect($wsHost, $wsToken, $wsSocket):bool` (line 8)
- `websocket::auth($wsHost, $wsToken, $wsSocket):bool` (line 9)
- `websocket::receive($wsHost, $wsToken, $wsSocket, $data):bool` (line 10)
- `websocket::close($wsHost, $wsToken, $wsSocket):bool` (line 11)

### %WhatsApp

WhatsApp client for phloWA using whatsapp-web.js

Advice: Speaks to a phloWA instance, which holds the actual WhatsApp session, so this resource is a client and not a connection: without that service running, nothing is sent. A contact is a full WhatsApp address, and one ending in @g is a group, which number() and isGroup() sort out. It is an unofficial route, so treat volume and content with the care an account you cannot replace deserves.

- File: `resources/WhatsApp.phlo`
- `WhatsApp->__construct(public string $url, public string $secret)` (line 9)
- `WhatsApp::channel($channel):static` (line 11)
- `WhatsApp->number($contact):string` (line 13)
- `WhatsApp->isGroup($contact):bool` (line 14)
- `WhatsApp->status:obj` (line 16)
- `WhatsApp->health:obj` (line 17)
- `WhatsApp->qr:obj` (line 18)
- `WhatsApp->disconnect:obj` (line 19)
- `WhatsApp->read($chat):obj` (line 21)
- `WhatsApp->reaction($msg, $emoji):obj` (line 22)
- `WhatsApp->text($to, $text):obj` (line 24)
- `WhatsApp->image($to, file $file, $text = void):obj` (line 25)
- `WhatsApp->location($to, $lat, $lon, $text):obj` (line 26)
- `WhatsApp->document($to, file $file, $text = void):obj` (line 27)
- `WhatsApp->audio($to, file $file):obj` (line 29)
- `WhatsApp->voice($to, file $file):obj` (line 30)
- `WhatsApp->poll($to, $name, array $options, bool $multi = false):obj` (line 32)
- `WhatsApp->startTyping($to):obj` (line 34)
- `WhatsApp->stopTyping($to):obj` (line 35)
- `WhatsApp->request($action, ...$data):obj` (line 37)
- `WhatsApp::asObj(\stdClass $data):obj` (line 54)

### Functions

- `active(bool $cond, string $classList = void):string`: Build active class attribute for UI state
- `age(int $time):int`: Get age in seconds since a given timestamp
- `age_human(int $age):string`: Convert age in seconds to human readable text
- `apcu(string $key, callable $cb, int $duration = 3600, bool $log = true):mixed`: Cache callback results in APCu
- `apcu_forget(string $key):bool`: Cache callback results in APCu
- `apcu_key(string $key):string`: Cache callback results in APCu
- `await(...$jobs):array`: Run app targets in parallel, via the daemon pool or one-shot CLI processes
- `button(...$args):string`: DOM form tags for button, input, select and textarea
- `camel(string $text):string`: Convert text to camelCase
- `chunk(...$cmds):void`: Stream JSON chunks over CLI or Server-Sent Events
- `create(iterable $items, \Closure $keyCb, ?\Closure $valueCb = null):array`: Create associative array from iterable using callbacks
- `en($text, ...$args):string`: Language and translation resource
- `exec_stream(string $cmd, ?int $timeoutSec = 0):Generator`: Stream shell command output via yielding
- `HTTP(string $url, array $headers = [], bool $JSON = false, $POST = null, $PUT = null, $PATCH = null, $QUERY = null, bool $DELETE = false, string|bool|null $agent = null, string|bool $cookies = false, int $timeout = 15, &$response = null, bool $public = false, bool $follow = true)`: HTTP request helper via cURL
- `input(...$args):string`: DOM form tags for button, input, select and textarea
- `n8n($webhook, ?array $data = null, $test = false)`: Call n8n webhook endpoint
- `nl($text, ...$args):string`: Language and translation resource
- `notify(string $title, string $body = void, string $type = 'info', string $level = 'info', ?string $user = null):void`: Notification to the central hub: POST to [notify].url (secret header) via Phlo's HTTP() function. No-op without [notify] config.
- `phlo(?string $phloName = null, ...$args):mixed`
- `phlo_app(...$args):void`
- `phlo_async(string $cb, ...$args):bool`: Run an app target in the background, via the daemon pool or a one-shot CLI process
- `phlo_cli(array $args):void`
- `phlo_dispatch(string $target, array $args = []):mixed`
- `phlo_exception(Throwable $e):void`
- `phlo_exists(string $obj):bool`: Check if compiled Phlo class exists
- `phlo_load(bool $http):void`
- `phlo_serve():void`
- `phlo_stream(string $cb, ...$args):Generator`: Stream an app target's output line by line, via the daemon pool or a one-shot CLI process
- `phlo_sync(string $cb, ...$args)`: Run an app target synchronously, via the daemon pool or a one-shot CLI process
- `phlo_thread():void`
- `public_address(string $url):?string`: HTTP request helper via cURL
- `sanitize_allow():array`: HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places
- `sanitize_html(string $html, ?array $allow = null):string`: HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places
- `sanitize_url(string $url, bool $image = false):bool`: HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places
- `sanitize_walk(DOMNode $node, array $allow):void`: HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places
- `select(...$args):string`: DOM form tags for button, input, select and textarea
- `setting(?string $key = null, $value = null):mixed`: Persistent app settings in data/settings.json: setting() lists everything, setting(key) reads one value or null, setting(key, value) writes
- `slug(string $text):string`: Convert text to URL slug
- `stream($data = null, string $type = 'application/octet-stream', ?string $name = null):void`: Raw data stream beside the JSON command channel: stream() emits text or binary chunks under any content type, app.stream() consumes them via fetch dispatching on the response type
- `tag(string $tagName, ?string $inner = null, ...$args):string`: Generate HTML tag string with attributes
- `textarea(...$args):string`: DOM form tags for button, input, select and textarea
- `time_human(?int $time = null):string`: Convert timestamp age to human label
- `wsCast($wsTarget = 'all', $wsHost = host, $wsPort = daemon, $wsExcept = void, ...$data):int`: Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels
- `wsChannel(string $action, string $channel, string $socket, string $token, $host, $port):int`: Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels
- `wsJoin(string $channel, string $wsSocket = void, string $wsToken = void, $wsHost = host, $wsPort = daemon):int`: Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels
- `wsLeave(string $channel = void, string $wsSocket = void, string $wsToken = void, $wsHost = host, $wsPort = daemon):int`: Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels

## AI

### %AI

Unified AI facade with engine auto-detect

Advice: One door for every engine: %AI->chat reads the engine from the model name, so gpt goes to OpenAI, claude to Claude and gemini to Gemini, while via names one outright. Every engine answers in the same shape, with answer, model, finish and a token count, so swapping models is a one-word change. A model no rule matches falls back to OpenAI, and each engine still needs credentials of its own.

- File: `resources/AI/AI.phlo`
- `AI->model:string` (line 9)
- `AI::engines` (line 10)
- `AI::http(string $url, array $headers, bool $json = true, mixed $post = null):string` (line 11)
- `AI->resolve(...$args):array` (line 12)
- `AI->chat(...$args):obj` (line 20)
- `AI->stream(...$args):Generator` (line 24)
- `AI->embedding(...$args):array` (line 28)
- `AI->vision(...$args):obj|Generator` (line 32)
- `AI->transcribe(...$args):obj` (line 36)

### %Claude

Anthropic Claude API

Advice: Anthropic has no embedding endpoint, so embedding() quietly goes out through OpenAI and needs that key too. system travels as its own field here rather than as a first message, which context() settles, so the same call works on either engine. vision() fetches an image URL itself and sends it inline as base64, so a large photo becomes a large request.

- File: `resources/AI/Claude.phlo`
- `Claude::model` (line 9)
- `Claude::context(...$args):array` (line 11)
- `Claude::tool($tool):array` (line 21)
- `Claude->embedding($input, $model = 'text-embedding-3-small'):array` (line 31)
- `Claude->vision($text, $image, $stream = false, ...$args):obj|Generator` (line 33)
- `Claude->chat(...$args):obj` (line 40)
- `Claude->parseSSE(string $url, array $headers, array $payload):Generator` (line 57)
- `Claude->stream(...$args):Generator` (line 89)
- `Claude->request($uri, ...$args)` (line 102)

### %DeepSeek

DeepSeek API (OpenAI-compatible, extends OpenAI)

Advice: OpenAI-compatible, so it inherits the whole OpenAI resource and only swaps endpoint, model and credentials; anything that works there works here unless DeepSeek itself lacks it. Embeddings are such a gap: they are routed to OpenAI, so that key has to be present as well.

- File: `resources/AI/DeepSeek.phlo`
- `DeepSeek::model` (line 10)
- `DeepSeek::endpoint` (line 11)
- `DeepSeek::cred` (line 12)
- `DeepSeek::label` (line 13)
- `DeepSeek->embedding($input, $model = 'text-embedding-3-small'):array` (line 15)

### %Gemini

Google Gemini API

Advice: Google puts the model in the path rather than in the body, so a wrong model name reads as a wrong URL. Its embeddings come from text-embedding-004 with a different vector length than OpenAI's, so a collection filled by one engine cannot be searched with the other.

- File: `resources/AI/Gemini.phlo`
- `Gemini::model` (line 9)
- `Gemini::endpoint` (line 10)
- `Gemini::context(...$args):array` (line 12)
- `Gemini::tool($tool):array` (line 23)
- `Gemini->embedding($input, $model = 'text-embedding-004'):array` (line 33)
- `Gemini->vision($text, $image, $stream = false, ...$args):obj|Generator` (line 35)
- `Gemini->chat(...$args):obj` (line 43)
- `Gemini->parseSSE(string $url, array $headers, array $payload):Generator` (line 58)
- `Gemini->stream(...$args):Generator` (line 89)
- `Gemini->request($path, ...$args)` (line 97)

### %Grok

xAI Grok API (OpenAI-compatible, extends OpenAI)

Advice: OpenAI-compatible, so it inherits the whole OpenAI resource and only swaps endpoint, model and credentials. Embeddings are not part of the deal and go out through OpenAI, so that key has to be present as well.

- File: `resources/AI/Grok.phlo`
- `Grok::model` (line 10)
- `Grok::endpoint` (line 11)
- `Grok::cred` (line 12)
- `Grok::label` (line 13)
- `Grok->embedding($input, $model = 'text-embedding-3-small'):array` (line 15)

### %OpenAI

Basic OpenAI functions

Advice: Write a conversation as system, user and assistant instead of assembling messages yourself; context() folds them into the right order. Each answer carries tokens_in and tokens_out, so a run can be metered or capped without reading the raw response. A refused request is raised as an error rather than returned, which is the opposite of how the connectors behave, so wrap a call you cannot afford to lose. Pass token to use a key other than the configured one.

- File: `resources/AI/OpenAI.phlo`
- `OpenAI::model` (line 9)
- `OpenAI::endpoint` (line 10)
- `OpenAI::cred` (line 11)
- `OpenAI::label` (line 12)
- `OpenAI::voices` (line 13)
- `OpenAI::context(...$args):array` (line 14)
- `OpenAI::tool($tool):array` (line 21)
- `OpenAI->chat(...$args):obj` (line 35)
- `OpenAI->embedding($input, $model = 'text-embedding-3-small'):array` (line 45)
- `OpenAI->parseSSE(string $url, array $headers, array $payload):Generator` (line 46)
- `OpenAI->stream(...$args):Generator` (line 77)
- `OpenAI->transcribe($file, $model = 'whisper-1', ...$args):obj` (line 87)
- `OpenAI->vision($text, $image, $stream = false, ...$args):obj|Generator` (line 98)
- `OpenAI->request($uri, $JSON = true, $token = null, ...$args)` (line 104)

### Functions

- `answer($question, ...$options):?string`: Simple AI answering helper

## connectors

### %Connector

Base class for API connectors: credentials, JSON requests, retries, pagination and a normalized result contract

Advice: Make one with Connector::make(); it reads its own section from %creds, so keys live in data/creds.ini or in PHLO__Section__key in the environment and never in your code. Every call answers in the same shape, ok with status and data or ok false with error, and nothing is thrown, so test ->ok rather than catching. Raise retries above zero to let GET, HEAD and QUERY back off and try again on 429 and 5xx; writes are never retried, because a repeated POST would book twice. Connector::for($record, 'column') uses the credentials of one record, a tenant or a user, on top of the app's section: the column holds them sealed with seal(), which encrypts with the key in [connectors], and an OAuth connector keeps its access token per record.

- File: `resources/connectors/Connector.phlo`
- `Connector::section` (line 9)
- `Connector::api` (line 10)
- `Connector->__construct(?array $config = null)` (line 12)
- `Connector::make(?array $config = null):static` (line 23)
- `Connector::for(object $record, string $column = 'connector'):static` (line 27)
- `Connector::seal(array $credentials):string` (line 35)
- `Connector::unseal(string $value):array` (line 37)
- `Connector::sealKey(bool $required = true):?string` (line 46)
- `Connector->base:string` (line 51)
- `Connector->headers:array` (line 52)
- `Connector::fields:array` (line 54)
- `Connector->configured(...$keys):bool` (line 56)
- `Connector->missing(...$keys):?obj` (line 63)
- `Connector::bearer($token):string` (line 67)
- `Connector::basic($user, $pass):string` (line 68)
- `Connector::build(string $method, string $url, ?array $query = null, array $headers = [], mixed $json = null, mixed $form = null):array` (line 70)
- `Connector::ok($data, int $status = 200):obj` (line 85)
- `Connector::fail($error, int $status = 0):obj` (line 86)
- `Connector::errorMessage($data, string $raw, int $status):string` (line 88)
- `Connector::parse($raw, int $status = 200):obj` (line 103)
- `Connector::retryable($method, int $status):bool` (line 110)
- `Connector::backoff(int $attempt, $response):int` (line 112)
- `Connector->dispatch(array $req):obj` (line 121)
- `Connector->request(string $method, string $url, ?array $query = null, array $headers = [], mixed $json = null, mixed $form = null):obj` (line 147)
- `Connector->get(string $url, ?array $query = null, array $headers = []):obj` (line 153)
- `Connector->post(string $url, mixed $json = null, array $headers = []):obj` (line 154)
- `Connector->put(string $url, mixed $json = null, array $headers = []):obj` (line 155)
- `Connector->patch(string $url, mixed $json = null, array $headers = []):obj` (line 156)
- `Connector->query(string $url, mixed $json = null, array $headers = []):obj` (line 157)
- `Connector->del(string $url, array $headers = []):obj` (line 158)
- `Connector->form(string $url, array $fields, array $headers = []):obj` (line 159)
- `Connector->paginate(string $url, callable $extract, ?array $query = null, string $param = 'page', int $start = 1, int $max = 0):array` (line 161)

### %EBoekhouden

e-Boekhouden.nl connector: session auth from an API token, relations and sales invoices

Advice: Authenticates with a session rather than a token per call: the first call trades api_token for one, later calls in the same request reuse it, and a new request starts over. Sessions are limited, so gather the work you need per request instead of making a connector per call.

- File: `resources/connectors/finance/EBoekhouden.phlo`
- `EBoekhouden::section` (line 10)
- `EBoekhouden::api` (line 11)
- `EBoekhouden->sessionToken:string` (line 13)
- `EBoekhouden->headers:array` (line 15)
- `EBoekhouden::fields:array` (line 17)
- `EBoekhouden->session:obj` (line 26)
- `EBoekhouden->guard:?obj` (line 37)
- `EBoekhouden->relations(array $query = []):obj` (line 42)
- `EBoekhouden->createRelation(array $relation):obj` (line 47)
- `EBoekhouden->invoices(array $query = []):obj` (line 52)
- `EBoekhouden->createInvoice(array $invoice):obj` (line 57)

### %ExactOnline

Exact Online connector (OAuth2): read sales invoices and accounts, create sales invoices

Advice: The division number sits in the base URL, so a connector speaks to exactly one administration and a second administration needs a second connector with its own config. Exact rotates the refresh token on every refresh, which is why the token store locks; running two apps on one refresh token logs both out.

- File: `resources/connectors/finance/ExactOnline.phlo`
- `ExactOnline::section` (line 10)
- `ExactOnline::tokenUrl` (line 11)
- `ExactOnline->base:string` (line 13)
- `ExactOnline::fields:array` (line 15)
- `ExactOnline->guard:?obj` (line 26)
- `ExactOnline->invoices(array $query = []):obj` (line 28)
- `ExactOnline->accounts(array $query = []):obj` (line 33)
- `ExactOnline->createInvoice(array $invoice):obj` (line 38)

### %GoogleCalendar

Google Calendar connector (OAuth2): read events and create events

Advice: Shares the Google section with Sheets, so one refresh token has to carry both scopes. calendarId defaults to primary, which is the mailbox of the account that authorized, not a shared agenda; give a calendar address for those. Google returns times as RFC3339 with an offset, so keep the timezone rather than casting to a local timestamp.

- File: `resources/connectors/cloud/GoogleCalendar.phlo`
- `GoogleCalendar::section` (line 10)
- `GoogleCalendar::tokenUrl` (line 11)
- `GoogleCalendar->base:string` (line 13)
- `GoogleCalendar::fields:array` (line 15)
- `GoogleCalendar->guard:?obj` (line 25)
- `GoogleCalendar->events(string $calendarId = 'primary', array $query = []):obj` (line 27)
- `GoogleCalendar->createEvent(array $event, string $calendarId = 'primary'):obj` (line 32)

### %GoogleSheets

Google Sheets connector (OAuth2): read ranges and append rows

Advice: Shares the Google section with Calendar, so one refresh token has to carry both scopes. A range is A1 notation including the tab name, e.g. Sheet1!A:D. append() writes with USER_ENTERED, so the sheet parses what you send just as a typist would and a leading zero or a date-like string is reinterpreted; pass RAW when the value has to stay untouched.

- File: `resources/connectors/cloud/GoogleSheets.phlo`
- `GoogleSheets::section` (line 10)
- `GoogleSheets::tokenUrl` (line 11)
- `GoogleSheets->base:string` (line 13)
- `GoogleSheets::fields:array` (line 15)
- `GoogleSheets->guard:?obj` (line 25)
- `GoogleSheets->values($spreadsheetId, string $range):obj` (line 27)
- `GoogleSheets->append($spreadsheetId, string $range, array $rows, string $valueInputOption = 'USER_ENTERED'):obj` (line 32)

### %Lightspeed

Lightspeed Retail (V3) connector: read customers and sales, create customers

Advice: Retail V3, so cluster_id names the account and the key and secret authenticate. Lightspeed rate limits per account with a leaky bucket, so raise retries rather than firing calls in a loop. findCustomer() picks its search field from what you pass: an address with an at sign searches on email, anything else on phone.

- File: `resources/connectors/shops/Lightspeed.phlo`
- `Lightspeed::section` (line 10)
- `Lightspeed->base:string` (line 12)
- `Lightspeed->headers:array` (line 14)
- `Lightspeed::fields:array` (line 16)
- `Lightspeed->customers(array $query = []):obj` (line 29)
- `Lightspeed->findCustomer($participant):obj` (line 34)
- `Lightspeed->customer($id):obj` (line 40)
- `Lightspeed->sales(array $query = []):obj` (line 45)
- `Lightspeed->createCustomer(array $customer):obj` (line 50)

### %MessageBird

MessageBird connector: send SMS

Advice: Needs access_key and an originator, the sender shown to the recipient; some countries refuse an alphanumeric originator, so a real number is the safer choice. Pass an array as the recipient to send one message to several numbers at once.

- File: `resources/connectors/chat/MessageBird.phlo`
- `MessageBird::section` (line 10)
- `MessageBird->base:string` (line 12)
- `MessageBird->headers:array` (line 14)
- `MessageBird::fields:array` (line 16)
- `MessageBird::errorMessage($data, string $raw, int $status):string` (line 22)
- `MessageBird->sms($to, $body, array $extra = []):obj` (line 27)

### %MicrosoftGraph

Microsoft Graph connector (app-only client credentials): read users and calendars, send mail, create events

Advice: This is the app-only flow: the token belongs to the registration, not to a person, so it needs admin-consented application permissions and every call names the mailbox it acts on. Tokens are cached in APCu for their lifetime, so a run without APCu fetches one per request. Set mailbox to spare yourself passing a user each time.

- File: `resources/connectors/cloud/MicrosoftGraph.phlo`
- `MicrosoftGraph::section` (line 10)
- `MicrosoftGraph->base:string` (line 12)
- `MicrosoftGraph->headers:array` (line 14)
- `MicrosoftGraph::fields:array` (line 16)
- `MicrosoftGraph->token:string` (line 27)
- `MicrosoftGraph->fetchToken:string` (line 33)
- `MicrosoftGraph->mailbox($user = null):string` (line 51)
- `MicrosoftGraph->users(array $query = []):obj` (line 53)
- `MicrosoftGraph->user($id):obj` (line 58)
- `MicrosoftGraph->events($user = null, array $query = []):obj` (line 63)
- `MicrosoftGraph->sendMail($message, $user = null, bool $save = true):obj` (line 70)
- `MicrosoftGraph->createEvent(array $event, $user = null):obj` (line 77)

### %Moneybird

Moneybird connector: read contacts and invoices, create sales invoices

Advice: Needs an administration_id and a personal access token with rights for contacts and invoices. findContact() searches on one match, so use it to look up rather than to list. An invoice is created as a draft: sending or booking it is a separate step in Moneybird.

- File: `resources/connectors/finance/Moneybird.phlo`
- `Moneybird::section` (line 10)
- `Moneybird->base:string` (line 12)
- `Moneybird->headers:array` (line 14)
- `Moneybird::fields:array` (line 16)
- `Moneybird->contacts(array $query = []):obj` (line 22)
- `Moneybird->findContact($query):obj` (line 27)
- `Moneybird->contact($id):obj` (line 32)
- `Moneybird->invoices(array $query = []):obj` (line 37)
- `Moneybird->createContact(array $contact):obj` (line 42)
- `Moneybird->createInvoice(array $invoice):obj` (line 47)

### %OAuthConnector

Base class for OAuth2 connectors: stored, auto-refreshed bearer access tokens via TokenStore, on the OAuth2 primitive

Advice: Use this instead of Connector when the provider hands out access tokens that expire. Give it client_id, client_secret and a refresh_token and TokenStore keeps the access token and renews it in time; a subclass only names its section and tokenUrl.

- File: `resources/connectors/OAuthConnector.phlo`
- `OAuthConnector::tokenUrl` (line 10)
- `OAuthConnector->oauthKey:string` (line 13)
- `OAuthConnector->token:?string` (line 15)
- `OAuthConnector->headers:array` (line 17)
- `OAuthConnector->authed:bool` (line 19)

### %PDOK

PDOK connector: a Dutch address from a postcode and house number, out of the government's open register

Advice: address('1012RJ', 147) gives the street, city, municipality, province and coordinates, or null when the register does not know it. It needs no key and no account. An addition goes in the third argument, as the register writes it: 147, A. Call it from your own route and cache what people ask often; the register is a public service, not yours to hammer.

- File: `resources/connectors/geo/PDOK.phlo`
- `PDOK::api` (line 10)
- `PDOK->address(string $postcode, int|string $number, string $addition = void):?obj` (line 12)

### %Resend

Resend connector: send transactional email via the HTTP API

Advice: Needs api_key and a from_email on a domain you verified with Resend, otherwise the send is refused. send() takes HTML; leave it out for a plain text mail and add anything else Resend accepts through extra.

- File: `resources/connectors/chat/Resend.phlo`
- `Resend::section` (line 10)
- `Resend->base:string` (line 12)
- `Resend->headers:array` (line 14)
- `Resend::fields:array` (line 16)
- `Resend->send($to, $subject, $html = void, array $extra = []):obj` (line 22)

### %Shopify

Shopify Admin API connector: read customers, orders and products; create draft orders and products; update inventory

Advice: Needs shop_domain including myshopify.com and an admin access token; api_version defaults to 2026-10 and a Shopify version is supported for about a year, after which Shopify answers with the oldest one it still supports, so set the one you tested against rather than leaning on the default. This connector speaks the REST Admin API, which Shopify calls legacy; its product writes are deprecated there since 2024-04. setInventory() writes an absolute level, not a difference, so read the current one first when you mean to add. A draft order is not an order until it is completed in Shopify.

- File: `resources/connectors/shops/Shopify.phlo`
- `Shopify::section` (line 10)
- `Shopify->base:string` (line 12)
- `Shopify->headers:array` (line 14)
- `Shopify::fields:array` (line 16)
- `Shopify->customers(array $query = []):obj` (line 26)
- `Shopify->searchCustomers($query, int $limit = 10):obj` (line 31)
- `Shopify->customer($id):obj` (line 36)
- `Shopify->orders(array $query = []):obj` (line 41)
- `Shopify->products(array $query = []):obj` (line 46)
- `Shopify->createDraftOrder(array $order):obj` (line 51)
- `Shopify->createProduct(array $product):obj` (line 56)
- `Shopify->setInventory($inventoryItemId, $locationId, int $available):obj` (line 61)

### %Slack

Slack connector: post messages, read channel history and list channels

Advice: Needs a bot token, and the bot has to be invited into the channel it posts in, else the call comes back ok false with not_in_channel. Slack answers HTTP 200 even when it refuses, so read the outcome from the result, never from the status.

- File: `resources/connectors/chat/Slack.phlo`
- `Slack::section` (line 10)
- `Slack::api` (line 11)
- `Slack->headers:array` (line 13)
- `Slack::fields:array` (line 15)
- `Slack->result(obj $res):obj` (line 24)
- `Slack->send($channel, $text, array $extra = []):obj` (line 31)
- `Slack->history($channel, int $limit = 20):obj` (line 36)
- `Slack->channels(int $limit = 100, string $types = 'public_channel'):obj` (line 41)

### %Telegram

Telegram Bot API connector: send messages, photos and documents; poll updates

Advice: Needs a bot token from BotFather and a chat_id, and a person has to have written to the bot before it can write to them. Like Slack, the API answers 200 on refusal, which the connector already translates into ok false. photo() and document() take a URL or an existing file_id, not raw bytes.

- File: `resources/connectors/chat/Telegram.phlo`
- `Telegram::section` (line 10)
- `Telegram->base:string` (line 12)
- `Telegram::fields:array` (line 14)
- `Telegram->result(obj $res):obj` (line 23)
- `Telegram->send($chatId, $text, array $extra = []):obj` (line 30)
- `Telegram->photo($chatId, $photo, $caption = void, array $extra = []):obj` (line 35)
- `Telegram->document($chatId, $document, $caption = void, array $extra = []):obj` (line 42)
- `Telegram->updates(int $offset = 0, int $limit = 100):obj` (line 49)

### %TokenStore

Persisted OAuth2 token store with automatic refresh via the OAuth2 resource

Advice: Tokens are kept as one file per key under data/tokens with 0600 rights, encrypted when [connectors] has a key, so a refresh survives a restart and every worker shares it. A refresh takes an exclusive lock, which matters with providers that rotate the refresh token: without it the losing request is left holding a dead one.

- File: `resources/connectors/TokenStore.phlo`
- `TokenStore::path($key):string` (line 9)
- `TokenStore::read($key):array` (line 11)
- `TokenStore::write($key, array $token):void` (line 20)
- `TokenStore::valid(array $token):bool` (line 30)
- `TokenStore::store($res, $refresh):array` (line 32)
- `TokenStore::lock($key)` (line 44)
- `TokenStore::access($key, $tokenUrl, $clientId, $clientSecret, array $seed = []):?string` (line 55)

### %Twilio

Twilio connector: send SMS and read message status

Advice: Needs account_sid and auth_token, plus either a from_number in E.164 or a messaging_service_sid; without one of the two the send is refused before it leaves. Twilio speaks form encoding rather than JSON, which sms() handles, so pass extra fields in Twilio's own capitalized names. A returned sid says it was accepted, not delivered; message() tells you what became of it.

- File: `resources/connectors/chat/Twilio.phlo`
- `Twilio::section` (line 10)
- `Twilio->base:string` (line 12)
- `Twilio->headers:array` (line 14)
- `Twilio::fields:array` (line 16)
- `Twilio->sms($to, $body, array $extra = []):obj` (line 26)
- `Twilio->message($sid):obj` (line 37)

## DB

### %DB

Database engine class

Advice: The shape every driver fills in, and the reason a model can move between MySQL, PostgreSQL, SQLite and a JSON file untouched. Reads come in named flavours, so ask for what you want back: record for one, records keyed by id, rows in order, column, pair and item. Anything you pass as an argument is bound, never pasted into the SQL, so a value from a visitor is safe by construction. A connection that went away is reconnected and the query is tried once more, which is what keeps a long-lived worker alive.

- File: `resources/DB/DB.phlo`
- `DB->PDO:\PDO` (line 10)
- `DB->fieldQuotes:string` (line 11)
- `DB->savepoint:int` (line 12)
- `DB->insertIgnore:string` (line 13)
- `DB->insertOnConflict:string` (line 14)
- `DB->load(string $table, string $columns = '*', string $where = void, string $joins = void, string $group = void, string $limit = void, string $order = void, array $whereArgs = [], ...$args)` (line 18)
- `DB->named(string $table, array $args):array` (line 37)
- `DB->query($query, ...$args)` (line 49)
- `DB->queryRun($query, $args, $retry):\PDOStatement` (line 56)
- `DB->goneAway($e):bool` (line 80)
- `DB->column(...$args):array` (line 82)
- `DB->item(...$args)` (line 83)
- `DB->pair(...$args):array` (line 84)
- `DB->group(...$args):array` (line 85)
- `DB->records(...$args):array` (line 86)
- `DB->rows(...$args):array` (line 87)
- `DB->record(...$args):?obj` (line 88)
- `DB->quoteList(array $ids):string` (line 89)
- `DB->quoteId($id):string` (line 94)
- `DB->create(string $table, ...$data)` (line 96)
- `DB->lastId` (line 105)
- `DB->upsert(string $table, array $objKey, ...$data):int` (line 108)
- `DB->upsertClause(array $key, array $update):string` (line 117)
- `DB->change(string $table, string $where, ...$data):int` (line 119)
- `DB->script(string $sql):void` (line 130)
- `DB->delete(string $table, string $where, ...$args):int` (line 134)
- `DB->begin:?bool` (line 135)
- `DB->commit:?bool` (line 136)
- `DB->rollback:?bool` (line 152)
- `DB->objAfterCommit` (line 158)
- `DB->objOnCommit(callable $work):void` (line 159)
- `DB->objInTransaction:bool` (line 163)
- `DB->transaction($callback)` (line 165)

### %JSONDB

JSON file database driver. One JSONDB instance = one JSON file = one model table. No joins, no transactions, no schema introspection.

Advice: A model in a JSON file, for a set of records that stays small and readable: no joins, no transactions, and every write rewrites the whole file. It understands comparisons, LIKE, IN, BETWEEN and IS NULL in a where, the same ones named arguments write, peels parentheses around a part, and refuses an OR or raw SQL rather than ignoring it, so keep the model plain. Move to SQLite the moment the file grows or two processes start writing.

- File: `resources/DB/JSONDB.phlo`
- `JSONDB::__handle` (line 10)
- `JSONDB->__construct(private string $file)` (line 11)
- `JSONDB->PDO:\PDO` (line 15)
- `JSONDB->fieldQuotes:string` (line 16)
- `JSONDB->lastInsertedId` (line 17)
- `JSONDB->quoteList(array $ids):string` (line 24)
- `JSONDB->objRead:array` (line 26)
- `JSONDB->objWrite(array $data):int|false` (line 27)
- `JSONDB->objNextId(array $data):int` (line 28)
- `JSONDB->objConditions(string $where, array $args):array` (line 34)
- `JSONDB->objMatches(array $row, array $conditions):bool` (line 60)
- `JSONDB::likePattern($value):string` (line 86)
- `JSONDB->objFilter(array $data, string $where = void, ...$args):array` (line 88)
- `JSONDB->objSelect(string $where = void, string $limit = void, string $order = void, ...$args):array` (line 94)
- `JSONDB->create(string $table, ...$data)` (line 110)
- `JSONDB->change(string $table, string $where, ...$data):int` (line 125)
- `JSONDB->upsert(string $table, array $objKey, ...$data):int` (line 146)
- `JSONDB->delete(string $table, string $where, ...$args):int` (line 156)
- `JSONDB->load(string $table, string $columns = '*', string $where = void, string $joins = void, string $group = void, string $limit = void, string $order = void, array $whereArgs = [], ...$args):JSON_result` (line 165)
- `JSONDB->query($query, ...$args)` (line 175)
- `JSONDB->begin:?bool` (line 177)
- `JSONDB->transaction($callback)` (line 178)
- `JSONDB->objOnCommit(callable $work):void` (line 179)
- `JSONDB->objInTransaction:bool` (line 182)
- `JSONDB->commit:?bool` (line 183)
- `JSONDB->rollback:?bool` (line 184)

### %JSON_result

Minimal PDOStatement-like wrapper for JSONDB result arrays

Advice: Exists so JSONDB can hand back something that behaves like a PDO statement, which is what lets the ORM stay unaware of which driver answered. You do not build one yourself; you meet it as the return value of a JSONDB query.

- File: `resources/DB/JSON.result.phlo`
- `JSON_result::__handle` (line 8)
- `JSON_result->data:array` (line 9)
- `JSON_result->columns:string` (line 10)
- `JSON_result->__construct(array $data, string $columns = '*')` (line 11)
- `JSON_result->values($row):array` (line 18)
- `JSON_result->fetchAll($mode = 2, $class = 'obj'):array` (line 24)
- `JSON_result->fetchObject($class = 'obj'):?obj` (line 55)
- `JSON_result->fetch($mode = 2)` (line 63)
- `JSON_result->fetchColumn($col = 0)` (line 70)
- `JSON_result->rowCount:int` (line 76)

### %migration

Schema migrations from numbered SQL files, run from the command line

Advice: One .sql file per change in migrations/ at the app root, named so they sort in order (001_users.sql). php www/app.php migration::run applies every file that has not run, each with its record in one transaction, and stops at the first that fails; migration::status lists what ran, what is open and what changed after it ran. A database with tables but no schema_migration is refused, so the chain is never laid over a schema it did not make; migration::adopt records the files as they are without running them, which also accepts a file that changed. A run holds a lock on the database (GET_LOCK on MySQL, an advisory lock on PostgreSQL, a .lock file beside the SQLite file), so a second one at the same time stops. A file that changed after it ran stops a run too. MySQL commits DDL as it goes, so there a failing file can leave the statements before it: keep one change per file, and take a dump first, because this does not. Set static %migration.prefix when several apps keep their chain in one database; a row another tool wrote without a hash is not checked until adopt, and a schema_migration from before the hash, made by an earlier version or a script of your own, gets that column on the next run or adopt.

- File: `resources/DB/migration.phlo`
- `migration::table` (line 9)
- `migration::prefix` (line 10)
- `migration::dir` (line 11)
- `migration::DB` (line 12)
- `migration::files:array` (line 14)
- `migration::sql(string $file):string` (line 15)
- `migration::hash(string $sql):string` (line 16)
- `migration::ran:array` (line 18)
- `migration::open:array` (line 23)
- `migration::changed:array` (line 28)
- `migration::status:array` (line 33)
- `migration::run:array` (line 35)
- `migration::adopt:array` (line 44)
- `migration::apply(string $file, bool $run):string` (line 56)
- `migration::locked(callable $work)` (line 72)
- `migration::begin(bool $adopt = false):void` (line 97)
- `migration::exists:bool` (line 106)
- `migration::hashed:bool` (line 116)
- `migration::tables:int` (line 121)

### %model

Phlo ORM class with unified columns and schema

Advice: A model is a class with fields, and everything else follows from that: columns, form, validation and relations. Named arguments in a read are equality and a list is IN, so records(active: 1, id: [3, 5]) needs no SQL; a comparison goes in where: with ? placeholders and whereArgs:, as in records(where: 'price >= ?', whereArgs: [5]). Cast a value from the request to a scalar when a lookup must match one row, because a list there matches several. A static where scopes every read in its own parentheses, so no OR in a search reaches past it. A parent field gives back the record itself rather than an id, and children and many-relations are fetched once for a whole result set instead of per row. A save writes only the columns this request changed since the read, so it leaves another request's change alone; objUpsert() creates or changes a row in one statement, objIncrement() adds in the database itself, objRecordPage() gives one page with its total, and change() takes raw SQL for its SET as objUpdates:, a name no column can have. A column cannot be called after a part of the query (table, columns, where, joins, group, limit, order, whereArgs), the cache (cache, cacheKey) or ignore, because as a named argument it would become that part; objUpsert($objKey) and objRecordPage($objPage, $objSize) name their own parameters so key, page and size stay free for columns. A virtual field with sql: is a computed column. An app names its database with static %model.DB; nothing picks one for it. Set objValidate to have field rules enforced on save, objAudit to log every change, objCache to keep reads in APCu until the next write through the model is committed (a transaction reads past the cache, and cacheKey: only names the entry), and objLive to tell the open screens over the websocket that it changed.

- File: `resources/DB/model.phlo`
- `model::DB` (line 10)
- `model::objCache` (line 11)
- `model::objRecordLimit` (line 12)
- `model::objAudit` (line 13)
- `model::objValidate` (line 14)
- `model::objLive` (line 15)
- `model::idColumn` (line 16)
- `model::idType` (line 17)
- `model::canView` (line 19)
- `model::canCreate` (line 20)
- `model::canChange` (line 21)
- `model::canDelete` (line 22)
- `model::state:obj` (line 24)
- `model->objLoaded` (line 29)
- `model->__construct(...$data)` (line 30)
- `model::columns:string` (line 34)
- `model::_columns:string` (line 41)
- `model::fields:array` (line 48)
- `model::objReserved:array` (line 53)
- `model::_fields:array` (line 54)
- `model::field($name)` (line 60)
- `model::create(...$args):?static` (line 62)
- `model::objCreateCommit($record, $pk):?static` (line 72)
- `model::objRunValidation($data):bool` (line 81)
- `model::objErrors:array` (line 92)
- `model::createRecord(...$args)` (line 93)
- `model::objFlush:void` (line 97)
- `model::objGeneration:int` (line 104)
- `model::objScoped(string $where = void):string` (line 108)
- `model::objUnscoped(callable $work)` (line 115)
- `model::change($where, ...$args):int` (line 127)
- `model::delete($where, ...$args):int` (line 143)
- `model::objDeleteCommit($where, $args, $records):int` (line 153)
- `model::objLogChange($where, ...$args):int` (line 163)
- `model::objUpsert(string|array $objKey = void, ...$data):?static` (line 168)
- `model->objIncrement(string $column, int|float $by = 1):static` (line 179)
- `model->objSave:?static` (line 188)
- `model->objChanges($old = null):array` (line 214)
- `model->objSaveCreate($pk, $pkValue):?static` (line 221)
- `model::transaction($callback)` (line 229)
- `model::column(...$args):array` (line 231)
- `model::item(...$args)` (line 232)
- `model::pair(...$args):array` (line 233)
- `model::records(...$args):array` (line 234)
- `model::recordCount(...$args)` (line 235)
- `model::objRecordPage(int $objPage = 1, int $objSize = 25, ...$args):obj` (line 239)
- `model::record(...$args):?static` (line 246)
- `model::recordsLoad($args, $fetch, $fetchMode, $saveRelations = false)` (line 253)
- `model::objRel($key):array` (line 277)
- `model->objState:array` (line 282)
- `model->objGet($key)` (line 283)
- `model->objIn($ids, $db = null):string` (line 284)
- `model->objMirror(string $bucket, $key)` (line 290)
- `model->getParent($key)` (line 299)
- `model->getChildren($key)` (line 322)
- `model->getMany($key)` (line 340)
- `model->getCount($key):int` (line 364)
- `model->getLast($key)` (line 394)
- `model::objResolveClass($name):string` (line 420)
- `model::objShortName($class = null):string` (line 421)
- `model::objParents:array` (line 423)
- `model::objChildren:array` (line 429)
- `model::objMany:array` (line 435)

### %MySQL

MySQL handler via DB class

Advice: Reads host, database, user and password from the mysql section of %creds. A model reaches it through static %model.DB => %MySQL.

- File: `resources/DB/MySQL.phlo`
- `MySQL->upsertClause(array $key, array $update):string` (line 11)
- `MySQL->PDO:\PDO` (line 13)

### %PostgreSQL

PostgreSQL resource

Advice: Quotes identifiers with double quotes rather than backticks and has no INSERT IGNORE, so a duplicate is skipped with ON CONFLICT DO NOTHING. Postgres folds an unquoted name to lower case, so a column called createdAt in a schema is not the same one you get back unquoted.

- File: `resources/DB/PostgreSQL.phlo`
- `PostgreSQL->PDO:\PDO` (line 10)
- `PostgreSQL->fieldQuotes:string` (line 11)
- `PostgreSQL->insertIgnore:string` (line 12)
- `PostgreSQL->insertOnConflict:string` (line 13)
- `PostgreSQL->lastId` (line 19)

### %Qdrant

Embeddings resource with Qdrant

Advice: Embeddings are cached in APCu for four weeks per input and model, so repeating a search costs nothing at the AI end. create() opens a collection at 1536 dimensions, the length of an OpenAI vector, so state the size yourself when another engine fills it. search() without input sends a zero vector, which lists a collection rather than searching it.

- File: `resources/DB/Qdrant.phlo`
- `Qdrant->get(string $input, ?string $model = null):array` (line 9)
- `Qdrant->collections:array` (line 11)
- `Qdrant->create($collection, $size = 1536, $distance = 'Cosine'):bool` (line 12)
- `Qdrant->upsert($collection, $id, $input, ...$payload)` (line 13)
- `Qdrant->delete($collection, ...$ids)` (line 14)
- `Qdrant->search($collection, $input = null, $top = 100):array` (line 15)
- `Qdrant->drop($collection)` (line 16)
- `Qdrant->request($uri, ...$data)` (line 18)

### %SQLite

SQLite resource

Advice: One file, one database, given as a path: %SQLite('/path/db.sqlite'). It writes with a lock over the whole file, so it fits a single site or a worker but not a set of processes writing at once. Perfect where you want the ORM without a server.

- File: `resources/DB/SQLite.phlo`
- `SQLite::__handle` (line 10)
- `SQLite->__construct(private string $file)` (line 11)
- `SQLite->PDO:\PDO` (line 12)
- `SQLite->insertIgnore:string` (line 13)

## DOM

### %charts

Lightweight dependency-free SVG charts: sparkline, bars and donut. Use charts::spark/bars/donut.

Advice: Three small SVG charts rendered on the server, without a library and without a script, so they show up in a mail, a PDF and a page with a strict policy alike. They are meant for a number in context, not for exploring data: no axes, no legend, no tooltips.

- File: `resources/DOM/charts.phlo`
- `charts::spark($values, $color = '#888', $w = 240, $h = 48, $label = null):string` (line 8)
- `charts::bars($values, $color = '#888', $w = 240, $h = 48, $label = null):string` (line 28)
- `charts::donut($parts, $colors = null, $size = 120):string` (line 46)

### %connection

One verdict on the connection, drawn from the traffic itself: app.online, offline on <body>, app.connection.on('change')

Advice: Nothing runs on a clock here, and the browser's own opinion is not asked either. The verdict comes from what actually happened: a request that got no answer at all, or a websocket reconnect that failed, means offline; any answer at all, or a socket that opens, means online. A socket that merely closes says nothing, because sockets drop for a hundred reasons while HTTP is fine, and the reconnect that follows is the only probe there is. Read app.online, style on body.offline, and subscribe with app.connection.on('change', cb) to pause a live view or refuse what needs the server. It decides nothing about what the visitor sees; that is the app's. The websocket listeners are attached after the bundle has run, so this resource may sit before or after DOM/websocket in the list.

- File: `resources/DOM/connection.phlo`

### %cookiewall

Subtle GDPR cookie-consent banner. English by default; auto-translates when the lang system (en()) is loaded. Override prop labels for a fixed language, or prop translate to force it on/off.

Advice: Asks once and keeps the answer in a cookie, so it stays out of the way afterwards. canTrack and canAnalytics are what the rest of the app should ask before it loads anything; the banner itself blocks nothing. It translates itself when the language system is loaded, so it speaks the visitor's language without a second set of texts.

- File: `resources/DOM/cookiewall.phlo`
- `cookiewall::__handle` (line 9)
- `cookiewall->choice` (line 11)
- `cookiewall->hasChosen:bool` (line 12)
- `cookiewall->canTrack:bool` (line 13)
- `cookiewall->canAnalytics:bool` (line 14)
- `cookiewall->translate:bool` (line 16)
- `cookiewall->labels:array` (line 17)
- `cookiewall->label($key):string` (line 23)
- `route async POST cookiewall accept all` (line 25)
- `route async POST cookiewall accept essential` (line 30)
- `cookiewall->banner` (line 35)

### %CSS_fixes

Single Page App basic CSS boilerplate fixes

Advice: The handful of corrections nearly every app makes anyway: border-box sizing, no tap delay on anything clickable, no spinners on a number field, collapsed table borders and a [hidden] that actually hides. Note that it also clears the focus outline on inputs and buttons, so give focus a visible state of your own or keyboard users lose their place.

- File: `resources/DOM/CSS.fixes.phlo`

### %CSS_var

CSS variable proxy via app.var

Advice: app.var reads and writes CSS custom properties as if they were an object, so the server can change a colour, a size or a spacing with a command instead of a stylesheet swap. It writes on the root element, so what you set applies everywhere that inherits it.

- File: `resources/DOM/CSS.var.phlo`

### %datatags

Single Page App datatag plugin

Advice: Turn any element into a request without writing a handler: data-get, data-post, data-put, data-patch or data-delete holds the path, and with post, put and patch every other data attribute travels along as a field. That is why an element that also carries data-confirm is left alone here: the dialog resource asks first and clicks it again afterwards. Attribute names arrive dash-lowered as the browser gives them, so keep them one word.

- File: `resources/DOM/datatags.phlo`

### %dialog

Single Page App dialog resource

Advice: Replaces alert, confirm and prompt with a real dialog element, so they no longer block the page and no longer break an automated session. They answer a promise, so await them. Put data-confirm on a link or a button to ask before it does anything: the question is asked once, then the original action runs. The button labels live in app.dlgLabels, so an app writes its own language straight into that object.

- File: `resources/DOM/dialog.phlo`

### %exists

onExist helper for dynamic SPA elements

Advice: on() binds to what is there now, which is why it does not survive a page swap; onExist runs your callback the first time an element appears and only then, however it got there. That makes it the right hook for anything a plugin has to prepare once, and it is what the store and the numpad use themselves.

- File: `resources/DOM/exists.phlo`

### %ffmpeg

ffmpeg-wasm for the DOM: encode a canvas timeline to MP4, decode source frames via WebCodecs (seek fallback), transcode/run arbitrary ffmpeg. Exposes the ready singleton `ffmpeg` (and class `Ffmpeg`).

Advice: Encodes and converts video in the browser through ffmpeg-wasm, so no file has to leave the machine and no server has to be equipped for it. That comes at a price: several megabytes of wasm on first use, and encoding costs real time and memory, so it fits a clip rather than an hour of video. It loads the multithreaded core only on a cross-origin isolated page and falls back to a single-threaded one otherwise, which still works but is markedly slower.

- File: `resources/DOM/ffmpeg.phlo`

### %form

Single Page App form handler and input state saver

Advice: A form with class async submits over the same channel as the rest and answers with commands rather than a new page, using its own method attribute. Method and target are read as attributes, never as properties of the form: a field named action or method shadows the property with the element itself, and a form for a record with such a field would then never leave the page. A relative action resolves the way the browser would: against a base element when the page carries one, against the page itself otherwise. An empty or absent action posts to the current address, which a base element does not move. A GET form puts its fields in the query string, replacing the one on the action, the way an ordinary GET form does; a value that has to survive belongs in a field. A file field contributes its filename, because a file cannot travel in a URL. Apart from that, this keeps the DOM honest: what a visitor types is written back into the attributes, so the state that is saved and restored on a back button matches what is on screen. The page goes into the history once typing pauses for a third of a second, and at once when the app leaves it; the browser's own back button within that pause leaves the last keystrokes out of the page it left.

- File: `resources/DOM/form.phlo`

### %image_resizer

Client-side file upload image resizer

Advice: Scales a picked file down in the browser before it is uploaded, so a phone photo of several megabytes leaves as a few hundred kilobytes. It only shrinks, keeps the aspect ratio, and gives a data URL back through the callback, which can go straight into a preview or a form field. The image field uses it, so an upload through the CMS is already covered.

- File: `resources/DOM/image.resizer.phlo`

### %keyboard

On-screen keyboard for touch devices, with selectable layout

Advice: Put data-keyboard on a field to open a keyboard on focus; data-keyboard="azerty" picks the layout. Inside a dialog the keys mount in that dialog; data-keyboard-dock on an element there places them in the flow. phlo.keyboard.layouts takes extra layouts.

- File: `resources/DOM/keyboard.phlo`

### %link

Single Page App async link handler

Advice: A link with class async is fetched and swapped in instead of loading the page, and everything else keeps working: a target, a modifier click and an outside link go to the browser untouched. An anchor is remembered across the swap, so a deep link scrolls to the right place after the new content has arrived.

- File: `resources/DOM/link.phlo`

### %markdown

Client-side markdown parser

Advice: Parses markdown in the browser, for text that arrives after the page: a chat message, a preview while typing, an answer streaming in. It renders what it is given, so escape or clean anything a visitor wrote before showing it to someone else. Markdown that is already known at render time is cheaper to parse on the server.

- File: `resources/DOM/markdown.phlo`

### %numpad

On-screen numeric keypad for touch input, bound to a field

Advice: Put data-numpad="<selector>" on a container; empty containers get the standard keys, containers with their own data-numpad-key buttons keep them. Without a selector the pad writes to the first field of its own form.

- File: `resources/DOM/numpad.phlo`

### %shorthands

onChange, onClick and onInput event shorthands

Advice: Nothing more than onClick, onChange and onInput for the three most common cases of on(). Same behaviour and the same limitation: they bind to what exists at that moment, so use onExist for anything that appears later.

- File: `resources/DOM/shorthands.phlo`

### %store

Stateful binding engine

Advice: Bind an element to a value with data-bind and it follows every change, in both directions on an input. data-bind-attr does the same for an attribute, data-each repeats a template over a list, and app.calc holds values derived from others and recalculated on their own. app.persist keeps a path across a reload and app.sync keeps it equal across tabs or over a websocket. On a first render the DOM wins over an empty store, so server-rendered content is not blanked before the store has been filled.

- File: `resources/DOM/store.phlo`

### %template

Single Page App client-side templating

Advice: Add cb's to the templates object and output via apply(template: [$name => $rows, $name2 => $rows2, etc])

- File: `resources/DOM/template.phlo`

### %timestamps

DOM live timestamps

Advice: Create an app.tsLabels array to overwrite the tsBase labels in any language

- File: `resources/DOM/timestamps.phlo`

### %toasts

Simple toast resource

Advice: app.mod.toast(msg) for a short message that needs no answer, gone after four seconds or on a click. Because it is a command, the server can raise one from a route without a line of frontend code. Anything a visitor must confirm belongs in the dialog resource instead.

- File: `resources/DOM/toasts.phlo`

### %visible

onVisible and onVisibleIn helpers for DOM visibility

Advice: Reacts to an element entering or leaving the viewport at ten percent visible, which is what you want for lazy loading, counting a view or starting an animation at the right moment. Give only cbOut and it fires once and stops watching, so a one-off costs nothing afterwards. onVisibleIn watches inside a scrolling container rather than the window.

- File: `resources/DOM/visible.phlo`

### %websocket

Client-side WebSocket handler

Advice: Reconnects on its own with a backoff that triples up to half a minute, and tries at once when the network says it is back or the tab becomes visible again. send() answers true or false and never complains: whether a message that could not go out is queued or dropped is the app's call. Opens the connection and keeps it open, reconnecting on its own, and treats what arrives as commands, so the server can update a page with the same instructions a route uses. It survives a page swap, which a hand-bound on() does not. A token belongs in a cookie rather than in the URL, since a URL ends up in logs. Where a proxy keeps the socket from opening, set app.websocket.poll to a path that answers with the same commands: while the socket is down it is asked every pollEvery milliseconds (15 seconds), quietly, and the polling stops when the socket opens.

- File: `resources/DOM/websocket.phlo`

## fields

### %field

Base ORM field

Advice: Every field type extends this one and is made with field(type: 'x'), which resolves to the resource field_x; anything else you pass becomes a property, so title, required, length, pattern and enum need no declaration. Override input() for the form and label() for the list, and let objColumns name the columns the field owns, so a field that stores nothing returns an empty array.

- File: `resources/fields/field.phlo`
- `function field($type, ...$args):field` (line 10)
- `field::__handle` (line 12)
- `field->title:string` (line 14)
- `field->input($record):string` (line 16)
- `field->label($record)` (line 18)
- `field->objColumns:array` (line 20)
- `field->cleared` (line 24)
- `field->objValidate($value):?string` (line 26)

### %field_bool

Boolean field

Advice: Stores 1 or 0 and never null, so a checkbox that is left alone still saves a value. Set true and false to change the two symbols a list shows.

- File: `resources/fields/bool.phlo`
- `field_bool->true` (line 10)
- `field_bool->false` (line 11)
- `field_bool->label($record):string` (line 13)
- `field_bool->input($record):string` (line 14)
- `field_bool->parse($record):int` (line 15)
- `field_bool->nullable:bool` (line 16)
- `field_bool->objColumns:array` (line 18)

### %field_child

Child relation field

Advice: The mirror of a parent field elsewhere: it reads the records that point back at this one and owns no column itself. It cannot be edited here, only followed, so change a child from its own record. Set key when the foreign key is not named after the parent model.

- File: `resources/fields/child.phlo`
- `field_child->list` (line 10)
- `field_child->change` (line 11)
- `field_child->create` (line 12)
- `field_child->record` (line 13)
- `field_child->count($record):string` (line 15)
- `field_child->last($record)` (line 16)
- `field_child->label($record):string` (line 17)
- `field_child->input($record):string` (line 18)
- `field_child->link($record):string` (line 19)
- `field_child->objKey($parentModel):string` (line 21)
- `field_child->objOwns($record, $parentId, $parentModel):bool` (line 23)

### %field_date

Date field

Advice: Renders in the reader's language through IntlDateFormatter, so a Dutch visitor sees a Dutch date without any work. Without the intl extension it falls back to a built-in Dutch and English month list, so any other language reads as English there. Set format to a date() pattern when the notation has to be fixed rather than local.

- File: `resources/fields/date.phlo`
- `field_date->format` (line 10)
- `field_date->months:array` (line 11)
- `field_date->label($record):string` (line 16)
- `field_date->cleared` (line 27)
- `field_date->objColumns:array` (line 29)

### %field_datetime

Date-time field

Advice: Stores a unix timestamp rather than a formatted string, and shows an age icon that runs blue under an hour, yellow under a day and red beyond. Fields called created and changed are kept out of the form because the model writes those itself.

- File: `resources/fields/datetime.phlo`
- `field_datetime->handle` (line 12)
- `field_datetime->change` (line 13)
- `field_datetime->create` (line 14)
- `field_datetime->label($record):string` (line 16)
- `field_datetime->labelIconClass($value):string` (line 17)
- `field_datetime->input($record):string` (line 18)
- `field_datetime->parse($record):void` (line 19)
- `field_datetime->cleared` (line 25)
- `field_datetime->objColumns:array` (line 27)

### %field_email

Email field

Advice: Only changes how a stored address is shown, as a mailto link. It validates nothing, so add pattern or required when the address has to be real.

- File: `resources/fields/email.phlo`
- `field_email->label($record)` (line 10)

### %field_file

File field

Advice: An upload is stored under a random token instead of its own name, so two people can send the same filename and no visitor can guess a neighbouring URL. That takes two columns, name and name_token, which objColumns already claims. Set accept to narrow the picker and what the server takes: an extension rule (.pdf) reads the name, a type rule (image/*, application/pdf) the content itself, so a script renamed to .jpg is not an image; maxSize caps the bytes. A refused upload ends the save with a 422 and the reason. Set path and uri when the files live somewhere other than the default. On disk the extension is lowercase whatever the upload said, so a route that lowercases it as well finds FOTO.JPG under token.jpg. Reading falls back to the extension as it was written, so an upload stored before that rule still opens.

- File: `resources/fields/file.phlo`
- `field_file->canDelete` (line 11)
- `field_file->delete` (line 12)
- `field_file->path` (line 13)
- `field_file->uri` (line 14)
- `field_file->length` (line 15)
- `field_file->accept` (line 16)
- `field_file->maxSize` (line 17)
- `field_file->label($record):string` (line 19)
- `field_file->input($record):string` (line 20)
- `field_file->parse($record):void` (line 29)
- `field_file->accepts($file):?string` (line 43)
- `field_file->read($record, $path = null):file` (line 54)
- `field_file->write($file)` (line 65)
- `field_file->writePath($file, $path = null):string` (line 66)
- `field_file->ext(string $filename):string` (line 73)
- `field_file->objColumns:array` (line 75)

### %field_image

Image field

Advice: A file field that also writes a thumbnail, and the browser scales the picture down before it is sent, so a phone photo does not travel at full size. thumbSize is the thumbnail edge in pixels; a list shows the thumbnail and a record shows the full image.

- File: `resources/fields/image.phlo`
- `field_image->accept` (line 11)
- `field_image->delete` (line 12)
- `field_image->uri` (line 13)
- `field_image->path` (line 14)
- `field_image->thumbPath` (line 15)
- `field_image->thumbSize` (line 16)
- `field_image->thumbUri` (line 17)
- `field_image->placeholder` (line 18)
- `field_image->record` (line 20)
- `field_image->label($record):string` (line 22)
- `field_image->preview($record):string` (line 23)
- `field_image->input($record):string` (line 24)
- `field_image->write($file)` (line 33)
- `field_image->objColumns:array` (line 35)

### %field_many

Many-to-many relation field

Advice: Editing is opt-in: a model that sets create/change on a many field gets the checkbox picker from input(); CMS.API::syncMany() then rewrites the pivot table on save.

- File: `resources/fields/many.phlo`
- `field_many->list` (line 10)
- `field_many->record` (line 11)
- `field_many->create` (line 12)
- `field_many->change` (line 13)
- `field_many->count($record):int` (line 15)
- `field_many->label($record):string` (line 16)
- `field_many->link($record):string` (line 17)
- `field_many->input($record):string` (line 19)
- `field_many->sync($model, $parentId)` (line 26)
- `field_many->objOwns($record, $parentId, $parentModel):bool` (line 34)
- `field_many->objColumns:array` (line 39)

### %field_multiselect

Multi-select via checkboxes; stores the choice as CSV in one hidden field (no save change needed).

Advice: Joins the checked boxes into one comma separated column, so it needs no pivot table and no extra save logic. Reach for many instead when the choices are records with a life of their own.

- File: `resources/fields/multiselect.phlo`
- `field_multiselect->label($record):string` (line 10)
- `field_multiselect->input($record):string` (line 15)
- `field_multiselect->objValidate($value):?string` (line 23)
- `field_multiselect->objColumns:array` (line 29)

### %field_number

Number field

Advice: decimals sets both the step of the input and the formatting of the list. min is 0 out of the box, so state it yourself when negative values are allowed.

- File: `resources/fields/number.phlo`
- `field_number->decimals` (line 10)
- `field_number->min` (line 11)
- `field_number->label($record):string` (line 13)
- `field_number->input($record):string` (line 14)
- `field_number->parse($record):void` (line 16)
- `field_number->objColumns:array` (line 24)

### %field_parent

Parent relation field

Advice: Points at another model through obj and offers every record of it in one select, so keep that to sets a person can still scroll; in the CMS, lookup: true gives a search box with suggestions instead. Reading the field gives you the record itself, not the id; its raw value is in objData.

- File: `resources/fields/parent.phlo`
- `field_parent->label($record):string` (line 10)
- `field_parent->input($record):string` (line 13)
- `field_parent->link($record, $content = null):string` (line 19)
- `field_parent->options:array` (line 20)
- `field_parent->cleared` (line 22)
- `field_parent->objColumns:array` (line 24)

### %field_password

Password field

Advice: Never gives the stored value back: a list prints dots and an empty form field leaves the current password untouched. It hashes with bcrypt on save, so keep the plain value nowhere.

- File: `resources/fields/password.phlo`
- `field_password->list` (line 10)
- `field_password->mcp` (line 11)
- `field_password->required` (line 12)
- `field_password->minlength` (line 13)
- `field_password->placeholder` (line 14)
- `field_password->input($record):string` (line 16)
- `field_password->label($record):string` (line 17)
- `field_password->parse($record)` (line 18)
- `field_password->objColumns:array` (line 20)

### %field_price

Price field

Advice: A number field fixed at two decimals. Store the amount in the unit you bill in and leave the formatting to the field.

- File: `resources/fields/price.phlo`
- `field_price->decimals` (line 10)

### %field_select

Select field

Advice: Stores the chosen option itself rather than a key, so renaming an option later leaves older records pointing at wording you no longer offer. Pass the accepted values as options; with labels: [value => label] instead the value is stored and the label shown, whatever its keys look like. Only those are accepted on save. An empty choice is an option like any other: options: ['', 'a', 'b'].

- File: `resources/fields/select.phlo`
- `field_select->choices:array` (line 11)
- `field_select->input($record):string` (line 17)
- `field_select->label($record)` (line 18)
- `field_select->objValidate($value):?string` (line 20)
- `field_select->objColumns:array` (line 22)

### %field_text

Text field

Advice: length is both the limit and the choice of input: over 250 characters the field renders a textarea instead of a single line.

- File: `resources/fields/text.phlo`
- `field_text->length` (line 10)
- `field_text->multiline:bool` (line 11)
- `field_text->label($record):string` (line 13)
- `field_text->input($record):string` (line 14)
- `field_text->inputField($record):string` (line 15)
- `field_text->inputMulti($record):string` (line 16)
- `field_text->objColumns:array` (line 18)

### %field_token

Token field

Advice: Fills itself with a random token when a record is made and refuses to change afterwards, which makes it the id to use for anything that ends up in a URL. handle is true, so a record can be looked up by this column instead of by its id.

- File: `resources/fields/token.phlo`
- `field_token->length` (line 11)
- `field_token->default:string` (line 12)
- `field_token->create` (line 13)
- `field_token->change` (line 14)
- `field_token->search` (line 15)
- `field_token->handle` (line 16)
- `field_token->label($record):string` (line 18)
- `field_token->parse($record)` (line 19)
- `field_token->objColumns:array` (line 21)

### %field_virtual

Virtual field

Advice: Owns no column and is never saved, so use it to show something derived next to the real fields. The record supplies the value through a prop or method of the same name.

- File: `resources/fields/virtual.phlo`
- `field_virtual->create` (line 10)
- `field_virtual->change` (line 11)
- `field_virtual->label($record)` (line 14)
- `field_virtual->objColumns:array` (line 16)

### %field_wysiwyg

WYSIWYG field

Advice: Stores whatever HTML the editor produces, including anything a user pasted in, so clean or escape it before it reaches a public page.

- File: `resources/fields/wysiwyg.phlo`
- `field_wysiwyg->label($record):string` (line 12)
- `field_wysiwyg->input($record):string` (line 14)
- `field_wysiwyg->objColumns:array` (line 22)

### Functions

- `field($type, ...$args):field`: Base ORM field

## files

### %CSV

CSV files: read with the header as keys, write rows that a spreadsheet will not run

Advice: Reads the first line as the header and picks its own separator by counting: more commas than semicolons and it is a comma, otherwise a semicolon. Every row comes back keyed by header name, so a file with duplicate or empty headers loses columns. CSV::text() and CSV::download() write rows: text that starts with =, +, -, @, a tab or a return gets a quote in front, so a value from a visitor cannot become a formula in someone's spreadsheet, while a number stays a number. A download starts with a byte-order mark, which Excel needs to read UTF-8; pass semi as the separator for a Dutch Excel.

- File: `resources/files/CSV.phlo`
- `CSV::__handle` (line 8)
- `CSV->__construct(string $filename, ?string $path = null)` (line 9)
- `CSV->objFile:string` (line 15)
- `CSV::row(array $values, string $separator = comma):string` (line 19)
- `CSV::text(iterable $rows, ?array $header = null, string $separator = comma):string` (line 22)
- `CSV::download(iterable $rows, string $filename, ?array $header = null, string $separator = comma)` (line 32)
- `CSV->objRead:void` (line 34)

### %DOCX

DOCX reader resource

Advice: Pulls the plain text out of a .docx and nothing more: no styling, no tables as tables, no images. Paragraphs come out as a list, which is what makes it usable for search and for feeding a model, and DOCX::toText() is the one-liner for that.

- File: `resources/files/DOCX.phlo`
- `DOCX->__construct(string $file)` (line 9)
- `DOCX::toText(string $file):string` (line 22)

### %file

File resource

Advice: Wrap a path in %file and everything about it is one call away: contents, size, mime, hashes, human dates, and a token() derived from the file's sha1, so the same content always yields the same token. Watch the difference between file and name: file is where it sits, name is what it is called, and ext and mime read the name. An upload therefore keeps its extension while the temp path has none.

- File: `resources/files/file.phlo`
- `file::__handle` (line 9)
- `file->__construct(public string $file, ?string $name = null, $contents = null, ...$args)` (line 10)
- `file->append(string $data):int|false` (line 16)
- `file->basename:string` (line 17)
- `file->base64:string` (line 18)
- `file->contents:string|false` (line 19)
- `file->contentsINI(bool $parse = true):array|false` (line 20)
- `file->contentsJSON($assoc = null)` (line 21)
- `file->copy($to):bool` (line 22)
- `file->created:int|false` (line 23)
- `file->createdAge:int` (line 24)
- `file->createdHuman:string` (line 25)
- `file->curl($type = null, $filename = null):CURLFile` (line 26)
- `file->delete:bool` (line 27)
- `file->exists:bool` (line 28)
- `file->ext:string` (line 29)
- `file->filename:string` (line 30)
- `file->getLine:string|false` (line 31)
- `file->getLength(int $length):string|false` (line 32)
- `file->is(string $file):bool` (line 33)
- `file->md5:string|false` (line 34)
- `file->mime:string` (line 35)
- `file->modified:int|false` (line 36)
- `file->modifiedAge:int` (line 37)
- `file->modifiedHuman:string` (line 38)
- `file->move($to):bool` (line 39)
- `file->name:string` (line 40)
- `file->output($download = false)` (line 41)
- `file->path:string` (line 42)
- `file->pathRel:string` (line 43)
- `file->pointer` (line 44)
- `file->readable:bool` (line 45)
- `file->src:string` (line 46)
- `file->size:int|false` (line 47)
- `file->sizeHuman(int $precision = 0):string` (line 48)
- `file->sha1:string|false` (line 49)
- `file->shortenTo(int $length):string` (line 50)
- `file->title:string` (line 51)
- `file->token($length = 20):string` (line 52)
- `file->type:string` (line 53)
- `file->touch:bool` (line 54)
- `file->writable:bool` (line 55)
- `file->writeINI($data, bool $deleteEmpty = false):bool` (line 56)
- `file->writeJSON($data, bool $deleteEmpty = false):bool` (line 57)
- `file->writeJSONplain($data, bool $deleteEmpty = false):bool` (line 58)
- `file->write(string $data, bool $deleteEmpty = false):bool` (line 59)
- `file->objInfo:array` (line 66)

### %ICS

Calendar files (iCalendar): events for a download, or a feed a calendar subscribes to

Advice: An event is an array or record with title and start, and optionally end, allDay, description, location, url and uid. A time is a timestamp or anything strtotime reads, and is written in UTC, so a calendar shows it in its own zone. An all-day end is the day after the last day, as the standard has it. Keep uid stable for an event that can change, because that is how a calendar recognises it on the next refresh; without one it follows from the title and the start. Behind a subscribe link a calendar has no login: put a token in the address.

- File: `resources/files/ICS.phlo`
- `ICS::text(iterable $events, string $name = void):string` (line 8)
- `ICS::download(iterable $events, string $filename, string $name = void)` (line 15)
- `ICS::feed(iterable $events, string $name = void)` (line 17)
- `ICS::event(array $event):array` (line 19)
- `ICS::escape(string $text):string` (line 39)
- `ICS::single(string $text):string` (line 42)
- `ICS::fold(string $line):string` (line 45)

### %img

GD image resource

Advice: Only scales down, never up: a request larger than the original returns the image untouched, so a thumbnail never looks stretched. The output format follows the extension you save to, so saving a .jpg writes JPEG at quality 85 whatever came in. Pass crop with a width and a height to fill the frame instead of fitting inside it, and top or bottom to choose which part survives. A JPEG is turned upright by its EXIF orientation when it is read, as a phone expects.

- File: `resources/files/img.phlo`
- `img::detect($data):?string` (line 8)
- `img::__handle` (line 18)
- `img->__construct(public string $file)` (line 19)
- `img->src:GdImage` (line 21)
- `img::upright(GdImage $image, string $file):GdImage` (line 26)
- `img->width:int` (line 33)
- `img->height:int` (line 34)
- `img->scale($width = null, $height = null, $crop = false):static` (line 36)
- `img->ext($file = null):string` (line 67)
- `img->source($format = null):string` (line 69)
- `img->save($file = null):bool` (line 75)
- `img->write($format = null, $file = null)` (line 80)

### %INI

Generic INI resource

Advice: The same shape as the JSON resource, saved when the object goes out of scope, but writing flattens the file: comments and section headers do not survive a round trip. Keep it to values a program owns; a file a person edits by hand deserves to be read rather than rewritten.

- File: `resources/files/INI.phlo`
- `INI->objFile:string` (line 8)
- `INI::__handle` (line 10)
- `INI->__construct(string $filename, ?string $path = null, bool $parse = true)` (line 11)
- `INI->objRead($parse = true)` (line 17)
- `INI->objWrite:int|false` (line 18)
- `INI->__destruct` (line 20)

### %JSON

Generic JSON resource

Advice: The file behaves as an object: read a key, write a key, and the file is saved when the object goes out of scope. That last part is the trap: nothing is written until then, so call objWrite() yourself when the request may end otherwise. Names are read against data/ and a slash in the name becomes a dot, so no name can escape the directory.

- File: `resources/files/JSON.phlo`
- `JSON::__handle` (line 9)
- `JSON->__construct(string $filename, ?string $path = null, $assoc = null)` (line 10)
- `JSON->objFile:string` (line 16)
- `JSON->objTouch:bool` (line 18)
- `JSON->objRead($assoc = null)` (line 19)
- `JSON->objWrite($data, $flags = null)` (line 20)
- `JSON->__destruct` (line 22)

### %PDF

PDF generator and reader

Advice: Two halves that share a name. Reading uses the pdftotext binary, so it needs poppler-utils on the machine and gives nothing on a scan without a text layer. Writing renders HTML through mPDF, and mode is the mPDF one: D sends a download, I shows it in the browser, S returns the bytes as a string, so leaving the default on an API route pushes a download at your caller.

- File: `resources/files/PDF.phlo`
- `PDF::toText(string $file):string` (line 8)
- `PDF->title:?string` (line 20)
- `PDF->author:?string` (line 21)
- `PDF->subject:?string` (line 22)
- `PDF->keywords:?string` (line 23)
- `PDF->creator:string` (line 24)
- `PDF->filename:string` (line 26)
- `PDF->mode:string` (line 27)
- `PDF->fromHTML($HTML):string` (line 29)

### %UBL

UBL 2.1 invoice XML (PEPPOL BIS Billing 3.0) from a normalized invoice structure. Use UBL::invoice($data).

Advice: Builds the invoice XML that PEPPOL expects from a plain array with supplier, customer and lines. Tax is grouped by rate and each group gets its own subtotal, so lines at 21 and 9 percent land in the right boxes on their own. It formats and escapes the amounts you hand it but checks nothing: a total that does not match its lines is written out as given, and a receiver will reject it.

- File: `resources/files/UBL.phlo`
- `UBL::invoice(array $data):string` (line 8)
- `UBL::xmlLine($idx, $line, $qty, $net, $rate, $currency = 'EUR'):string` (line 65)
- `UBL::partyXml($wrapper, $name, $info, $vatNumber):string` (line 80)
- `UBL::n($v):string` (line 101)
- `UBL::esc($v):string` (line 102)

### %upload

Upload progress for every form, and large files sent in parts that pick up where a break left them

Advice: Enabled, every request that carries a file reports its progress: the html element gets the class uploading and --upload from 0 to 1, and document receives an upload event with loaded, total and path, so a progress bar of your own is a few lines of CSS or script. For a file too large for one request, give its input data-upload: it is sent in parts of eight megabytes as soon as it is chosen, a part that fails is sent again, and choosing the same file after a break resumes it; the form then posts the upload's id under the input's name, and upload::take($id) in your route gives the file. A part goes only to the session that started the upload, every upload has a limit (prop max, 2 GB), and unfinished parts are removed after a day. What a file may be is yours to check after take(), with its mime and ext.

- File: `resources/files/upload.phlo`
- `upload->dir` (line 9)
- `upload->max` (line 10)
- `upload->canUpload` (line 12)
- `upload->owner` (line 15)
- `upload->meta(string $id):?array` (line 17)
- `upload->offset(string $id):int` (line 23)
- `route async POST upload` (line 26)
- `route async GET upload $id` (line 44)
- `route async PUT upload $id` (line 51)
- `upload::take(string $id):?file` (line 66)

### %XLSX

XLSX workbooks: read every sheet by name, write sheets that a spreadsheet will not run

Advice: Reads a workbook without a library by unpacking the zip itself, and gives every sheet by name with the first row as the header. Values arrive as the sheet stored them, so a date is the serial number Excel keeps and a percentage is a fraction; convert those yourself. Formulas give the last calculated value, so a sheet that was never opened after an edit hands you the old one. XLSX::write() and XLSX::download() make a workbook from sheets of rows, the keys of the first row as the header: a number is a number and all else is text, so a value can never become a formula.

- File: `resources/files/XLSX.phlo`
- `XLSX->__construct(string $file)` (line 14)
- `XLSX::text(string $xml):string` (line 77)
- `XLSX::write(string $file, array $sheets):void` (line 84)
- `XLSX::column(int $i):string` (line 109)
- `XLSX::download(array $sheets, string $filename):void` (line 111)

## payments

### %Mollie

Mollie connector: payments by iDEAL, Bancontact, card and the rest, with refunds

Advice: pay() starts a payment and Mollie::checkout($payment) is where you send the customer. Mollie then calls your webhook with only the id of the payment, and that is on purpose: ask payment($id) what happened instead of trusting what was posted. The webhook carries no cookie and no browser header, so the CSRF guard lets it through without an except. An amount is in euros or the currency you pass, never in cents. A test key (test_...) runs the whole flow without money.

- File: `resources/payments/Mollie.phlo`
- `Mollie::section` (line 10)
- `Mollie::api` (line 11)
- `Mollie->headers:array` (line 13)
- `Mollie::fields:array` (line 15)
- `Mollie::amount(int|float|string $amount, string $currency):array` (line 22)
- `Mollie->pay(int|float|string $amount, string $description, string $redirectUrl, ?string $webhookUrl = null, string $currency = 'EUR', array $metadata = [], ?string $method = null):obj` (line 27)
- `Mollie->payment(string $id):obj` (line 32)
- `Mollie->refund(string $id, int|float|string $amount, string $description = void, string $currency = 'EUR'):obj` (line 37)
- `Mollie->methods:obj` (line 42)
- `Mollie::checkout(obj $payment):?string` (line 48)
- `Mollie::paid(obj $payment):bool` (line 51)

### %Stripe

Thin Stripe wrappers: Checkout, Billing Portal, prices, customers, subscriptions and webhook verification. Call Stripe::boot($secret) first. Requires the Stripe PHP SDK (composer: stripe/stripe-php).

Advice: A thin layer over the Stripe SDK, which has to be installed and booted with Stripe::boot($secret) before anything else. Checkout and the billing portal are hosted by Stripe, so card details never touch your server. Verify a webhook before you read it: an unverified POST is a stranger claiming a payment, and verifyWebhook() is what turns it into a fact.

- File: `resources/payments/Stripe.phlo`
- `Stripe::boot($secret, $version = '2025-09-30.clover'):void` (line 8)
- `Stripe::price($lookupKey)` (line 15)
- `Stripe::customer($id)` (line 20)
- `Stripe::createCustomer(array $data)` (line 30)
- `Stripe::checkout(array $params)` (line 32)
- `Stripe::portal($customerId, $returnUrl)` (line 34)
- `Stripe::verifyWebhook($payload, $sigHeader, $secret)` (line 36)
- `Stripe::subscriptions($customerId, $status = 'all', $limit = 10)` (line 42)
- `Stripe::subscription($id)` (line 44)
- `Stripe::product($id)` (line 46)

### %SumUp

SumUp connector: card-present checkouts on paired Solo readers via the Cloud API, transaction lookup and history

Advice: Cloud-initiated terminal payments: the POS creates a checkout for a paired reader over HTTPS, the reader wakes up with the amount, and the result arrives on the return_url webhook or by polling transaction(). A checkout must start on the device within 60 seconds and only one checkout can be active per reader at a time. Treat the webhook as a wake-up call, never as the verdict: re-fetch the transaction with transaction() before recording a payment, so a forged POST can never book money.

- File: `resources/payments/SumUp.phlo`
- `SumUp::section` (line 10)
- `SumUp::api` (line 11)
- `SumUp->headers:array` (line 13)
- `SumUp::fields:array` (line 15)
- `SumUp->merchant:string` (line 24)
- `SumUp->readers:obj` (line 29)
- `SumUp->reader(?string $readerId = null):string` (line 34)
- `SumUp->createReaderCheckout(int $amountMinor, string $currency = 'EUR', ?string $readerId = null, ?string $description = null, ?string $returnUrl = null):obj` (line 39)
- `SumUp->terminateReaderCheckout(?string $readerId = null):obj` (line 52)
- `SumUp->transaction(string $clientTransactionId):obj` (line 62)
- `SumUp->transactions(array $query = []):obj` (line 67)

## security

### %account

Accounts on the app's own user model: sign in, stay signed in, activate and reset. Schema: resources/security/account.sql

Advice: account works on your user model (prop %account.model, default user) and its email and password columns (emailColumn, passwordColumn), so it adds no user table of its own. signIn() checks the password with a rate limit and an equal-time miss, renews the session id and upgrades the hash when PHP's default moves on; failure then says why it did not (unknown, inactive, throttled), so the message stays yours. user is the signed-in record, signOut() ends it. With remember, a rotating cookie keeps someone signed in across browser restarts. With activeColumn set, a record that is switched off is signed out on its next request, by session and by cookie alike. issue() makes a single-use token for an activation or reset link and claim() spends it: once, also when two requests bring it at the same moment, and a wrong secret leaves it for the person it was sent to. For a second factor with an authenticator app, enable security/totp, store totp::secret() on the user, show qr::svg(totp::uri($secret, $email)), and name the column in prop %account.totpColumn: signIn() then wants code: as well and fails with 'code' without it. Pages, texts and mail stay in the app: send the link with mail::send().

- File: `resources/security/account.phlo`
- `account->model` (line 9)
- `account->emailColumn` (line 10)
- `account->passwordColumn` (line 11)
- `account->activeColumn` (line 13)
- `account->totpColumn` (line 15)
- `account->rateStorage` (line 17)
- `account->rememberDays` (line 18)
- `account->failure` (line 19)
- `account->db` (line 20)
- `account->user` (line 23)
- `account->active($user):bool` (line 30)
- `account::hash(string $password):string` (line 32)
- `account->signIn(string $email, string $password, bool $remember = false, ?string $code = null):?object` (line 34)
- `account->fail(string $failure):null` (line 53)
- `account->spendCode($user, string $secret, string $code):bool` (line 59)
- `account->signOut:void` (line 69)
- `account->remember($user):void` (line 77)
- `account->fromCookie` (line 84)
- `account->issue($user, string $kind, int $hours = 48):string` (line 94)
- `account->claim(string $token, string $kind):?object` (line 101)
- `account->store(string $id, $user, string $kind, string $secret, int $hours):void` (line 103)
- `account->spend(string $id, string $kind, string $secret):?object` (line 108)

### %audit

Audit log for model mutations (opt-in via static idColumn/objAudit). Schema: resources/security/audit.sql

Advice: Off unless a model sets objAudit, and then every create, change and delete is written: an update as the difference between before and after, a create as the new row, a delete as the row that went. Pass exclude for columns you would rather not keep, a password hash or a token; the log outlives the record, so what goes in is a decision, not a detail. purge() is there because a log nobody prunes eventually costs more than the table it watches.

- File: `resources/security/audit.phlo`
- `audit::log($model, $action, $before = [], $after = [], $exclude = []):void` (line 8)
- `audit::diff($before, $after):array` (line 29)
- `audit::history($model, $recordId, $limit = 50):array` (line 38)
- `audit::byUser($model, $userId, $fromTs = 0, $limit = 100):array` (line 46)
- `audit::purge($model, $olderThanSeconds = 31536000)` (line 53)

### %captcha

Self-contained interactive slider-puzzle captcha (no external service). The server picks a secret gap position and renders the background plus a loose piece with GD; the client drags the piece into place. verify() checks the end position plus human drag behaviour (time, path, variation). Single-use and session-bound; the gap position never leaves the server.

Advice: Runs entirely on your own server, so no visitor is handed to a third party and nothing has to be disclosed in a privacy statement. The gap position never leaves the server, and it judges the drag as well as the endpoint, so a script that jumps straight to the answer is refused. verify() does not consume the puzzle: call consume() yourself, and only on success, or a failed attempt costs the visitor their challenge. It needs GD.

- File: `resources/security/captcha.phlo`
- `captcha::W` (line 9)
- `captcha::H` (line 10)
- `captcha::P` (line 11)
- `captcha::tol` (line 12)
- `captcha::ttl` (line 13)
- `captcha::issue:array` (line 15)
- `captcha::images($gapX, $gapY):array` (line 22)
- `captcha::verify($x, $telemetry):bool` (line 57)
- `captcha::consume:void` (line 78)
- `captcha->widget:string` (line 82)
- `captcha->field($bg, $piece, $gapY, $w, $h, $p)` (line 88)

### %creds

Credentials resolver from env and ini sources

Advice: One place for every secret, filled from data/creds.ini and from the environment, where PHLO__Section__key sets a value and PHLO_<HOST>__Section__key overrides it for one host, with <HOST> the request host uppercased and every other character an underscore. Values are wrapped so a var_dump or an error page shows stars instead of the secret. Keep the ini file out of the repository and let the environment win on a server.

- File: `resources/security/creds.phlo`
- `creds->__construct(?array $values = null)` (line 8)
- `creds->resolve:array` (line 15)
- `creds->loadINI(string $file):array` (line 23)
- `creds->envValues(bool $hostScoped = false):array` (line 29)
- `creds->hostKey:string` (line 48)
- `creds->envAssign(array &$target, array $parts, string $value):void` (line 54)
- `creds->merge(array &$base, array $add):void` (line 69)
- `creds->objGet($key)` (line 79)
- `creds->objInfo:array` (line 84)

### %CSRF

CSRF protection for every state-changing request of the app

Advice: Enabled, it guards the whole app before any route runs: a POST, PUT, PATCH or DELETE from a browser, which shows by a cookie, HTTP basic auth, an Origin or a Sec-Fetch-Site header, needs the session's token, which phlo.js sends as the X-CSRF-Token header and a plain form sends as a csrf field (%CSRF->field). Put %CSRF in your head view for the meta tag the frontend reads. A request with none of those, such as a webhook with a signature or an API call with a token from a server, is no browser and passes; except is for a post from another site's page or from the system, such as an OAuth provider posting back or a share target. A public form starts the session on its GET and carries %CSRF->field. update() answers with a fresh token the page applies, which makes a stolen token worth one request; verify() is there for a check of your own: it is true after the guard validated the token, also when it took a csrf field out of the payload, or when the request itself carries a valid token, as on an except path; without a token where the guard checked nothing, it is false. It protects a session, so it says nothing about an API authenticated with a bearer token. %CSRF in the head starts a session on every page it is on: each visitor, a crawler too, gets a session cookie and a session file, and under PHP's default cache limiter the page is sent no-store, so a public site without forms that change something can leave the resource off.

- File: `resources/security/CSRF.phlo`
- `CSRF->view` (line 10)
- `CSRF->field` (line 11)
- `CSRF->token:string` (line 12)
- `CSRF->except:array` (line 15)
- `CSRF->passed` (line 17)
- `CSRF->verify:bool` (line 18)
- `CSRF::beforeRoute` (line 21)
- `CSRF->update:array` (line 29)
- `CSRF::ambient:bool` (line 30)

### %JWT

Sign and verify compact HS256 JSON Web Tokens (RFC 7519), secure by default

Advice: HS256 only, and a token that claims another algorithm is refused rather than tried, which is the classic way these are broken. The secret must be at least 32 bytes, an expiry is always written, and verify() throws with a 401 instead of returning false, so a route can simply call it. Name an issuer and it is checked as well. A signed token is readable by anyone holding it, so keep secrets out of the claims.

- File: `resources/security/JWT.phlo`
- `JWT->__construct(public string $secret, public string $issuer = void, public int $leeway = 30)` (line 9)
- `JWT->sign(array $claims, int $ttl = 3600):string` (line 11)
- `JWT->verify(string $token):array` (line 20)
- `JWT->sig(string $body):string` (line 36)
- `JWT->encode($data):string` (line 37)
- `JWT->decode(string $data):string` (line 38)

### %OAuth2

Stateless OAuth2 client: build the authorize URL and exchange/refresh tokens. Token storage and config are the caller's responsibility. The protocol primitive under TokenStore and OAuthConnector.

Advice: The bare protocol: build an authorize URL, trade a code for tokens, refresh. It keeps nothing and knows nothing about your app, which is what makes it usable for any provider. For a connector you almost never need it directly, since TokenStore and OAuthConnector do the keeping for you; reach for it when you run the login yourself.

- File: `resources/security/OAuth2.phlo`
- `OAuth2::authorizeUrl($endpoint, array $params):string` (line 9)
- `OAuth2::token($tokenUrl, $clientId, $clientSecret, $grantType, array $extra = []):array` (line 11)
- `OAuth2::exchangeCode($tokenUrl, $clientId, $clientSecret, $code, $redirectUri = null, array $extra = []):array` (line 25)
- `OAuth2::refresh($tokenUrl, $clientId, $clientSecret, $refreshToken, array $extra = []):array` (line 27)

### %rate

Rate-limit (fixed window) on the rate_limit table. Schema: resources/security/rate.sql

Advice: A fixed window, counted in one atomic statement, so two requests arriving together cannot both slip past the limit. Storage db survives a restart and is shared across machines; apcu is faster but lives in one server's shared memory, so it is gone after a restart and says nothing about a second machine. Because the window is fixed rather than sliding, a caller can spend a full limit at the end of one window and again at the start of the next.

- File: `resources/security/rate.phlo`
- `rate::check($key, $limit, $windowSeconds, $storage = 'db'):bool` (line 9)
- `rate::checkApcu($key, $limit, $windowSeconds):bool` (line 19)
- `rate::status($key, $limit, $windowSeconds):obj` (line 26)
- `rate::reset($key)` (line 33)
- `rate::purge($olderThanSeconds = 604800)` (line 34)

### %security

Generic security resource

Advice: Pick a profile per app rather than writing headers yourself: strict allows only nonced scripts and styles, basic allows your own files, marketing also allows images from anywhere, and api shuts everything off and marks the response as an API. Async responses get no policy, because the page they land in already has one. Add a source per directive to allow, such as 'img-src' => ['https://cdn.example.com'], 'frame-src' => ['https://*.youtube.com'] or 'connect-src' => ['wss://example.com']; everything else stays closed. sandbox() is the profile for a file someone uploaded: it runs and loads nothing. Under debug, basic and marketing let inline scripts through so the debug console runs, so a production site with debug on is running a weaker policy than it thinks.

- File: `resources/security/security.phlo`
- `security->allow:array` (line 11)
- `security->setNonce:string` (line 13)
- `security->frameProtect($mode = 'DENY')` (line 15)
- `security->page:array` (line 18)
- `security->policy(array $directives):void` (line 33)
- `security->strict:void` (line 39)
- `security->basic:void` (line 48)
- `security->marketing:void` (line 53)
- `security->api:void` (line 58)
- `security->sandbox:void` (line 66)
- `security->base:void` (line 72)

### %social

Reusable social login (OIDC) on top of OAuth2: build the authorize URL and turn a callback code into a verified profile. Google, Microsoft and Apple. No user, session or route handling - that is the caller's responsibility.

Advice: The id_token is verified against the provider's JWKS (RS256 only, key looked up by kid) before any claim is read, on top of issuer, audience (must equal client_id), expiry and, when supplied, nonce. `verified` reports what the provider actually proved: Microsoft omits email_verified, so it counts only when the optional xms_edov claim states the tenant owns the address. Treat an unverified email as a claim, never as an identity: match users on provider + sub. Apple's client_secret is an ES256 JWT signed with the .p8 key (team_id/key_id/client_id + key from creds).

- File: `resources/security/social.phlo`
- `social::providers:array` (line 9)
- `social::config($provider):?array` (line 36)
- `social::configured($provider):bool` (line 48)
- `social::authUrl($provider, $state, $nonce = void):string` (line 53)
- `social::profile($provider, $code, $nonce = void):?array` (line 67)
- `social::decodeIdToken($jwt):?array` (line 84)
- `social::algs:array` (line 94)
- `social::verifySignature($provider, $jwt):bool` (line 96)
- `social::jwks($provider):array` (line 109)
- `social::key($provider, $kid):string` (line 123)
- `social::jwkToPem(array $jwk):string` (line 130)
- `social::der($tag, $content):string` (line 142)
- `social::derInt($bytes):string` (line 149)
- `social::b64urlDecode($data):string` (line 156)
- `social::verifyClaims($provider, array $cfg, array $claims, $nonce = void):bool` (line 163)
- `social::verifyIssuer($provider, array $claims):bool` (line 171)
- `social::normalize($provider, array $claims):array` (line 182)
- `social::b64url($data):string` (line 200)
- `social::appleSecret` (line 202)
- `social::derToJose($der):string` (line 220)
- `social::pad32($x):string` (line 228)

### %totp

Codes from an authenticator app (TOTP, RFC 6238): a secret, the link to scan and the check

Advice: secret() makes a secret to keep on the user, uri() is the otpauth: link an authenticator app reads (as a QR code, or typed in), and step() checks a code: one step either side is accepted, for a clock that drifts. It answers which step the code belongs to, so the caller can refuse the same code a second time; %account does that for you when its totpColumn is set.

- File: `resources/security/totp.phlo`
- `totp::secret:string` (line 8)
- `totp::uri(string $secret, string $label, string $issuer = host):string` (line 10)
- `totp::step(string $secret, string $code, ?int $time = null):?int` (line 12)
- `totp::code(string $key, int $step):string` (line 21)
- `totp::base32(string $bytes):string` (line 27)
- `totp::unbase32(string $text):string` (line 29)

### %webhook

Verify a signed webhook: a signature over the raw body, within a time window, handled once

Advice: Check the signature before you read anything from the body. hmac() is a signature over the body alone (GitHub and Meta send sha256= and hex); stripe(), slack() and standard() (Standard Webhooks, as Svix and Resend send it) also refuse a timestamp outside the window, five minutes by default, so a captured request cannot be sent again later. Each reads its header and the raw body itself and returns true or false; the answer is yours, usually a 400. once($id) is true the first time it sees a delivery id, so a retried event is handled once; it needs the apcu resource and lets everything through without it. A webhook carries no cookie and no browser header, so the CSRF guard lets it through without an except.

- File: `resources/security/webhook.phlo`
- `webhook::hmac(string $secret, string $header = 'X-Hub-Signature-256', string $algo = 'sha256'):bool` (line 10)
- `webhook::stripe(string $secret, int $tolerance = 300):bool` (line 17)
- `webhook::slack(string $secret, int $tolerance = 300):bool` (line 29)
- `webhook::standard(string $secret, int $tolerance = 300):bool` (line 36)
- `webhook::fresh(int $timestamp, int $tolerance):bool` (line 44)
- `webhook::matches(string $expected, array $given):bool` (line 46)
- `webhook::once(string $id, int $ttl = 86400):bool` (line 49)

### Functions

- `decrypt($encrypted, $key):string|false`: Encrypt and decrypt secretbox payloads using a key
- `encrypt($data, $key):string`: Encrypt and decrypt secretbox payloads using a key
- `token(int $length = 8, ?string $input = null):string`: Generate deterministic or random lowercase token

