Core

object

%binary

/phlo/resources/binary.phlo

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

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.

binaryreleaseinstallsingle-filecli
prop

%binary -> ini:array

line 10
Settings for the PHP inside, on top of the defaults: ['memory_limit' => '1G'].
[]
prop

%binary -> data:array

line 12
What in data/ belongs to the app and not to the place it runs: it goes along, and each new version overwrites it there.
['langs']
static

binary :: run (string $command):string

line 14
exec($command.' 2>&1', $lines, $code)
$code === 0 || error('It failed: '.$command.lf.implode(lf, $lines))
return implode(lf, $lines)
static

binary :: libraries (string $file, string $lib):void

line 21
The shared libraries a file wants, and the loader among them, copied once.
if (!preg_match_all('~(?:=>\s*|^\s*)(/\S+)~m', (string)shell_exec('ldd '.escapeshellarg($file).' 2>/dev/null'), $found)) return
is_dir($lib) || mkdir($lib, 0755, true)
foreach ($found[1] AS $path) is_file($target = $lib.basename($path)) || static::run('cp -L '.escapeshellarg($path).' '.escapeshellarg($target))
static

binary :: extensions (string $frankenphp, string $stage):array

line 28
The extensions this server loads from files: only the ones it can bring.
$code = 'echo json_encode([ini_get("extension_dir"), array_filter(array_map("trim", explode(",", (string)php_ini_scanned_files())))]);'
[$dir, $scanned] = json_decode(static::run(escapeshellarg($frankenphp).' php-cli -r '.escapeshellarg($code)), true)
$lines = []
foreach ($scanned AS $ini){
	if (!preg_match_all('~^\s*extension\s*=\s*"?([^"\s;]+)~m', (string)@file_get_contents($ini), $found)) continue
	foreach ($found[1] AS $name){
		$file = rtrim((string)$dir, slash).slash.basename($name)
		is_file($file) || is_file($file .= '.so') || error('No file for the extension '.$name)
		is_dir($stage.'ext') || mkdir($stage.'ext', 0755)
		copy($file, $stage.'ext/'.basename($file))
		static::libraries($file, $stage.'lib/')
		$lines[] = 'extension='.basename($file)
	}
}
return $lines
static

binary :: settings (array $extensions):string

line 46
$settings = [
	'memory_limit' => '512M',
	'post_max_size' => '1024M',
	'upload_max_filesize' => '1024M',
	'expose_php' => 'Off',
	'display_errors' => 'Off',
	'log_errors' => 'On',
	'date.timezone' => 'UTC',
	'opcache.enable' => '1',
	'opcache.validate_timestamps' => '0',
	'apc.enable_cli' => '1',
	...%binary->ini,
]
$lines = ['[PHP]', 'session.save_path="${PHLO_DATA}/sessions"', 'sys_temp_dir="${PHLO_DATA}/tmp"', 'upload_tmp_dir="${PHLO_DATA}/tmp"', 'curl.cainfo="${PHLO_RUN}/ca.pem"', 'openssl.cafile="${PHLO_RUN}/ca.pem"', 'extension_dir="${PHLO_RUN}/ext"']
foreach ($settings AS $key => $value) $lines[] = $key.'='.$value
return implode(lf, [...$lines, ...$extensions]).lf
static

binary :: entry:string

line 65
$composer = defined('composer') ? "\tcomposer: __DIR__.'/',\n" : void
return "<?php\nrequire __DIR__.'/engine/phlo.php';\n\nphlo_app(\n\tid: ".var_export(id, true).",\n\thost: getenv('PHLO_HOST') ?: 'localhost',\n\tapp: __DIR__.'/release/',\n\tdata: getenv('PHLO_DATA').'/',\n\tphp: __DIR__.'/release/',\n\tcli: getenv('PHLO_BINARY').' php',\n\tthread: PHP_SAPI !== 'cli',\n$composer);\n"
static

binary :: make (string $frankenphp, string $output = 'dist/app'):string

line 71
Run it from the app: php www/app.php binary::make /path/to/frankenphp dist/myapp
%req->cli || error('binary::make runs from the command line')
is_executable($frankenphp) || error('Not an executable: '.$frankenphp)
trim((string)shell_exec('command -v go')) === void && error('The launcher is built with Go, and it is not on this machine')
static::run(escapeshellarg(PHP_BINARY).space.escapeshellarg($_SERVER['SCRIPT_FILENAME']).' build::release')
is_dir(app.'release') || error('Name a release path in data/app.json')
$engine = dirname((new \ReflectionFunction('phlo_app'))->getFileName()).slash
$work = sys_get_temp_dir().'/phlo-binary-'.bin2hex(random_bytes(6)).slash
$stage = $work.'stage/'
mkdir($stage.'engine', 0755, true)
try {
	static::run('cp -a '.escapeshellarg(app.'release').space.escapeshellarg($stage.'release'))
	// What the build does not make, such as images, stays where a page asks for it; the build's own files win.
	is_dir(app.'www') && static::run('cp -an '.escapeshellarg(app.'www/.').space.escapeshellarg($stage.'release/www/'))
	static::run('find '.escapeshellarg($stage.'release/www').' -name "*.php" -delete')
	is_dir(app.'migrations') && static::run('cp -a '.escapeshellarg(app.'migrations').space.escapeshellarg($stage.'release/migrations'))
	foreach (['phlo.php', 'functions.php', 'error.php', 'classes', 'assets'] AS $part) static::run('cp -a '.escapeshellarg($engine.$part).space.escapeshellarg($stage.'engine/'))
	defined('composer') && static::run('cp -a '.escapeshellarg(composer.'vendor').space.escapeshellarg($stage.'vendor'))
	is_dir($stage.'seed') || mkdir($stage.'seed', 0755)
	foreach (%binary->data AS $own) file_exists(data.$own) && static::run('cp -a '.escapeshellarg(data.$own).space.escapeshellarg($stage.'seed/'))
	static::run('cp -L '.escapeshellarg($frankenphp).space.escapeshellarg($stage.'frankenphp'))
	static::libraries($frankenphp, $stage.'lib/')
	file_put_contents($stage.'php.ini', static::settings(static::extensions($frankenphp, $stage)))
	file_put_contents($stage.'entry.php', static::entry())
	is_file($certs = '/etc/ssl/certs/ca-certificates.crt') && copy($certs, $stage.'ca.pem')
	static::run('tar czf '.escapeshellarg($work.'bundle.tar.gz').' -C '.escapeshellarg($stage).' .')
	copy($engine.'resources/binary.go', $work.'main.go')
	file_put_contents($work.'go.mod', "module app\n\ngo 1.22\n")
	file_put_contents($work.'stamp', slug(id).'-'.substr(hash_file('sha256', $work.'bundle.tar.gz'), 0, 12).lf)
	$target = str_starts_with($output, slash) ? $output : app.$output
	is_dir(dirname($target)) || mkdir(dirname($target), 0755, true)
	static::run('cd '.escapeshellarg($work).' && CGO_ENABLED=0 go build -buildvcs=false -trimpath -ldflags "-s -w" -o '.escapeshellarg($target).' .')
	return $target.' ('.round(filesize($target) / 1048576).' MB)'
}
finally {
	foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($work, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST) AS $file) $file->isDir() && !$file->isLink() ? rmdir($file->getPathname()) : unlink($file->getPathname())
	rmdir($work)
}
object

%cookies

/phlo/resources/cookies.phlo

Cookies data object

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.

cookiessessionbrowserweb
method

%cookies -> controller

line 8
Deze controller haalt de huidige staat van cookies op en wijst deze toe aan de objData-eigenschap.
this->objData = $_COOKIE
prop

%cookies -> lifetimeDays:int

line 10
Stelt de levensduur van cookies in dagen in.
180
method

%cookies -> objSet ($key, $value, array $options = []):bool

line 12
Stelt een cookie in met de opgegeven sleutel en waarde, samen met optionele parameters voor vervaldatum, pad, beveiliging en SameSite-attributen.
$this->objData[$key] = $value
$_COOKIE[$key] = $value
$defaults = ['expires' => time() + $this->lifetimeDays * 86400, 'path' => slash, 'secure' => %req->secure, 'httponly' => true, 'samesite' => 'Lax']
setcookie($key, $value, array_merge($defaults, $options))
return true
method

%cookies -> __unset ($key):void

line 20
Verwijdert een cookie door deze uit de lokale objectgegevens en de globale $_COOKIE-array te verwijderen, en stelt de vervaldatum in op het verleden.
unset($this->objData[$key], $_COOKIE[$key])
$options = ['expires' => time() - 86400, 'path' => slash, 'secure' => %req->secure, 'httponly' => true, 'samesite' => 'Lax']
setcookie($key, void, $options)
object

%feed

/phlo/resources/feed.phlo

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

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.

feedatomrssblogxml
static

feed :: atom (string $title, iterable $items, ?string $link = null, ?string $subtitle = null):string

line 8
$link ??= %req->base.slash
// XML has no way to write a control character, and one in a title would make the whole feed unreadable.
$xml = fn($text) => htmlspecialchars(preg_replace('/[^\x09\x0A\x0D\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u', void, mb_scrub((string)$text, 'UTF-8')), ENT_XML1 | ENT_QUOTES, 'UTF-8');
$time = fn($value) => gmdate('Y-m-d\TH:i:s\Z', is_numeric($value) ? (int)$value : (int)strtotime((string)$value));
$entries = void
$latest = 0
foreach ($items AS $item){
	$item = (array)($item instanceof obj ? $item->objData : $item)
	$updated = is_numeric($item['updated']) ? (int)$item['updated'] : (int)strtotime((string)$item['updated'])
	$latest = max($latest, $updated)
	$entries .= tab.'<entry>'.lf
	$entries .= tab.tab.'<title>'.$xml($item['title']).'</title>'.lf
	$entries .= tab.tab.'<link href="'.$xml($item['link']).'"/>'.lf
	$entries .= tab.tab.'<id>'.$xml($item['id'] ?? $item['link']).'</id>'.lf
	$entries .= tab.tab.'<updated>'.$time($updated).'</updated>'.lf
	isset($item['author']) && $entries .= tab.tab.'<author><name>'.$xml($item['author']).'</name></author>'.lf
	isset($item['summary']) && $entries .= tab.tab.'<summary>'.$xml($item['summary']).'</summary>'.lf
	isset($item['content']) && $entries .= tab.tab.'<content type="html">'.$xml($item['content']).'</content>'.lf
	$entries .= tab.'</entry>'.lf
}
$out = '<?xml version="1.0" encoding="utf-8"?>'.lf.'<feed xmlns="http://www.w3.org/2005/Atom">'.lf
$out .= tab.'<title>'.$xml($title).'</title>'.lf
$subtitle === null || $out .= tab.'<subtitle>'.$xml($subtitle).'</subtitle>'.lf
$out .= tab.'<link href="'.$xml($link).'"/>'.lf.tab.'<link rel="self" href="'.$xml(%req->base.slash.%req->path).'"/>'.lf
$out .= tab.'<id>'.$xml($link).'</id>'.lf.tab.'<updated>'.$time($latest ?: time()).'</updated>'.lf
return $out.$entries.'</feed>'.lf
static

feed :: output (string $title, iterable $items, ?string $link = null, ?string $subtitle = null)

line 37
output(static::atom($title, $items, $link, $subtitle), type: 'application/atom+xml; charset=utf-8')
object

%lang

/phlo/resources/lang.phlo

Language and translation resource

%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.

langtranslationi18nai
function

function nl ($text, ...$args):string

line 9
Vertaal de gegeven tekst naar het Nederlands met de opgegeven argumenten voor opmaak.
%lang->translation('nl', $text, ...$args)
function

function en ($text, ...$args):string

line 10
Deze functie haalt een vertaling op voor de opgegeven tekst in het Engels, en kan optioneel worden opgemaakt met extra argumenten.
%lang->translation('en', $text, ...$args)
static

lang :: asyncBatch ($from, $to, $json):void

line 12
Voert een batchvertaling asynchroon uit, decodeert JSON-invoer en slaat de vertalingen op als deze succesvol zijn.
%app->lang = $to
$texts = json_decode($json, true)
$translations = $this->translateBatch($from, $to, $texts)
if ($translations) $this->save($to, $translations)
view

%lang -> view

line 19
Deze functie haalt de huidige taalinstelling van de applicatie op, waardoor lokalisatie van views mogelijk is.
%app->lang
prop

%lang -> model:string

line 21
Deze functie haalt het model op dat is gekoppeld aan de opgegeven taalidentificator.
'gpt-4o-mini'
prop

%lang -> instructions

line 22
Definieert een set instructies voor de Phlo programmeertaal.
void
static

lang :: fileCache:array

line 23
lang::$fileCache is een statische eigenschap die gecachete taaldocumenten opslaat voor efficiënte toegang tijdens runtime.
[]
prop

%lang -> batchLines:int

line 28
How much goes into one job, whichever cap is reached first.
50
prop

%lang -> batchChars:int

line 29
4000
prop

%lang -> pending:array

line 34
Phrases waiting for a job, keyed by source and target language, with their character count.
[]
prop

%lang -> pendingChars:array

line 35
[]
method

%lang -> collect ($from, $to, array $missing):void

line 40
Gathers missing phrases and hands over a batch once it is full.
$key = $from.'|'.$to
foreach ($missing AS $hash => $line){
	if (isset($this->pending[$key][$hash])) continue
	$length = strlen($line)
	// A line that no longer fits sends what is waiting first, so a batch never leaves over the cap.
	// One line longer than the cap cannot be split and goes on its own.
	if (($this->pending[$key] ?? null) && $this->pendingChars[$key] + $length > $this->batchChars) $this->flush($key)
	$this->pending[$key][$hash] = $line
	$this->pendingChars[$key] = ($this->pendingChars[$key] ?? 0) + $length
	if (count($this->pending[$key]) >= $this->batchLines || $this->pendingChars[$key] >= $this->batchChars) $this->flush($key)
}
method

%lang -> flush ($key):bool

line 57
Hands one batch over and forgets it.
$lines = $this->pending[$key] ?? []
unset($this->pending[$key], $this->pendingChars[$key])
if (!$lines) return false
$parts = explode('|', (string)$key, 2)
return $this->dispatch($parts[0], $parts[1] ?? $parts[0], json_encode($lines))
method

%lang -> flushAll:void

line 65
foreach (array_keys($this->pending) AS $key) $this->flush($key)
method

%lang -> dispatch ($from, $to, $json):bool

line 71
The one place that reaches the background, so a test can count jobs without a daemon or a process.
$this->translator && phlo_async('lang::asyncBatch', $from, $to, $json)
prop

%lang -> translator:bool

line 75
Whether the engine the model goes to is in the build and has a key. Each engine reads a key named
class_exists('AI') && class_exists($engine = phlo('AI')->resolve(model: $this->model)[0]) && class_exists('creds') && (string)(phlo('creds')->$engine ?? void) !== void
method

%lang -> __destruct

line 81
Where the tail of a batch leaves, at the end of every request.
try {
	$this->flushAll()
}
catch (\Throwable $e){}
method

%lang -> file ($lang):string

line 89
Where a language's translations live: the langs path when the app sets one, data/langs/ otherwise.
(defined('langs') ? langs : data.'langs/').$lang.'.ini'
method

%lang -> escape ($value):string

line 91
Escaped speciale tekens in een string voor veilige uitvoer in HTML, vervangend backslashes, dubbele aanhalingstekens en regeleinden met hun respectieve escape-sequenties.
strtr((string)$value, [bs => bs.bs, dq => bs.dq, lf => '\n'])
method

%lang -> unescape ($value):string

line 92
Deze functie ontsnapt een gegeven string door escape-sequenties te vervangen door hun overeenkomstige karakters.
strtr(strtr($value, [bs.bs => "\x01", bs.dq => dq, '\n' => lf]), ["\x01" => bs])
method

%lang -> lineValue ($line, $eq):string

line 94
Extraheert en verwerkt een lijnwaarde uit een gegeven string, verwijdert omringende aanhalingstekens indien aanwezig en ontsnapt speciale tekens.
$value = rtrim(substr($line, $eq + 3), cr.lf)
if (strlen($value) > 1 && $value[0] === dq && substr($value, -1) === dq) $value = substr($value, 1, -1)
return $this->unescape($value)
method

%lang -> readAll ($file):array

line 100
Leest alle sleutel-waarde paren uit een opgegeven bestand en retourneert deze als een associatieve array. Als het bestand niet bestaat of geen geldig bestand is, retourneert het een lege array.
$items = []
if (!is_file($file)) return $items
foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] AS $line){
	$eq = strpos($line, ' = ')
	if ($eq === false) continue
	$items[substr($line, 0, $eq)] = $this->lineValue($line, $eq)
}
return $items
method

%lang -> search ($file, $hash):?string

line 116
Finds one line with a binary search over the raw bytes of the translation file.
$size = (int)@filesize($file)
if (!$size) return null
$h = @fopen($file, 'rb')
if (!$h) return null
$lo = 0
$hi = $size
while ($hi - $lo > 4096){
	$mid = intdiv($lo + $hi, 2)
	fseek($h, $mid)
	fgets($h)
	$pos = ftell($h)
	if ($pos >= $hi){
		$hi = $mid
		continue
	}
	$line = (string)fgets($h)
	$eq = strpos($line, ' = ')
	if ($eq === false){
		$hi = $mid
		continue
	}
	$cmp = strcmp(substr($line, 0, $eq), $hash)
	if ($cmp < 0) $lo = ftell($h)
	elseif ($cmp > 0) $hi = $pos
	else {
		fclose($h)
		return $this->lineValue($line, $eq)
	}
}
fseek($h, $lo)
$value = null
while (ftell($h) < $hi && ($line = fgets($h)) !== false){
	$eq = strpos($line, ' = ')
	if ($eq === false) continue
	$cmp = strcmp(substr($line, 0, $eq), $hash)
	if ($cmp > 0) break
	if ($cmp === 0){
		$value = $this->lineValue($line, $eq)
		break
	}
}
fclose($h)
return $value
method

%lang -> lookup ($hash):?string

line 162
Zoekt een waarde in de taalbestanden cache op basis van de opgegeven hash en werkt de cache bij als het bestand is gewijzigd.
$file = $this->file(%app->lang)
$mtime = (int)@filemtime($file)
$cache =& static::$fileCache[$file]
if (!$cache || $cache['mtime'] !== $mtime) $cache = ['mtime' => $mtime, 'items' => []]
if (array_key_exists($hash, $cache['items'])) return $cache['items'][$hash]
$value = $this->search($file, $hash)
if ($value === null && $mtime) $value = $this->readAll($file)[$hash] ?? null
return $cache['items'][$hash] = $value
method

%lang -> save ($lang, $pairs):void

line 177
Writes the whole file under a temporary name and renames it into place.
$file = $this->file($lang)
is_dir(dirname($file)) || mkdir(dirname($file), 0775, true)
$items = $this->readAll($file)
foreach ($pairs AS $hash => $value) $items[$hash] = $value
ksort($items, SORT_STRING)
$out = void
foreach ($items AS $hash => $value) $out .= $hash.' = '.dq.$this->escape($value).dq.lf
$tmp = $file.'.'.getmypid().'.tmp'
file_put_contents($tmp, $out, LOCK_EX)
@chmod($tmp, 0664)
rename($tmp, $file)
unset(static::$fileCache[$file])
method

%lang -> transContext:string

line 192
Haal de context op van de app-auteur met betrekking tot het doel en het domein, indien beschikbaar; anders retourneert het void.
($instr = trim($this->instructions ?? void)) !== void ? lf.'Context from the app author about purpose and domain: '.$instr : void
prop

%lang -> browser:?string

line 194
Haal de voorkeurstaal uit de 'Accept-Language' HTTP-header, en retourneer de eerste overeenkomende taalcodes uit de ondersteunde talen van de applicatie.
last($langs = array_filter(explode(comma, %req->acceptLanguage), fn($lang) => isset(%app->langs[substr($lang, 0, 2)])), $langs ? substr(current($langs), 0, 2) : null)
method

%lang -> cookie:?string

line 195
($lang = %cookies->lang) && isset(%app->langs[$lang]) ? $lang : null
method

%lang -> detect ($text, $fallback = 'en'):string

line 196
if (!$this->translator) return $fallback
$res = phlo('AI')->chat (
	model: $this->model,
	system: 'Analyse which language this text is in and return only the ISO 639-1 code of the language, no other data!',
	user: $text.lf.lf.'The ISO 639-1 code of the language is: ',
	temperature: 0,
)->answer
return strlen($res) === 2 ? strtolower($res) : $fallback
method

%lang -> hash ($from, $text):string

line 206
Genereert een hash op basis van de opgegeven tekst en een voorvoegsel van de opgegeven taal.
$from.($short = substr(implode(regex_all('/[A-Za-z0-9]+/', ucwords($text))[0]), 0, 8)).substr(md5($text), 0, 10 - strlen($short))
method

%lang -> translation ($from, $text, ...$args):string

line 207
if ($from === %app->lang) $translation = strtr($text, ['\n' => lf])
else {
	$translation = []
	$missing = []
	foreach (explode(lf, $text) AS $line){
		if (trim($line)){
			$hash = $this->hash($from, $line)
			$item = $this->lookup($hash)
			if ($item === null) [$missing[$hash] = $item = $line, debug(%app->lang.': '.(mb_strlen($line) > 20 ? mb_substr($line, 0, 18).'...' : $line))]
		}
		else $item = void
		$translation[] = $item
	}
	if ($missing) $this->collect($from, %app->lang, $missing)
	$translation = implode(lf, $translation)
}
return $args ? sprintf($translation, ...$args) : $translation
method

%lang -> translate ($from, $to, $text):string

line 226
if ($from === $to) return $text
return phlo('AI')->chat (
	model: $this->model,
	system: "You will be provided with a word, sentence or (markdown) text in ISO 639-1 language $from, and your task is to translate this string into ISO 639-1 language $to. Respect markdown, missing interpunction and specific use of capitals. Give only the translation.".$this->transContext(),
	user: $text,
	temperature: 0,
)->answer
method

%lang -> translateBatch ($from, $to, $texts):array

line 235
if ($from === $to) return $texts
$hashes = array_keys($texts)
$numbered = implode(lf, array_map(fn($i, $t) => ($i + 1).'. '.$t, array_keys($values = array_values($texts)), $values))
$answer = phlo('AI')->chat (
	model: $this->model,
	system: "You will be provided with numbered lines in ISO 639-1 language $from. Translate each line into ISO 639-1 language $to. Return only the numbered translations in the same format. Respect markdown, missing interpunction and specific use of capitals.".$this->transContext(),
	user: $numbered,
	temperature: 0,
)->answer
$result = []
foreach (explode(lf, trim($answer)) AS $line){
	if (preg_match('/^(\d+)\.\s*(.+)/', $line, $m))
		$result[$hashes[(int)$m[1] - 1]] = $m[2]
}
return $result
object

%lang_address

/phlo/resources/lang.address.phlo

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

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.

langaddressurlslugi18n
static

lang_address :: default:string

line 9
The language without a prefix in the address: the first of %app->langs.
(string)(array_key_first((array)(%app->langs ?? [])) ?? %app->lang ?? 'en')
static

lang_address :: beforeRoute

line 12
A prefix sets the language and a translated slug reads back to its source path, before any route matches.
if (%req->cli || count((array)(%app->langs ?? [])) < 2) return
$parts = array_values(array_filter(explode(slash, %req->path), 'strlen'))
%app->lang = static::prefix($parts[0] ?? void) ? array_shift($parts) : (%req->async && %req->header('X-Phlo-Navigate') === null && static::prefix($page = explode(slash, ltrim((string)parse_url(%req->referer, PHP_URL_PATH), slash))[0]) ? $page : static::default())
%req->route = ltrim(%lang_address->source(slash.implode(slash, $parts), %app->lang), slash)
static

lang_address :: prefix (string $part):bool

line 19
$part !== static::default() && isset(%app->langs[$part])
method

%lang_address -> slug (string $path, string $lang):?string

line 21
(%app->slugs ?? [])[$path][$lang] ?? null
method

%lang_address -> source (string $path, string $lang):string

line 25
The source path of an address in a language. The longest slug that starts it wins, so /fr/pour/bar
$best = null
foreach (array_keys((array)(%app->slugs ?? [])) AS $source){
	$slug = $this->slug($source, $lang)
	if ($slug !== null && ($path === $slug || str_starts_with($path, rtrim($slug, slash).slash)) && strlen($slug) > strlen((string)$best?->slug)) $best = obj(source: $source, slug: $slug)
}
return $best ? $best->source.substr($path, strlen($best->slug)) : $path
method
line 36
The address of a source path in a language, the current one unless given: /pricing in French is
$lang ??= (string)%app->lang
$path = slash.ltrim($path, slash)
$best = null
foreach (array_keys((array)(%app->slugs ?? [])) AS $source){
	if (($path === $source || str_starts_with($path, rtrim($source, slash).slash)) && strlen($source) > strlen((string)$best) && $this->slug($source, $lang) !== null) $best = $source
}
$path = $best ? $this->slug($best, $lang).substr($path, strlen($best)) : $path
return $lang === static::default() ? $path : "/$lang".rtrim($path, slash)
object

%lastmod

/phlo/resources/lastmod.phlo

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

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.

seositemaplastmodbuildstamp
static

lastmod :: file ($dir = null):string

line 11
Where the map lives, beside the generated PHP so it travels with a release.
($dir ?: php).'lastmod.json'
prop

%lastmod -> sources:array

line 15
Sources the convention cannot find, as a uri to file path map.
[]
static

lastmod :: resolve ($uri):?string

line 18
The file most likely to render this page.
$slug = trim((string)$uri, slash)
$names = $slug === void ? ['home.phlo', 'page.home.phlo'] : [$slug.'.phlo', 'page.'.$slug.'.phlo', strtr($slug, [slash => dot]).'.phlo']
foreach ($names AS $name) if (is_file($file = app.$name)) return $file
return null
static

lastmod :: day ($file):?string

line 27
The day of the last commit that changed the file. A deploy or a checkout rewrites every mtime, so a file outside git,
if (!$file || !is_file($file)) return null
$git = 'git -C '.escapeshellarg(dirname($file)).space
[$day, $parents] = explode(tab, trim((string)@shell_exec($git.'log -1 --date=short --format='.perc.'cd'.perc.'x09'.perc.'P -- '.escapeshellarg(basename($file)).' 2>/dev/null'), lf).tab)
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $day)) return null
return $parents === void && trim((string)@shell_exec($git.'rev-parse --is-shallow-repository 2>/dev/null')) === 'true' ? null : $day
static

lastmod :: uriOf ($page):string

line 35
is_string($page) ? $page : (string)(is_array($page) ? ($page['uri'] ?? void) : ($page->uri ?? void))
static

lastmod :: stamp ($dir = null):array

line 37
$map = []
foreach ((array)(%app->pages ?? []) AS $page) ($d = static::day(static::resolve(static::uriOf($page)))) && $map[static::uriOf($page)] = $d
foreach ((array)%lastmod->sources AS $uri => $file) ($d = static::day($file)) && $map[$uri] = $d
ksort($map)
file_put_contents($target = static::file($dir), json_encode($map, jsonPretty))
return ['file' => $target, 'pages' => count($map)]
prop

%lastmod -> map:array

line 46
is_file($file = static::file()) ? (array)json_decode((string)file_get_contents($file), true) : []
method

%lastmod -> for ($uri):?string

line 48
$this->map[$uri] ?? null
object

%locale

/phlo/resources/locale.phlo

Numbers, money and dates the way a language writes them

%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.

localenumbermoneydatei18n
static

locale :: table

line 8
[
	'nl' => ['decimal' => ',', 'thousands' => '.', 'money' => '€ {n}', 'date' => '{d} {m} {y}', 'months' => ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december']],
	'en' => ['decimal' => '.', 'thousands' => ',', 'money' => '€{n}', 'date' => '{m} {d}, {y}', 'months' => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']],
	'de' => ['decimal' => ',', 'thousands' => '.', 'money' => '{n} €', 'date' => '{d}. {m} {y}', 'months' => ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']],
	'fr' => ['decimal' => ',', 'thousands' => ' ', 'money' => '{n} €', 'date' => '{d} {m} {y}', 'months' => ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre']],
	'es' => ['decimal' => ',', 'thousands' => '.', 'money' => '{n} €', 'date' => '{d} de {m} de {y}', 'months' => ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']],
	'it' => ['decimal' => ',', 'thousands' => '.', 'money' => '{n} €', 'date' => '{d} {m} {y}', 'months' => ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre']],
	'pt' => ['decimal' => ',', 'thousands' => ' ', 'money' => '{n} €', 'date' => '{d} de {m} de {y}', 'months' => ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro']],
]
method

%locale -> of (?string $lang = null):array

line 18
static::table()[$lang ?? %app->lang] ?? static::table()['en']
method

%locale -> number (int|float $value, int $decimals = 0, ?string $lang = null):string

line 20
number_format($value, $decimals, $this->of($lang)['decimal'], $this->of($lang)['thousands'])
method

%locale -> money (int|float $amount, string $currency = 'EUR', ?string $lang = null):string

line 22
$number = $this->number($amount, 2, $lang)
return $currency === 'EUR' ? strtr($this->of($lang)['money'], ['{n}' => $number]) : "$currency $number"
method

%locale -> date (int|string $time, ?string $lang = null):string

line 27
$ts = is_int($time) ? $time : strtotime($time)
$locale = $this->of($lang)
return strtr($locale['date'], ['{d}' => date('j', $ts), '{m}' => $locale['months'][date('n', $ts) - 1], '{y}' => date('Y', $ts)])
object

%mail

/phlo/resources/mail.phlo

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

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.

mailemailsmtpsendmailmimetransactional
static

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
An attachment is [name, content] or [name, content, mime type].
$config = ($section = %creds->mail) ? (array)$section->toArray : []
$from = static::line($from ?? $config['from'] ?? 'noreply@'.host)
$to = array_map([static::class, 'line'], (array)$to)
$cc = array_map([static::class, 'line'], $cc)
$bcc = array_map([static::class, 'line'], $bcc)
$title = static::line($subject)
$subject = static::encode($title)
$text ??= static::plain($html)
[$content, $body] = static::mime($text, $html, $attachments)
$headers = array_filter(['From: '.$from, $replyTo ? 'Reply-To: '.static::line($replyTo) : null, $cc ? 'Cc: '.implode(', ', $cc) : null, 'Date: '.date('r'), 'Message-ID: <'.bin2hex(random_bytes(12)).'@'.host.'>', 'MIME-Version: 1.0', $content])
$message = implode(nl, ['To: '.implode(', ', $to), 'Subject: '.$subject, ...$headers]).nl.nl.$body
return match ($config['transport'] ?? 'sendmail') {
	'smtp' => static::smtp($config, $from, [...$to, ...$cc, ...$bcc], $message),
	'resend' => static::resend($from, $to, $cc, $bcc, $replyTo, $title, $text, $html, $attachments),
	'graph' => static::graph($from, $to, $cc, $bcc, $replyTo, $title, $text, $html, $attachments),
	'log' => file_put_contents(data.'mail.log', date('c').lf.$message.lf.str_repeat(dash, 60).lf, FILE_APPEND | LOCK_EX) !== false,
	default => mail(implode(', ', $to), $subject, $body, implode(nl, [...$headers, ...($bcc ? ['Bcc: '.implode(', ', $bcc)] : [])]), '-f'.static::address($from)),
};
static

mail :: line ($value):string

line 32
A header value on one line: a CR or LF in input must not start a header of its own.
trim(preg_replace('/[\r\n]+/', space, (string)$value))
static

mail :: address (string $value):string

line 34
preg_match('/<([^>]+)>/', $value, $m) ? trim($m[1]) : trim($value)
static

mail :: encode (string $value):string

line 36
preg_match('/[^\x20-\x7e]/', $value) ? '=?UTF-8?B?'.base64_encode($value).'?=' : $value
static

mail :: mime (?string $text, ?string $html, array $attachments):array

line 41
The message as [its content headers, its body]: text, or text and HTML as alternatives, and
$part = fn($type, $content) => "Content-Type: $type\r\nContent-Transfer-Encoding: base64\r\n\r\n".chunk_split(base64_encode((string)$content));
$content = $html === null ? $part('text/plain; charset=utf-8', $text) : static::multipart('alternative', [$part('text/plain; charset=utf-8', $text), $part('text/html; charset=utf-8', $html)])
if ($attachments) $content = static::multipart('mixed', [$content, ...loop($attachments, fn($a) => $part(($a[2] ?? 'application/octet-stream').'; name="'.str_replace(['"', "\r", "\n"], void, (string)$a[0]).'"', $a[1]))])
return explode("\r\n\r\n", $content, 2)
static

mail :: plain (?string $html):string

line 49
The text part of a mail that was given only as HTML.
$html === null ? void : trim(html_entity_decode(strip_tags(preg_replace('/<br\s*\/?>|<\/p>/i', lf, $html))))
static

mail :: multipart (string $kind, array $parts):string

line 51
$boundary = bin2hex(random_bytes(16))
return "Content-Type: multipart/$kind; boundary=\"$boundary\"\r\n\r\n".loop($parts, fn($p) => "--$boundary\r\n$p\r\n", void)."--$boundary--\r\n"
static

mail :: smtp (array $config, string $from, array $recipients, string $message):bool

line 58
A conversation with an SMTP server: TLS from the start on 465, STARTTLS when offered, AUTH LOGIN
$host = (string)($config['host'] ?? 'localhost')
$port = (int)($config['port'] ?? 587)
$socket = @stream_socket_client(($port === 465 ? 'tls://' : 'tcp://').$host.colon.$port, $errno, $problem, 15) ?: error("SMTP $host:$port: $problem", 500)
$talk = function(?string $line, int ...$expect) use ($socket):string {
	$line === null || fwrite($socket, $line."\r\n")
	$reply = void
	while (($got = fgets($socket, 515)) !== false){
		$reply .= $got
		if (($got[3] ?? void) !== dash) break
	}
	in_array((int)substr($reply, 0, 3), $expect, true) || error('SMTP: '.trim($reply), 500)
	return $reply
};
$talk(null, 220)
$hello = $talk('EHLO '.host, 250)
$tls = $port === 465
if (!$tls && str_contains($hello, 'STARTTLS')){
	$talk('STARTTLS', 220)
	stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) || error('SMTP: TLS failed', 500)
	$talk('EHLO '.host, 250)
	$tls = true
}
if (($config['user'] ?? void) !== void){
	// Without TLS the password crosses the network as it is, also when someone in between hid STARTTLS.
	$tls || ($config['tls'] ?? void) === 'none' || error("SMTP $host:$port offers no TLS, so the password stays here; tls = none in [mail] sends it anyway", 500)
	$talk('AUTH LOGIN', 334)
	$talk(base64_encode((string)$config['user']), 334)
	$talk(base64_encode((string)($config['password'] ?? void)), 235)
}
$talk('MAIL FROM:<'.static::address($from).'>', 250)
foreach ($recipients AS $recipient) $talk('RCPT TO:<'.static::address($recipient).'>', 250, 251)
$talk('DATA', 354)
$talk(preg_replace('/^\./m', '..', $message)."\r\n.", 250)
$talk('QUIT', 221)
fclose($socket)
return true
static

mail :: resend (string $from, array $to, array $cc, array $bcc, ?string $replyTo, string $subject, ?string $text, ?string $html, array $attachments):bool

line 98
Through Resend's API, with the connector's key.
class_exists('Resend') || error('mail: the resend transport needs the Resend connector', 500)
$sent = Resend::make()->post('emails', array_filter(['from' => $from, 'to' => $to, 'cc' => $cc, 'bcc' => $bcc, 'reply_to' => $replyTo, 'subject' => $subject, 'text' => $text, 'html' => $html, 'attachments' => loop($attachments, fn($a) => ['filename' => (string)$a[0], 'content' => base64_encode((string)$a[1])])]))
return $sent->ok || error('mail: Resend refused: '.json_encode($sent->error ?? $sent->data), 500)
static

mail :: graph (string $from, array $to, array $cc, array $bcc, ?string $replyTo, string $subject, ?string $text, ?string $html, array $attachments):bool

line 105
Through Microsoft Graph, sent from the mailbox the from address names.
class_exists('MicrosoftGraph') || error('mail: the graph transport needs the MicrosoftGraph connector', 500)
$people = fn(array $list) => loop(array_values($list), fn($a) => ['emailAddress' => ['address' => static::address($a)]]);
$message = array_filter([
	'subject' => $subject,
	'body' => $html === null ? ['contentType' => 'Text', 'content' => $text] : ['contentType' => 'HTML', 'content' => $html],
	'toRecipients' => $people($to),
	'ccRecipients' => $people($cc),
	'bccRecipients' => $people($bcc),
	'replyTo' => $replyTo ? $people([$replyTo]) : null,
	'attachments' => loop($attachments, fn($a) => ['@odata.type' => '#microsoft.graph.fileAttachment', 'name' => (string)$a[0], 'contentType' => $a[2] ?? 'application/octet-stream', 'contentBytes' => base64_encode((string)$a[1])]),
])
$sent = MicrosoftGraph::make()->sendMail($message, static::address($from))
return $sent->ok || error('mail: Microsoft Graph refused: '.json_encode($sent->error ?? $sent->data), 500)
static

mail :: later (...$args):bool

line 123
The same mail, sent by a process of its own so the request does not wait for the transport. The
function_exists('phlo_async') || error('mail::later() needs phlo.async', 500)
is_dir($dir = data.'mail/') || mkdir($dir, 0700, true)
isset($args['attachments']) && $args['attachments'] = loop($args['attachments'], fn($a) => [$a[0], base64_encode((string)$a[1]), $a[2] ?? null])
json_write($file = $dir.bin2hex(random_bytes(8)).'.json', $args)
return phlo_async('mail::sendWaiting', $file)
static

mail :: sendWaiting (string $file):bool

line 131
$dir = realpath(data.'mail/')
$dir && realpath(dirname($file)) === $dir && str_ends_with($file, '.json') || error('mail: not a waiting mail', 400)
$claim = $dir.slash.basename($file, '.json').dot.time().'.sending'
if (!@rename($file, $claim)) return false
try {
	$args = json_read($claim, true)
	isset($args['attachments']) && $args['attachments'] = loop($args['attachments'], fn($a) => array_filter([$a[0], base64_decode((string)$a[1]), $a[2] ?? null], fn($v) => $v !== null))
	$sent = static::send(...$args)
}
finally {
	($sent ?? false) ? unlink($claim) : touch($claim) && rename($claim, $file)
}
return $sent
static

mail :: retry (int $olderThan = 3600):int

line 150
Sends what a failed attempt left behind, from a task or a cron line; only a message of at least
$sent = 0
foreach (glob(data.'mail/*.sending') ?: [] AS $claim) preg_match('/^(.+)\.(\d+)\.sending$/', $claim, $m) && (int)$m[2] < time() - $olderThan && @rename($claim, $m[1].'.json')
foreach (glob(data.'mail/*.json') ?: [] AS $file){
	try {
		if (filemtime($file) < time() - $olderThan && static::sendWaiting($file)) $sent++
	}
	catch (\Throwable $e){}
}
return $sent
object

%manifest

/phlo/resources/manifest.phlo

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

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().

manifestpwawebmanifestinstallstandalone
route

route GET manifest.json

line 8
if (!%manifest->body) return false
manifest::output(%manifest->body)
prop

%manifest -> body

line 13
null
prop

%manifest -> maxAge:int

line 14
60
static

manifest :: encode ($body):string

line 16
json_encode($body, jsonPretty)
static

manifest :: output ($body, $maxAge = null):void

line 18
%res->header('Cache-Control', 'public, max-age='.($maxAge ?? %manifest->maxAge))
output(static::encode($body), type: 'application/manifest+json')
view

%manifest -> view

line 23
manifest::encode(%manifest->body)
view

%manifest -> head

line 25
<link rel=manifest href=/manifest.json>
object

%manual

/phlo/resources/manual.phlo

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

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.

manualdocsreflectionai
static

manual :: instruction

line 9
'Summarise what this application does and what has changed recently. Write in the same language as the description, at most eight sentences, running text without lists or headings. Do not open with a sentence about what you are going to do.'
prop

%manual -> translate:bool

line 11
function_exists('en')
prop

%manual -> labels:array

line 12
arr(
	title:    'Manual',
	lead:     'This page comes from the source itself: the description, what the code exposes and the latest changes.',
	state:    'State',
	unknown:  'unknown',
	summary:  'In short',
	about:    'What this app is',
	files:    'Files',
	routes:   'Routes',
	changes:  'Recent changes',
	why:      'Why',
	own:      'Codebase',
	shared:   'Shared with the sibling app',
	noKey:    'No AI key is configured, so there is no summary. The rest of this page comes straight from the source and works without one.',
	noAnswer: 'The model returned nothing.',
	noSummary:'The summary could not be fetched: ',
	noInfo:   'This app does not carry a data/app.md yet.',
	noNodes:  'This file carries no nodes; it consists of markup or script.',
)
method

%manual -> label ($key):string

line 31
$this->translate ? en($this->labels[$key]) : $this->labels[$key]
static

manual :: appInfo:string

line 33
(string)(reflect::appInfo() ?: void)
static

manual :: commits (string $path, int $limit = 12):array

line 35
if (!$path || !is_dir($path)) return []
$field = perc.'x1f'
$record = perc.'x1e'
$format = perc.'h'.$field.perc.'ad'.$field.perc.'s'.$field.perc.'b'.$record
$command = 'git -C '.escapeshellarg($path).' log -'.(int)$limit.' --no-merges --date=iso --format='.$format.' 2>/dev/null'
$raw = (string)@shell_exec($command)
$out = []
foreach (array_filter(explode("\x1e", $raw), 'trim') AS $entry){
	$parts = explode("\x1f", trim($entry))
	if (count($parts) < 3) continue
	$when = strtotime($parts[1]) ?: 0
	$out[] = obj(
		hash: $parts[0],
		when: $when,
		date: $when ? date('d-m-Y H:i', $when) : $parts[1],
		subject: $parts[2],
		body: trim((string)($parts[3] ?? void)),
	)
}
return $out
static

manual :: repos:array

line 58
$path = app
$dirs = [%manual->label('own') => $path]
$config = json_decode((string)@file_get_contents($path.'data/app.json'), true)
foreach ((array)($config['paths']['resources'] ?? []) AS $dir){
	$dir = rtrim((string)$dir, slash).slash
	$label = is_dir($dir) ? static::dirLabel($dir) : void
	if ($label === void || isset($dirs[$label])) continue
	$dirs[$label] = $dir
}
$roots = []
$out = []
foreach ($dirs AS $label => $dir){
	$root = trim((string)@shell_exec('git -C '.escapeshellarg($dir).' rev-parse --show-toplevel 2>/dev/null'))
	if ($root === void || isset($roots[$root])) continue
	$roots[$root] = true
	$out[$label] = $dir
}
return $out
static

manual :: commitList (int $limit = 20):array

line 79
$all = []
foreach (static::repos() AS $label => $dir){
	foreach (static::commits($dir) AS $commit){
		$commit->origin = $label
		$all[] = $commit
	}
}
usort($all, fn($a, $b) => $b->when <=> $a->when)
return array_slice($all, 0, $limit)
static

manual :: head:string

line 91
$commits = static::commits(app, 1)
return (string)($commits[0]->hash ?? void)
static

manual :: routes:array

line 96
(array)reflect::compactRoutes()
static

manual :: routeGroups:array

line 98
$groups = []
foreach (static::routes() AS $route){
	$file = basename((string)($route['file'] ?? 'unknown'))
	$groups[$file][] = $route
}
ksort($groups)
return $groups
static

manual :: nodesByFile:array

line 108
if (isset(%req->docsNodes)) return (array)%req->docsNodes
$found = []
foreach (['route', 'view', 'static', 'method', 'prop'] AS $type){
	foreach ((array)reflect::find($type, null, true, 'all') AS $row){
		$row = (array)$row
		$file = basename((string)($row['file'] ?? void), '.phlo')
		if ($file === void) continue
		$found[$file][] = obj(
			type: $type,
			name: (string)($row['name'] ?? void),
			args: (string)($row['args'] ?? void),
			ret: (string)($row['type'] ?? void),
			summary: (string)($row['summary'] ?? void),
		)
	}
}
%req->docsNodes = $found
return $found
static

manual :: fileRow (string $file):obj

line 129
$meta = (new build_file($file))->meta
$key = basename($file, '.phlo')
return obj(
	name: basename($file),
	summary: trim((string)($meta['summary'] ?? void)),
	advice: trim((string)($meta['advice'] ?? void)),
	lines: count(file($file) ?: []),
	nodes: static::nodesByFile()[$key] ?? [],
)
static

manual :: sources:array

line 141
$path = app
$own = %manual->label('own')
$config = json_decode((string)@file_get_contents($path.'data/app.json'), true)
if (!is_array($config)) return []

$dirs = [$path => $own]
foreach ((array)($config['paths']['resources'] ?? []) AS $dir){
	$dir = rtrim((string)$dir, slash).slash
	if (!is_dir($dir)) continue
	$label = static::dirLabel($dir)
	if ($label !== void) $dirs[$dir] = $label
}

$groups = []
foreach ($dirs AS $dir => $label) $groups[$label] = []
foreach (glob($path.'*.phlo') ?: [] AS $file) $groups[$own][] = static::fileRow($file)
foreach ((array)($config['resources'] ?? []) AS $name){
	foreach ($dirs AS $dir => $label){
		if ($label === $own) continue
		$file = $dir.$name.'.phlo'
		if (!is_file($file)) continue
		$groups[$label][] = static::fileRow($file)
		break
	}
}
return array_filter($groups)
static

manual :: dirLabel (string $dir):string

line 170
$root = trim((string)@shell_exec('git -C '.escapeshellarg($dir).' rev-parse --show-toplevel 2>/dev/null'))
$marker = $root === void ? null : json_decode((string)@file_get_contents($root.slash.'layer.json'), true)
if (is_array($marker) && ($marker['docs'] ?? true) !== false){
	$label = trim((string)($marker['label'] ?? void))
	if ($label !== void) return $label
	preg_match('~^#\s+(.+)~m', (string)@file_get_contents($root.slash.'README.md'), $match)
	if (($label = trim((string)($match[1] ?? void))) !== void) return $label
}
if (str_starts_with(rtrim($dir, slash), rtrim(dirname(rtrim(app, slash)), slash))) return %manual->label('shared')
return void
static

manual :: cacheFile:string

line 183
data.'manual.json'
static

manual :: cached:?obj

line 185
$file = static::cacheFile()
if (!is_file($file)) return null
$row = json_decode((string)file_get_contents($file))
return $row instanceof \stdClass ? obj(...(array)$row) : null
static

manual :: configured:bool

line 192
if (!class_exists('AI') || !class_exists('creds')) return false
return (string)(%creds->OpenAI ?? void) !== void || (string)(%creds->Claude ?? void) !== void
static

manual :: appName:string

line 197
defined('id') ? (string)id : (string)%app->title
static

manual :: model:string

line 199
$set = class_exists('setting') ? (string)(setting::value('docs.model') ?: void) : void
return $set ?: 'gpt-5.4-mini'
static

manual :: summary:obj

line 204
$info = static::appInfo()
$head = $info === void ? void : md5($info)
$row = static::cached()
if ($row && (string)$row->hash === $head && $head !== void) return $row
if (!static::configured()) return obj(hash: $head, text: void, missing: true)

$lines = ['This is the description of the app:']
$lines[] = mb_substr(static::appInfo(), 0, 4000)
$lines[] = 'And these are the latest changes:'
foreach (static::commits(app) AS $commit) $lines[] = $commit->date.space.$commit->subject
try {
	$answer = phlo('AI')->chat(model: static::model(), system: static::$instruction, user: implode(lf, $lines))
	$text = trim((string)($answer->answer ?? void))
}
catch (\Throwable $e){
	return obj(hash: $head, text: void, error: mb_substr($e->getMessage(), 0, 200))
}
if ($text === void) return obj(hash: $head, text: void, error: %manual->label('noAnswer'))
@file_put_contents(static::cacheFile(), json_encode(['hash' => $head, 'text' => $text, 'written' => time()]))
return obj(hash: $head, text: $text)
static

manual :: pageFile:string

line 227
data.'manual.html'
static

manual :: store (string $body, string $page):bool

line 229
$mark = '<!-- manual '.md5($body).' -->'
$file = static::pageFile()
if (is_file($file) && str_contains((string)@file_get_contents($file), $mark)) return false
return (bool)@file_put_contents($file, preg_replace('~<meta name="csrf"[^>]*>\s*~', void, $page).lf.$mark.lf)
route

route both GET manual

line 236
%app->title = static::appName()
%app->css = []
%app->js = []
%app->defer = []
$body = %manual->page()
$page = view($body, title: %manual->label('title'), css: [], js: [], inline: true, ns: 'manual')
static::store($body, $page)
return $page
view

%manual -> page

line 247
<main.docs>
	<header.docs__head>
		<h1>{{ manual::appName() }}</h1>
		<p.docs__sub>{{ %manual->label('lead') }} {{ %manual->label('state') }} {{ static::head() ?: %manual->label('unknown') }}.</p>
	</header>
	<div#docs-summary>{{ %manual->summaryBlock }}</div>
	{{ %manual->infoBlock }}
	{{ %manual->filesBlock }}
	{{ %manual->routesBlock }}
	{{ %manual->commitsBlock }}
</main>
view

%manual -> summaryBlock

line 260
$row = static::summary()
if ($row->missing) return indentView(lf.'<section class="docs__box docs__box--quiet"><p>'.esc(%manual->label('noKey')).'</p></section>'.lf)
if ((string)($row->error ?? void) !== void) return indentView(lf.'<section class="docs__box docs__box--quiet"><p>'.esc(%manual->label('noSummary')).esc((string)$row->error).'</p></section>'.lf)
return indentView(lf.$this->summaryText($row).lf)
view

%manual -> summaryText ($row)

line 267
<section.docs__box>
	<h2>{{ %manual->label('summary') }}</h2>
	<p.docs__lead>{[ $row->text ]}</p>
</section>
view

%manual -> infoBlock

line 273
$info = static::appInfo()
if ($info === void) return indentView(lf.'<section class="docs__box"><p>'.esc(%manual->label('noInfo')).'</p></section>'.lf)
return indentView(lf.$this->infoText(markdown::html(preg_replace('~^#[^\n]*\n~', void, $info), 2)).lf)
view

%manual -> infoText (string $html)

line 279
<details.docs__box open>
	<summary.docs__summary>{{ %manual->label('about') }}</summary>
	<div.docs__md>
		$html
	</div>
</details>
view

%manual -> filesBlock

line 287
$groups = static::sources()
if (!$groups) return void
return indentView(lf.$this->filesTable($groups).lf)
view

%manual -> filesTable (array $groups)

line 293
<details.docs__box>
	<summary.docs__summary>{{ %manual->label('files') }} ({{ array_sum(array_map('count', $groups)) }})</summary>
	<foreach $groups AS $label => $files>
		<h3>{{ $label }} <span.docs__num>{{ count($files) }}</span></h3>
		<foreach $files AS $file>
			{{ %manual->fileNodes($file) }}
		</foreach>
	</foreach>
</details>
view

%manual -> fileNodes ($file)

line 304
<details.docs__file>
	<summary.docs__summary>
		<span.docs__mono>{[ $file->name ]}</span>
		<span.docs__filesum>{[ $file->summary ?: void ]}</span>
		<span.docs__num>{{ count($file->nodes) }}</span>
	</summary>
	<if $file->advice !== void>
		<p.docs__meta>{[ $file->advice ]}</p>
	</if>
	<if !$file->nodes>
		<p.docs__meta>{{ %manual->label('noNodes') }}</p>
	</if>
	<foreach $file->nodes AS $node>
		<div.docs__node>
			<span.docs__kind>{[ $node->type ]}</span>
			<span.docs__mono>{[ $node->name.($node->args !== void ? '('.$node->args.')' : void).($node->ret !== void ? ': '.$node->ret : void) ]}</span>
			<if $node->summary !== void>
				<p.docs__meta>{[ mb_substr($node->summary, 0, 240) ]}</p>
			</if>
		</div>
	</foreach>
</details>
view

%manual -> routesBlock

line 328
$groups = static::routeGroups()
if (!$groups) return void
return indentView(lf.$this->routesTable($groups).lf)
view

%manual -> routesTable (array $groups)

line 334
<details.docs__box>
	<summary.docs__summary>{{ %manual->label('routes') }} ({{ array_sum(array_map('count', $groups)) }})</summary>
	<foreach $groups AS $file => $routes>
		<h3>{{ $file }} <span.docs__num>{{ count($routes) }}</span></h3>
		<foreach $routes AS $route>
			{{ %manual->routeRow($route) }}
		</foreach>
	</foreach>
</details>
view

%manual -> routeRow (array $route)

line 345
$whole = (string)($route['route'] ?? void)
$space = strpos($whole, space)
$method = $space === false ? void : substr($whole, 0, $space)
$path = $space === false ? $whole : substr($whole, $space + 1)
return indentView(lf.$this->routeLine($method, $path, (string)($route['summary'] ?? void)).lf)
view

%manual -> routeLine (string $method, string $path, string $summary)

line 353
<div.docs__route>
	<span.docs__origin>{[ $method ?: 'GET' ]}</span>
	<span.docs__path>/{[ str_replace(space, slash, trim($path)) ]}</span>
	<if $summary !== void>
		<p.docs__meta>{[ $summary ]}</p>
	</if>
</div>
view

%manual -> commitsBlock

line 362
$commits = static::commitList()
if (!$commits) return void
return indentView(lf.$this->commitsList($commits).lf)
view

%manual -> commitsList (array $commits)

line 368
<details.docs__box>
	<summary.docs__summary>{{ %manual->label('changes') }} ({{ count($commits) }})</summary>
	<foreach $commits AS $commit>
		<article.docs__commit>
			<h4>{[ $commit->subject ]}</h4>
			<p.docs__meta>
				<span.docs__origin>{[ $commit->origin ]}</span>
				{[ $commit->date ]} &middot; <span.docs__mono>{[ $commit->hash ]}</span>
			</p>
			<if $commit->body !== void>
				<details.docs__more>
					<summary.docs__summary>{{ %manual->label('why') }}</summary>
					<pre.docs__pre>{[ $commit->body ]}</pre>
				</details>
			</if>
		</article>
	</foreach>
</details>
view

style

line 388
.docs {
	max-width: 54rem
	margin: 0 auto
	padding: 2rem 1.2rem 4rem
	font: 16px/1.6 system-ui, sans-serif
	color: #1d2126
}
.docs__head {
	margin-bottom: 1.4rem
}
.docs h1 {
	margin: 0 0 .3rem
	font-size: 1.5rem
}
.docs__sub {
	margin: 0 0 .9rem
	color: #68727d
	font-size: .92rem
}
.docs__box {
	margin: 0 0 1rem
	padding: 1rem 1.1rem
	border: 1px solid #e2e6ea
	border-radius: 10px
	background: #fff
}
.docs__box--quiet {
	background: #f6f8f9
	color: #68727d
	font-size: .92rem
}
.docs__box h2 {
	margin: 0 0 .5rem
	font-size: 1.05rem
}
.docs__summary {
	cursor: pointer
	font-weight: 600
	font-size: .98rem
	display: flex
	align-items: baseline
	gap: .5rem
	list-style: none
	\::-webkit-details-marker: display: none
}
.docs__summary::before {
	content: '\25b8'
	color: #9aa4ae
	font-weight: 400
	transition: transform .12s ease
}
.docs__file[open] > .docs__summary::before {
	transform: rotate(90deg)
}
.docs__lead {
	margin: 0 0 .8rem
}
.docs__md h2 {
	margin: 1.1rem 0 .4rem
	font-size: 1rem
}
.docs__md p, .docs__md ul {
	margin: 0 0 .7rem
}
.docs__md li.task {
	list-style: none
	margin-left: -1.1rem
}
.docs__md li.task::before {
	content: '\25cb\a0'
	color: #68727d
}
.docs__md li.done::before {
	content: '\25cf\a0'
	color: #1d2126
}
.docs__md table {
	width: 100%
	border-collapse: collapse
	font-size: .9rem
	margin: .4rem 0 1rem
}
.docs__md th, .docs__md td {
	padding: .28rem .5rem .28rem 0
	border-bottom: 1px solid #eef1f3
	vertical-align: top
}
.docs__md th {
	text-align: left
	color: #68727d
}
.docs__mono {
	font-family: ui-monospace, monospace
	font-size: .86rem
	white-space: nowrap
}
.docs__num {
	text-align: right
	color: #68727d
}
.docs h3, .docs__md h4 {
	margin: 1rem 0 .2rem
	font-size: .9rem
	color: #68727d
}
.docs__file {
	margin: .15rem 0
	padding: .3rem .5rem
	border: 1px solid #eef1f3
	border-radius: 8px
}
.docs__filesum {
	color: #68727d
	font-size: .86rem
	font-weight: 400
	margin-left: auto
	text-align: right
}
.docs__node {
	padding: .3rem 0 .3rem .8rem
	border-left: 2px solid #eef1f3
	margin: .3rem 0
}
.docs__kind {
	display: inline-block
	min-width: 4rem
	color: #68727d
	font-size: .78rem
	text-transform: uppercase
}
.docs__origin {
	display: inline-block
	margin-right: .4rem
	padding: .05rem .4rem
	border-radius: 4px
	background: #eef1f3
	color: #4a5560
	font-size: .74rem
	text-transform: uppercase
	letter-spacing: .02em
}
.docs__route {
	padding: .3rem 0
	border-bottom: 1px solid #eef1f3
}
.docs__path {
	font-family: ui-monospace, monospace
	font-size: .86rem
	word-break: break-word
}
.docs__commit {
	padding: .6rem 0
	border-bottom: 1px solid #eef1f3
}
.docs__commit h4 {
	margin: 0 0 .15rem
	font-size: .95rem
}
.docs__meta {
	margin: 0
	color: #68727d
	font-size: .84rem
}
.docs__pre, .docs__md pre {
	margin: .4rem 0 0
	padding: .6rem .7rem
	border-radius: 8px
	background: #f6f8f9
	font-family: ui-monospace, monospace
	font-size: .84rem
	white-space: pre-wrap
}
.docs__more {
	margin-top: .3rem
}
.docs__btn {
	padding: .35rem .8rem
	border: 1px solid #d6dade
	border-radius: 6px
	background: #fff
	font-size: .88rem
	cursor: pointer
}
object

%markdown

/phlo/resources/markdown.phlo

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

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.

markdownhtmltextparser
static

markdown :: html (string $md, int $top = 1):string

line 9
implode(lf, array_map(fn($block) => static::block($block, $top), static::blocks($md)))
static

markdown :: block (obj $block, int $top):string

line 11
return match ($block->type) {
	'heading' => tag('h'.min(6, $block->depth + $top - 1), static::inline($block->text)),
	'code' => tag('pre', tag('code', esc($block->text), class: $block->lang ? 'language-'.$block->lang : null)),
	'quote' => tag('blockquote', static::inline($block->text)),
	'hr' => '<hr>',
	'list' => tag($block->ordered ? 'ol' : 'ul', implode(loop($block->items, fn($item) => tag('li', static::inline((string)$item->text).implode(loop($item->blocks, fn($sub) => lf.static::block($sub, $top))), class: $item->checked === null ? null : ($item->checked ? 'task done' : 'task'))))),
	'table' => tag('table', tag('thead', tag('tr', implode(loop($block->head, fn($cell) => tag('th', static::inline($cell)))))).tag('tbody', implode(loop($block->rows, fn($row) => tag('tr', implode(loop($row, fn($cell) => tag('td', static::inline($cell))))))))),
	default => tag('p', static::inline($block->text)),
};
static

markdown :: blocks (string $md):array

line 23
$lines = explode(lf, str_replace(cr, void, $md))
$count = count($lines)
$blocks = []
$para = []
$i = 0
while ($i < $count){
	$line = $lines[$i]
	if (trim($line) === void){
		static::para($para, $blocks)
		$i++
		continue
	}
	if (preg_match('/^ {0,3}(`{3,}|~{3,})\s*([\w+-]*)/', $line, $match)){
		static::para($para, $blocks)
		$fence = '/^ {0,3}'.preg_quote($match[1][0], slash).'{3,}\s*$/'
		$body = []
		$i++
		while ($i < $count && !preg_match($fence, $lines[$i])){
			$body[] = $lines[$i]
			$i++
		}
		$i++
		$blocks[] = obj(type: 'code', text: implode(lf, $body), lang: $match[2] ?? void)
		continue
	}
	if (preg_match('/^ {0,3}(#{1,6})\s+(.*?)\s*#*$/', $line, $match)){
		static::para($para, $blocks)
		$blocks[] = obj(type: 'heading', depth: strlen($match[1]), text: trim($match[2]))
		$i++
		continue
	}
	if (preg_match('/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/', $line)){
		static::para($para, $blocks)
		$blocks[] = obj(type: 'hr')
		$i++
		continue
	}
	if (preg_match('/^ {0,3}>/', $line)){
		static::para($para, $blocks)
		$body = []
		while ($i < $count && preg_match('/^ {0,3}>\s?(.*)$/', $lines[$i], $match)){
			$body[] = $match[1]
			$i++
		}
		$blocks[] = obj(type: 'quote', text: trim(implode(lf, $body)))
		continue
	}
	if (str_contains($line, pipe) && preg_match('/^ {0,3}\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/', (string)($lines[$i + 1] ?? void))){
		static::para($para, $blocks)
		$head = static::cells($line)
		$rows = []
		$i += 2
		while ($i < $count && str_contains($lines[$i], pipe)){
			$rows[] = static::cells($lines[$i])
			$i++
		}
		$blocks[] = obj(type: 'table', head: $head, rows: $rows)
		continue
	}
	if (($marker = static::marker($line)) !== null){
		static::para($para, $blocks)
		$raw = []
		while ($i < $count){
			if (trim($lines[$i]) === void){
				if (static::breaks(static::marker((string)($lines[$i + 1] ?? void)), $marker)) break
				$raw[] = void
				$i++
				continue
			}
			$here = static::marker($lines[$i])
			if ($here === null && !preg_match('/^ {2,}\S/', $lines[$i])) break
			if ($here !== null && static::breaks($here, $marker)) break
			$raw[] = $lines[$i]
			$i++
		}
		$blocks[] = obj(type: 'list', ordered: $marker->ordered, items: static::items($raw, $marker->indent))
		continue
	}
	$para[] = $line
	$i++
}
static::para($para, $blocks)
return $blocks
static

markdown :: marker (string $line):?obj

line 109
if (!preg_match('/^( *)([*+-]|\d{1,9}\.)\s+/', $line, $match)) return null
return obj(indent: strlen($match[1]), ordered: ctype_digit($match[2][0]))
static

markdown :: breaks (?obj $here, obj $marker):bool

line 114
$here === null || ($here->indent <= $marker->indent && $here->ordered !== $marker->ordered)
static

markdown :: para (array &$para, array &$blocks):void

line 116
$text = trim(implode(lf, $para))
$para = []
if ($text !== void) $blocks[] = obj(type: 'para', text: $text)
static

markdown :: cells (string $line):array

line 122
array_map('trim', explode(pipe, trim(trim($line), pipe)))
static

markdown :: items (array $lines, int $indent):array

line 124
$groups = []
$group = null
foreach ($lines AS $line){
	if (preg_match('/^( *)([*+-]|\d{1,9}\.)\s+(.*)$/', $line, $match) && strlen($match[1]) <= $indent){
		if ($group !== null) $groups[] = $group
		$group = [$match[3]]
		continue
	}
	if ($group === null) continue
	$group[] = preg_replace('/^ {1,'.($indent + 2).'}/', void, $line)
}
if ($group !== null) $groups[] = $group
$items = []
foreach ($groups AS $group){
	$raw = trim(implode(lf, $group))
	$checked = null
	if (preg_match('/^\[([ xX])\]\s*(.*)$/s', $raw, $match)){
		$checked = strtolower($match[1]) === 'x'
		$raw = $match[2]
	}
	$sub = static::blocks($raw)
	$text = void
	if ($sub && $sub[0]->type === 'para') $text = array_shift($sub)->text
	$items[] = obj(text: $text, checked: $checked, blocks: $sub)
}
return $items
static

markdown :: inline (string $text):string

line 154
Code steps aside for the formatting, so emphasis or a link can hold code, as in **`dx()` in a request**, and code shows its own asterisks.
$code = []
$text = preg_replace_callback('/`+[^`]*`+/', function($m) use (&$code){
	$code[] = '<code>'.esc(trim($m[0], bt)).'</code>'
	return chr(0).(count($code) - 1).chr(0)
}, $text)
return preg_replace_callback('/\x00(\d+)\x00/', fn($m) => $code[$m[1]], static::format($text))
static

markdown :: format (string $text):string

line 163
$out = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', esc($text))
$out = preg_replace('/(?<![*\w])\*([^*\n]+)\*(?![*\w])/', '<em>$1</em>', $out)
// An image before a link, so the image inside [![alt](src)](href) is one before the link closes around it.
$out = preg_replace('/!\[([^\]]*)\]\(\s*((?:https?:|mailto:|[\/#])\S*?)\s*\)/', '<img src="$2" alt="$1">', $out)
$out = preg_replace('/\[([^\]]+)\]\(\s*((?:https?:|mailto:|[\/#])\S*?)\s*\)/', '<a href="$2">$1</a>', $out)
return static::autolink($out)
static
line 173
A bare http or https address outside a tag and outside a link becomes a link; the punctuation after it stays text.
preg_replace_callback('/(<a\b[^>]*>.*?<\/a>|<[^>]+>)|(&lt;)?(https?:\/\/(?:(?!&(?:lt|gt|quot);)[^\s<\x00])+)(&gt;)?/s', [static::class, 'autolinkOne'], $html)
static

markdown :: autolinkOne (array $m):string

line 175
if ($m[1] !== void) return $m[1]
$url = $m[3]
$tail = void
while (preg_match('/[.,;:!?]$/', $url) || (str_ends_with($url, ')') && !str_contains($url, '('))){
	$tail = substr($url, -1).$tail
	$url = substr($url, 0, -1)
}
$angled = $m[2] !== void && ($m[4] ?? void) !== void && $tail === void
return ($angled ? void : $m[2]).'<a href="'.$url.'">'.$url.'</a>'.$tail.($angled ? void : ($m[4] ?? void))
object

%mcp

/phlo/resources/mcp.phlo

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

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.

mcpaiagentstoolsjson-rpc
prop

%mcp -> models:array

line 10
What an agent may reach, as model => what it holds. The text is what the agent reads to choose a tool.
[]
prop

%mcp -> tools:array

line 12
Tools of your own, as name => arr(about: 'What it does', input: [column => field(...)], run: fn($args) => [...], readOnly: true).
[]
prop

%mcp -> instructions

line 13
null
prop

%mcp -> origins:array

line 15
Browser origins that may call, besides the app's own. A client outside a browser sends none.
[]
prop

%mcp -> canUse

line 17
($creds = %creds->mcp) && (string)$creds->token !== void && hash_equals((string)$creds->token, $this->bearer)
prop

%mcp -> bearer:string

line 18
preg_match('/^Bearer\s+(\S+)$/i', (string)%req->header('Authorization'), $m) ? $m[1] : void
static

mcp :: beforeRoute

line 21
A browser on an origin in prop origins asks first with OPTIONS, and reads an answer only with these headers.
if (%req->method !== 'OPTIONS' || %req->route !== 'mcp') return
%mcp->cors || output(void, code: 403, type: 'application/json')
%res->header('Access-Control-Allow-Methods', 'POST')
%res->header('Access-Control-Allow-Headers', 'Authorization, Content-Type, MCP-Protocol-Version, Mcp-Method, Mcp-Name')
output(void, code: 204, type: 'application/json')
method

%mcp -> cors:bool

line 29
$origin = %req->header('Origin')
if ($origin === null || $origin === %req->base) return true
if (!in_array($origin, $this->origins, true)) return false
%res->header('Access-Control-Allow-Origin', $origin)
%res->header('Vary', 'Origin')
return true
static

mcp :: versions

line 39
The first speaks with _meta on every request and no handshake; the others start with initialize.
['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']
prop

%mcp -> modern

line 40
false
route

route POST mcp

line 42
if (!$this->cors) return output(void, code: 403, type: 'application/json')
// No token is nobody, also for a canUse that looks one up: an empty column would match it.
if ($this->bearer === void || !$this->canUse){
	%res->header('WWW-Authenticate', 'Bearer')
	return output(void, code: 401, type: 'application/json')
}
$rpc = json_decode(%req->body, true)
if (!is_array($rpc) || array_is_list($rpc)) return $this->fail(null, $rpc === null ? -32700 : -32600, 'Invalid JSON-RPC', 400)
$id = $rpc['id'] ?? null
$method = (string)($rpc['method'] ?? void)
$params = is_array($rpc['params'] ?? null) ? $rpc['params'] : []
if (($rpc['jsonrpc'] ?? null) !== '2.0' || $method === void) return $this->fail($id, -32600, 'Invalid JSON-RPC', 400)
if (!array_key_exists('id', $rpc)) return output(void, code: 202, type: 'application/json')
if ($refused = $this->refused($method, $params)) return $this->fail($id, ...$refused)
$server = ['name' => (string)(%app->title ?? (defined('id') ? id : host)), 'version' => (string)(%app->version ?? '1.0')]
return match ($method) {
	'initialize' => $this->reply($id, array_filter(['protocolVersion' => in_array($params['protocolVersion'] ?? null, array_slice(static::versions(), 1), true) ? $params['protocolVersion'] : static::versions()[1], 'capabilities' => ['tools' => (object)[]], 'serverInfo' => $server, 'instructions' => $this->instructions])),
	'ping' => $this->reply($id, (object)[]),
	'server/discover' => $this->reply($id, array_filter(['resultType' => 'complete', 'supportedVersions' => static::versions(), 'capabilities' => ['tools' => (object)[]], 'instructions' => $this->instructions, 'ttlMs' => 60000, 'cacheScope' => 'private', '_meta' => ['io.modelcontextprotocol/serverInfo' => $server]])),
	'tools/list' => $this->reply($id, ['resultType' => 'complete', 'tools' => loop(array_keys($this->catalog), fn($name) => $this->describe($name)), 'ttlMs' => 60000, 'cacheScope' => 'private']),
	'tools/call' => $this->call($id, (string)($params['name'] ?? void), $params['arguments'] ?? []),
	default => $this->fail($id, -32601, "Method not found: $method", $this->modern ? 404 : 200),
};
route

route GET mcp

line 68
$this->notHere()
route

route DELETE mcp

line 69
$this->notHere()
method

%mcp -> notHere

line 71
%res->header('Allow', 'POST')
return output(void, code: 405, type: 'application/json')
method

%mcp -> reply ($id, $result)

line 77
One record with broken text must not cost the whole answer.
output(json_encode(['jsonrpc' => '2.0', 'id' => $id, 'result' => $result], jsonFlat | JSON_INVALID_UTF8_SUBSTITUTE), type: 'application/json')
method

%mcp -> fail ($id, int $code, string $message, ?int $status = null, ?array $data = null)

line 78
output(['jsonrpc' => '2.0', 'id' => $id, 'error' => array_filter(['code' => $code, 'message' => $message, 'data' => $data])], code: $status ?? ($this->modern ? 400 : 200))
method

%mcp -> refused (string $method, array $params):?array

line 82
A modern request carries its version in _meta and repeats version, method and tool name in headers,
$header = %req->header('MCP-Protocol-Version')
$meta = (array)($params['_meta'] ?? [])
$version = $meta['io.modelcontextprotocol/protocolVersion'] ?? null
$supported = ['supported' => static::versions(), 'requested' => $version ?? $header]
if ($header !== null && !in_array($header, static::versions(), true)) return [-32022, 'Unsupported protocol version', 400, $supported]
if ($version === null && $header !== static::versions()[0]) return null
$this->modern = true
if ($version === null || !is_array($meta['io.modelcontextprotocol/clientCapabilities'] ?? null)) return [-32602, 'A request carries its protocol version and client capabilities in _meta', 400]
if ($version !== static::versions()[0]) return [-32022, 'Unsupported protocol version', 400, $supported]
$name = (string)%req->header('Mcp-Name')
preg_match('/^=\?base64\?(.*)\?=$/', $name, $encoded) && $name = (string)base64_decode($encoded[1])
if ($header !== $version || %req->header('Mcp-Method') !== $method || ($method === 'tools/call' && $name !== (string)($params['name'] ?? void))) return [-32020, 'Header mismatch: the MCP headers do not match the body', 400]
return null
method

%mcp -> call ($id, string $name, $arguments)

line 98
if (!$tool = $this->catalog[$name] ?? null) return $this->fail($id, -32602, "Unknown tool: $name")
try {
	$data = $tool['run'](is_array($arguments) ? $arguments : [])
	return $this->reply($id, ['resultType' => 'complete', 'content' => [['type' => 'text', 'text' => json_encode($data, jsonFlat | JSON_INVALID_UTF8_SUBSTITUTE)]], 'structuredContent' => $data])
}
catch (\Throwable $e){
	// What the app refused is meant for the caller, like a 4xx in a page. Anything else may hold SQL or a path.
	$told = debug || ($e->getCode() >= 400 && $e->getCode() < 500)
	if (!$told){
		require_once engine.'error.php'
		phlo_error_log(phlo_error_id((string)%req->host, "mcp/$name", $e->getMessage()), "mcp/$name", $e->getMessage())
	}
	return $this->reply($id, ['resultType' => 'complete', 'content' => [['type' => 'text', 'text' => $told ? $e->getMessage() : 'The tool failed']], 'isError' => true])
}
method

%mcp -> describe (string $name):array

line 115
$tool = $this->catalog[$name]
return ['name' => $name, 'description' => $tool['about'], 'inputSchema' => $tool['input'], 'annotations' => ['readOnlyHint' => (bool)($tool['readOnly'] ?? false), 'destructiveHint' => (bool)($tool['destructive'] ?? false), 'idempotentHint' => (bool)($tool['readOnly'] ?? false), 'openWorldHint' => false]]
prop

%mcp -> catalog:array

line 121
Every tool, from the models and from the app. A rule that needs a record is checked when the tool is called.
$tools = []
foreach ($this->models AS $model => $about){
	$pk = $model::idColumn()
	$id = [$pk => ['type' => $model::idType() === 'int' ? 'integer' : 'string']]
	$fields = $this->schemas($this->writable($model, 'change'))
	$this->may($model, 'canView') && $tools[$model.'_list'] = ['about' => "List and search: $about", 'readOnly' => true, 'input' => $this->schema($this->listInput($model)), 'run' => fn($args) => $this->list($model, $args)]
	$this->may($model, 'canView') && $tools[$model.'_get'] = ['about' => "One record by its $pk: $about", 'readOnly' => true, 'input' => $this->schema($id, [$pk]), 'run' => fn($args) => $this->row($this->visible($model, $this->find($model, $args)))]
	$this->may($model, 'canCreate') && $tools[$model.'_create'] = ['about' => "Create a record: $about", 'input' => $this->schema($this->schemas($this->writable($model, 'create')), array_keys(array_filter($this->writable($model, 'create'), fn($f) => $f->required))), 'run' => fn($args) => $this->create($model, $args)]
	$this->may($model, 'canChange') && $fields && $tools[$model.'_change'] = ['about' => "Change the given columns of a record: $about", 'input' => $this->schema([...$id, ...$fields], [$pk]), 'run' => fn($args) => $this->change($model, $args)]
	$this->may($model, 'canDelete') && $tools[$model.'_delete'] = ['about' => "Delete a record: $about", 'destructive' => true, 'input' => $this->schema($id, [$pk]), 'run' => fn($args) => $this->delete($model, $args)]
}
foreach ($this->tools AS $name => $tool){
	$input = (array)($tool['input'] ?? [])
	foreach ($input AS $column => $field) $field->name ??= $column
	$tools[$name] = [...$tool, 'input' => $this->schema($this->schemas($input), array_keys(array_filter($input, fn($f) => $f->required))), 'run' => fn($args) => $this->custom($tool, $input, $args)]
}
return $tools
method

%mcp -> may (string $model, string $rule, $record = null):bool

line 142
A rule the model states without a record, such as canDelete = false, leaves the tool out.
if (!$record && method_exists($model, $rule) && (new \ReflectionMethod($model, $rule))->getNumberOfRequiredParameters()) return true
return (bool)($record ? $model::$rule($record) : $model::$rule())
method

%mcp -> readable (string $model):array

line 147
array_filter($model::fields(), fn($f) => $f->mcp !== false && ($f->objColumns || $f->sql) && !($f->record === false && $f->list === false))
method

%mcp -> writable (string $model, string $mode):array

line 148
array_filter($model::fields(), fn($f) => $f->mcp !== false && $f->objColumns && !in_array($f->type, ['child', 'many', 'virtual', 'file', 'image'], true) && !in_array($f->$mode, [false, 'label'], true))
method

%mcp -> schema (array $properties, array $required = []):array

line 150
array_filter(['type' => 'object', 'properties' => $properties ?: (object)[], 'required' => array_values($required), 'additionalProperties' => false], fn($v) => $v !== [])
method

%mcp -> schemas (array $fields):array

line 151
loop($fields, fn($field) => $this->fieldSchema($field))
method

%mcp -> fieldSchema ($field):array

line 153
$schema = match ($field->type) {
	'number', 'price' => ['type' => $field->decimals ? 'number' : 'integer'],
	'bool' => ['type' => 'boolean'],
	'parent' => ['type' => $field->obj::idType() === 'int' ? 'integer' : 'string'],
	default => ['type' => 'string'],
};
$schema['description'] = $field->title
($choices = $field->choices ?: $field->enum) && $schema['enum'] = array_map('strval', $field->choices ? array_keys($choices) : (array)$choices)
$schema['type'] === 'string' && $field->length && $schema['maxLength'] = (int)$field->length
$schema['type'] === 'string' && $field->pattern && $schema['pattern'] = (string)$field->pattern
return $schema
method

%mcp -> listInput (string $model):array

line 167
$columns = array_filter($this->readable($model), fn($f) => $f->objColumns)
$search = array_filter($columns, fn($f) => $f->search)
return array_filter([
	'filter' => ['type' => 'object', 'description' => 'Columns that must match: a value, or a list of values of which one must match', 'properties' => loop($columns, fn($f) => ['description' => $f->title]), 'additionalProperties' => false],
	'search' => $search ? ['type' => 'string', 'description' => 'Words to find in '.implode(', ', array_keys($search))] : null,
	'order' => ['type' => 'string', 'enum' => array_keys($columns)],
	'desc' => ['type' => 'boolean'],
	'page' => ['type' => 'integer', 'minimum' => 1],
	'size' => ['type' => 'integer', 'minimum' => 1, 'maximum' => 100],
])
method

%mcp -> row ($record):array

line 180
$row = []
foreach ($this->readable($record::class) AS $column => $field) foreach ($field->objColumns ?: [$column] AS $name) $row[$name] = $record->objData[$name] ?? null
$row[$pk = $record::idColumn()] = $record->objData[$pk] ?? null
$record->objHasMethod('view') && $row['_label'] = strip_tags((string)$record)
return $row
method

%mcp -> find (string $model, array $args)

line 188
$id = $args[$model::idColumn()] ?? null
is_scalar($id) || error($model::idColumn().' is required', 422)
return $model::record(...[$model::idColumn() => $id]) ?? error('Not found', 404)
method

%mcp -> visible (string $model, $record)

line 195
A rule that takes a record says no here as it does on a screen: to the agent, that record is not there.
$this->may($model, 'canView', $record) ? $record : error('Not found', 404)
method

%mcp -> written (string $model, $record):array

line 198
What a write answers: the record, or only that it worked for whom may write it but not read it.
$this->may($model, 'canView', $record) ? $this->row($record) : ['saved' => true, $model::idColumn() => $record->objData[$model::idColumn()] ?? null]
method

%mcp -> list (string $model, array $args):array

line 200
$columns = array_filter($this->readable($model), fn($f) => $f->objColumns)
$filter = (array)($args['filter'] ?? [])
($unknown = array_diff_key($filter, $columns)) && error('Not a column to filter on: '.implode(', ', array_keys($unknown)), 422)
[$where, $bindings] = $filter ? $model::DB()->named($model::$table, $filter) : [void, []]
if (($words = trim((string)($args['search'] ?? void))) !== void){
	$search = array_keys(array_filter($columns, fn($f) => $f->search)) ?: error('This model has no search fields', 422)
	$part = '('.loop($search, fn($c) => $model::$table.dot.$model::DB()->quoteId($c).' LIKE ?', ' OR ').')'
	$where = $where === void ? $part : "$where AND $part"
	array_push($bindings, ...array_fill(0, count($search), perc.strtr($words, [space => perc]).perc))
}
$order = (string)($args['order'] ?? void)
$order === void || isset($columns[$order]) || error("Not a column to order on: $order", 422)
$page = $model::objRecordPage(max(1, (int)($args['page'] ?? 1)), min(100, max(1, (int)($args['size'] ?? 25))), ...array_filter(['where' => $where, 'whereArgs' => $bindings, 'order' => $order === void ? void : $model::$table.dot.$model::DB()->quoteId($order).(($args['desc'] ?? false) ? ' DESC' : ' ASC')]))
$records = array_filter($page->records, fn($record) => $this->may($model, 'canView', $record))
return ['records' => array_values(array_map(fn($record) => $this->row($record), $records)), 'total' => $page->total, 'page' => $page->page, 'pages' => $page->pages]
method

%mcp -> fill (string $model, $record, array $args, string $mode):void

line 220
As a form does it in the CMS: a field with a parser of its own reads the payload, the others take the
$writable = $this->writable($model, $mode)
($unknown = array_diff_key($args, $writable)) && error('Not a column to write: '.implode(', ', array_keys($unknown)), 422)
%payload->objClear()->objImport(...$args)
foreach ($model::fields() AS $column => $field){
	if (in_array($field->type, ['child', 'many', 'virtual'], true)) continue
	$sent = isset($writable[$column]) && array_key_exists($column, $args)
	if ($field->objHasMethod('parse')) ($field->handle || $sent) && $field->parse($record)
	elseif ($sent) $record->$column = ($args[$column] === null || $args[$column] === void) ? $field->cleared : $args[$column]
}
method

%mcp -> invalid (string $model, array $values):void

line 232
$model::objRunValidation($values) || error(implode(lf, $model::objErrors()), 422)
method

%mcp -> create (string $model, array $args):array

line 236
$this->may($model, 'canCreate') || error('Not allowed', 403)
$record = new $model
$this->fill($model, $record, $args, 'create')
$this->may($model, 'canCreate', $record) || error('Not allowed', 403)
foreach ($this->writable($model, 'create') AS $column => $field) $field->required && $field->objColumns && ($record->objData[$column] ?? void) === void && error($field->title.' is required', 422)
$this->invalid($model, $record->objData)
// A record that lands outside the scope cannot be read back: then it was not written either.
return $this->written($model, $model::transaction(fn() => $model::create(...$record) ?? error('Not saved', 422)))
method

%mcp -> change (string $model, array $args):array

line 247
$record = $this->find($model, $args)
$this->may($model, 'canChange', $record) || error('Not allowed', 403)
unset($args[$model::idColumn()])
if (method_exists($model, 'objRefusal')) foreach (array_keys($args) AS $column) ($why = $record->objRefusal($column)) && error($why, 422)
$old = clone $record
$this->fill($model, $record, $args, 'change')
$this->invalid($model, $record->objChanges($old))
return $this->written($model, $model::transaction(fn() => $record->objSave() ?? error('Not saved', 422)))
method

%mcp -> delete (string $model, array $args):array

line 258
$record = $this->find($model, $args)
$this->may($model, 'canDelete', $record) || error('Not allowed', 403)
$pk = $model::idColumn()
$model::delete($pk.'=?', $record->objData[$pk])
return ['deleted' => true, $pk => $record->objData[$pk]]
method

%mcp -> custom (array $tool, array $input, array $args):array

line 266
($unknown = array_diff_key($args, $input)) && error('Not an argument: '.implode(', ', array_keys($unknown)), 422)
foreach ($input AS $column => $field){
	$value = $args[$column] ?? null
	($value === null || $value === void) && $field->required && error($field->title.' is required', 422)
	is_array($value) && $field->type !== 'multiselect' && error($field->title.' is one value, not a list', 422)
	($why = $field->objValidate($value)) && error($why, 422)
}
$data = $tool['run']($args)
return is_array($data) && !array_is_list($data) ? $data : ['result' => $data]
object

%offline

/phlo/resources/offline.phlo

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

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.

offlinepwaservice-workerqueuesync
prop

%offline -> shell:array

line 11
The pages in the cache from the first visit on; the first also answers for a page that was never opened.
['/']
prop

%offline -> pages:array

line 13
Path prefixes of the pages that stay readable once they were opened: ['orders', 'clients/'].
[]
prop

%offline -> queue:array

line 15
Path prefixes of the posts that wait in the queue without a line: ['note', 'order/'].
[]
prop

%offline -> assets:array

line 17
Files besides app.js and app.css that belong in the cache.
[]
prop

%offline -> owner:string

line 19
Who the cache and the queue belong to, such as a user id.
void
prop

%offline -> patience:int

line 21
How long a page waits for the network before its cached copy answers, in milliseconds.
3000
prop

%offline -> version:string

line 23
substr(md5(implode(comma, array_map(fn($file) => (string)@filemtime(www.$file), ['app.js', 'app.css', 'offline-sw.js']))), 0, 8)
view

%offline -> view

line 25
<meta name=offline data-version="$this->version" data-owner="{{ esc($this->owner) }}" data-queue="{{ esc(implode(comma, $this->queue)) }}">
route

route GET offline.json

line 28
What the service worker keeps, and what a page reads before it sends the queue: the token of this moment and who is signed in now.
%res->header('Cache-Control', 'no-store')
output(arr(csrf: class_exists('CSRF') ? phlo('CSRF')->token : null, owner: $this->owner, shell: $this->shell, pages: $this->pages, assets: $this->assets, patience: $this->patience))
static

offline :: beforeRoute

line 35
Every answer says who is signed in. A post from the queue says who it is from, and is refused here if that is someone
if (%req->cli) return
$for = %req->header('X-Offline-For')
if ($for !== null && rawurldecode($for) !== %offline->owner) error('Someone else is signed in', 409)
%res->header('X-Offline-Owner', rawurlencode(%offline->owner))
method

%offline -> update:array

line 43
For the answer to signing in or out, because the header above was set before that happened: apply(...%offline->update, location: '/')
unset($this->objProps['owner'])
return arr(offlineOwner: $this->owner)
static

offline :: once (callable $work, $db = null)

line 50
The work of a route in the queue, once per post: the mark and the work commit together, so a post that comes again does nothing.
if (!$id = substr((string)%req->header('X-Offline-Id'), 0, 36)) return $work()
$db ??= model::DB()
return $db->transaction(fn() => $db->query('INSERT'.$db->insertIgnore.' INTO offline_post (id, at) VALUES (?, ?)'.$db->insertOnConflict, $id, time())->rowCount() ? $work() : null)
static

offline :: at:int

line 57
When it happened by the clock of the device, for a post from the queue; never later than now.
min(time(), (int)(%req->header('X-Offline-At') ?? time()))
static

offline :: purge (int $olderThanSeconds = 2592000, $db = null):int

line 59
($db ?? model::DB())->delete('offline_post', 'at < ?', time() - $olderThanSeconds)
view

script

line 61
app.offline = (() => {
	const config = () => obj('meta[name="offline"]')?.dataset ?? {}
	// Without https or localhost a browser has no service worker, no cache and no ids: then this does nothing.
	if (typeof caches === 'undefined' || !crypto?.randomUUID) return {flush: async () => {}, items: async () => [], retry: async () => {}, drop: async () => {}}
	const tabs = typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel('phlo-offline')
	let waiting = 0
	let next = null
	let busy = false
	const store = (mode, work) => new Promise((resolve, reject) => {
		const open = indexedDB.open('phlo-offline', 1)
		open.onupgradeneeded = () => open.result.createObjectStore('queue', {keyPath: 'seq', autoIncrement: true})
		open.onerror = () => reject(open.error)
		open.onsuccess = () => {
			const tx = open.result.transaction('queue', mode)
			const request = work(tx.objectStore('queue'))
			tx.oncomplete = () => [open.result.close(), resolve(request.result)]
			tx.onerror = tx.onabort = () => [open.result.close(), reject(tx.error)]
		}
	})
	const items = () => store('readonly', queue => queue.getAll())
	const mine = item => item.owner === (config().owner ?? '')
	const tell = (type, detail = {}) => document.dispatchEvent(new CustomEvent('queue', {cancelable: true, detail: {type, ...detail}}))
	const show = async () => {
		waiting = (await items()).filter(item => !item.rejected && mine(item)).length
		obj('html').classList.toggle('queued', waiting > 0)
		objects('[data-offline-count]').forEach(el => el.textContent = waiting)
	}
	const lines = text => text.split('\n').flatMap(line => {
		try { return line ? [JSON.parse(line)] : [] }
		catch (e){ return [] }
	})
	const refresh = () => app.fetch(app.path + location.search, {headers: {'X-Requested-With': 'phlo'}}).then(response => response.text()).then(text => lines(text).forEach(({trans, state, ...cmds}) => apply(cmds, false, false))).catch(() => {})
	const owner = value => {
		const meta = obj('meta[name="offline"]')
		if (meta) meta.dataset.owner = value
		const seen = localStorage.getItem('phlo-offline-owner')
		if (seen === value) return
		localStorage.setItem('phlo-offline-owner', value)
		seen === null || caches.keys().then(keys => Promise.all(keys.filter(key => key.startsWith('phlo-offline-')).map(key => caches.delete(key)))).then(() => navigator.serviceWorker?.ready).then(ready => ready?.active?.postMessage('fill'))
	}
	const line = online => {
		const html = obj('html').classList
		const back = online && html.contains('offline')
		html.toggle('offline', !online)
		back && flush()
	}
	let last = null
	const hold = async (method, path, data, id = crypto.randomUUID()) => {
		const form = data instanceof FormData
		const item = {id, method, path, form, body: form ? [...data.entries()] : data, at: Math.floor(Date.now() / 1000), owner: config().owner ?? ''}
		// A second click on the same form: with a line the first request blocks it, here nothing does.
		const same = JSON.stringify([method, path, form ? item.body.map(([name, value]) => [name, typeof value === 'string' ? value : value.name]) : data])
		if (last?.same === same && Date.now() - last.at < 1000) return
		last = {same, at: Date.now()}
		await store('readwrite', queue => queue.add(item))
		await show()
		tabs?.postMessage('queued')
		tell('queued', {item})
	}
	const body = item => {
		if (!item.form) return item.body === null ? undefined : JSON.stringify(item.body)
		const data = new FormData
		item.body.forEach(([name, value]) => data.append(name, value))
		return data
	}
	const send = async item => {
		const headers = {'X-Requested-With': 'phlo', 'X-Offline-Id': item.id, 'X-Offline-At': String(item.at), 'X-Offline-For': encodeURIComponent(item.owner)}
		item.form || item.body === null || (headers['Content-Type'] = 'application/json')
		const response = await app.fetch(item.path, {method: item.method, body: body(item), headers})
		// 409 is another person signed in since this queue started: it waits for the one it belongs to.
		if (response.status >= 500 || response.status === 409) return false
		const text = await response.text()
		const answer = lines(text)
		answer.forEach(cmds => cmds.csrf && app.mod.csrf?.(cmds.csrf))
		// An answer that is no answer, such as a page after a redirect, did not say the work was done, so the post stays.
		const unread = response.redirected || (text.trim() !== '' && !answer.length)
		const error = answer.find(cmds => cmds.error)?.error ?? (response.status >= 400 ? 'HTTP ' + response.status : unread ? 'No answer that says it worked' : null)
		if (!error) return store('readwrite', queue => queue.delete(item.seq)).then(() => true)
		await store('readwrite', queue => queue.put({...item, rejected: error}))
		tell('rejected', {item, error})
		return null
	}
	const run = async () => {
		const open = (await items()).filter(item => !item.rejected)
		if (!open.length) return
		let me
		try { me = await (await fetch('/offline.json', {cache: 'no-store'})).json() }
		catch (e){ return line(false) }
		line(true)
		owner(me.owner)
		me.csrf && app.mod.csrf?.(me.csrf)
		let sent = 0
		for (const item of open.filter(item => item.owner === me.owner)){
			const result = await send(item).catch(() => (line(false), false))
			if (result === false) break
			result && sent++
		}
		await show()
		tabs?.postMessage(sent ? 'sent' : 'queued')
		sent && tell('sent', {count: sent}) && (document.activeElement?.closest('form') || refresh())
	}
	const once = async () => {
		if (busy) return
		busy = true
		try { await run() }
		finally { busy = false }
	}
	const flush = () => navigator.locks ? navigator.locks.request('phlo-offline', {ifAvailable: true}, lock => lock && once()) : once()
	const request = phlo.request
	phlo.request = (method, path, data = null, blocking = true, navigate = false) => {
		const mine = !['GET', 'QUERY'].includes(method) && (config().queue ?? '').split(',').some(prefix => prefix && path.replace(/^\/+/, '').startsWith(prefix))
		if (!mine) return request(method, path, data, blocking, navigate)
		if (!navigator.onLine || waiting > 0) return void hold(method, path, data)
		const id = next = crypto.randomUUID()
		const xhr = request(method, path, data, blocking)
		next = null
		xhr?.addEventListener('error', () => hold(method, path, data, id))
		xhr?.addEventListener('load', () => [502, 503, 504].includes(xhr.status) && hold(method, path, data, id))
		return xhr
	}
	app.requests.push(xhr => {
		next && xhr.setRequestHeader('X-Offline-Id', next)
		xhr.addEventListener?.('error', () => line(false))
		xhr.addEventListener?.('load', () => {
			const value = xhr.getResponseHeader('X-Offline-Owner')
			value === null || owner(decodeURIComponent(value))
			line(xhr.status < 500)
		})
	})
	if (obj('meta[name="offline"]')){
		'serviceWorker' in navigator && navigator.serviceWorker.register('/offline-sw.js?v=' + config().version).catch(() => {})
		owner(config().owner ?? '')
		addEventListener('online', () => line(true))
		addEventListener('offline', () => line(false))
		navigator.onLine || line(false)
		if (tabs) tabs.onmessage = e => [show(), e.data === 'sent' && !document.activeElement?.closest('form') && refresh()]
		setInterval(() => waiting && flush(), 30000)
		show().then(flush)
	}
	app.mod.offlineOwner = owner
	return {
		flush,
		items: () => items().then(list => list.filter(mine)),
		retry: seq => store('readonly', queue => queue.get(seq)).then(item => item && store('readwrite', queue => queue.put({...item, rejected: undefined}))).then(show).then(flush),
		drop: seq => store('readwrite', queue => queue.delete(seq)).then(show),
	}
})()
view

script

line 211
const CACHE = 'phlo-offline-' + (new URL(self.location).searchParams.get('v') ?? '0')
let config = null
let filling = null

const plain = async response => response.redirected ? new Response(await response.blob(), {status: response.status, headers: response.headers}) : response

const fill = async () => {
	const cache = await caches.open(CACHE)
	const answer = await fetch('/offline.json', {cache: 'no-store'})
	if (!answer.ok || answer.redirected) throw new Error('No settings to keep')
	const settings = await answer.clone().json()
	await cache.put('/offline.json', answer)
	config = settings
	await Promise.allSettled([...config.shell, ...config.assets, '/app.js', '/app.css'].map(path => fetch(path, {cache: 'reload'}).then(plain).then(response => response.ok && cache.put(path, response))))
}

const settings = async () => config ??= await (await caches.open(CACHE)).match('/offline.json').then(hit => hit?.json()).catch(() => null) ?? null

const answer = async (request, url) => {
	const set = await settings()
	if (!set){
		// The cache went while the server was away: it fills again as soon as that works.
		filling ??= fill().catch(() => {}).finally(() => filling = null)
		return fetch(request)
	}
	const asked = request.headers.get('X-Requested-With') === 'phlo'
	const page = asked || request.mode === 'navigate'
	const listed = page ? set.shell.includes(url.pathname) || set.pages.some(prefix => url.pathname.slice(1).startsWith(prefix)) : ['/app.js', '/app.css', ...set.assets].includes(url.pathname)
	if (!listed && request.mode !== 'navigate') return fetch(request)
	const full = url.pathname + url.search
	// A navigation and an async answer that kept the language of the page before are two answers to one address.
	const key = page && asked ? full + (url.search ? '&' : '?') + 'offline=' + (request.headers.get('X-Phlo-Navigate') ? 'navigate' : 'asked') : page ? full : url.pathname
	const cache = await caches.open(CACHE)
	const network = fetch(request).then(response => {
		listed && response.ok && cache.put(key, response.clone()).catch(() => {})
		// A page opened from within the app has to survive a reload too, and that is a whole page.
		listed && asked && response.ok && cache.match(full).then(hit => hit || fetch(full).then(plain).then(page => page.ok && cache.put(full, page))).catch(() => {})
		return response
	})
	const hit = await cache.match(key)
	if (!hit) return network.catch(async () => {
		if (request.mode === 'navigate') return await cache.match(set.shell[0]) || Response.error()
		// Opened as a whole page, asked for from within the app: the page knows where to go with the whole page.
		return asked && await cache.match(full) ? Response.json({location: location.origin + full}) : Response.error()
	})
	return Promise.race([network, new Promise(resolve => setTimeout(resolve, set.patience, hit))]).catch(() => hit)
}

self.addEventListener('install', event => event.waitUntil(fill().then(() => self.skipWaiting())))

self.addEventListener('activate', event => event.waitUntil(caches.keys()
	.then(keys => Promise.all(keys.filter(key => key.startsWith('phlo-offline-') && key !== CACHE).map(key => caches.delete(key))))
	.then(() => self.clients.claim())))

self.addEventListener('message', event => event.data === 'fill' && event.waitUntil(fill().catch(() => {})))

self.addEventListener('fetch', event => {
	const url = new URL(event.request.url)
	if (event.request.method !== 'GET' || url.origin !== location.origin || url.pathname === '/offline.json') return
	event.respondWith(answer(event.request, url))
})
object

%payload

/phlo/resources/payload.phlo

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

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.

payloadrequestuploadpostputpatchquery
method

%payload -> controller

line 9
contentType = %req->contentType
if (in_array(phlo('req')->method, ['POST', 'PUT', 'PATCH', 'QUERY']) && str_starts_with($contentType, 'application/json')){
$data = json_decode((string)file_get_contents('php://input'))
return $this->objData = is_object($data) ? get_object_vars($data) : (is_array($data) ? $data : [])
}
if ($_POST) loop($_POST, fn($value, $key) => $this->$key = $value)
elseif (in_array(phlo('req')->method, ['PUT', 'PATCH', 'QUERY']) && str_starts_with($contentType, 'application/x-www-form-urlencoded')){
$body = file_get_contents('php://input')
$data = []
parse_str($body, $data)
if ($data) loop($data, fn($value, $key) => $this->$key = $value)
}
elseif (in_array(phlo('req')->method, ['PUT', 'PATCH', 'QUERY']) && str_starts_with($contentType, 'multipart/form-data')){
$match = regex('/boundary="?([^";]+)"?/', $contentType)
if (!$match) return
$boundary = '--'.$match[1]
$arrays = []
$raw = file_get_contents('php://input')
foreach (explode($boundary, $raw) AS $part){
	if (!trim($part) || $part === '--' || !str_contains($part, nl.nl)) continue
	$headers = []
	[$rawHeaders, $body] = explode(nl.nl, $part, 2)
	foreach (explode(nl, trim($rawHeaders)) AS $header){
		if (str_contains($header, colon)){
			[$key, $value] = explode(colon, $header, 2)
			$headers[strtolower(trim($key))] = trim($value)
		}
	}
	if (!isset($headers['content-disposition'])) continue
	if (!preg_match('/name="([^"]+)"/', $headers['content-disposition'], $match)) continue
	$name = $match[1]
	$body = rtrim($body, nl)
	if ($body === void) $body = null
	$base = $name
	$keys = []
	$hasEmptyIndex = false
	if (preg_match('/^([^\[]+)((?:\[[^\]]*\])*)$/', $name, $m)){
		$base = $m[1]
		$brackets = $m[2]
		if ($brackets){
			preg_match_all('/\[([^\]]*)\]/', $brackets, $mm)
			$keys = $mm[1]
			$hasEmptyIndex = in_array(void, $keys, true)
		}
	}
	if ($hasEmptyIndex) $arrays[] = $base
	$assign = function($value) use ($base, $keys){
		if ($keys){
			if (!isset($this->objData[$base]) || !is_array($this->objData[$base])) $this->objData[$base] = []
			$ref =& $this->objData[$base]
			$count = count($keys)
			foreach ($keys AS $i => $k){
				$last = $i === $count - 1
				if ($k === void){
					if ($last) $ref[] = $value
					else {
						$ref[] = []
						end($ref)
						$idx = key($ref)
						$ref =& $ref[$idx]
					}
				}
				else {
					if ($last) $ref[$k] = $value
					else {
						if (!isset($ref[$k]) || !is_array($ref[$k])) $ref[$k] = []
						$ref =& $ref[$k]
					}
				}
			}
		}
		else $this->objData[$base] = $value
	};
	if (preg_match('/filename="([^"]*)"/', $headers['content-disposition'], $f)){
		if ($f[1] === void || $body === null){
			if (!$hasEmptyIndex) $assign(null)
			continue
		}
		$filename = $f[1]
		$file = %file(tempnam(sys_get_temp_dir(), 'phlo'), $filename, $body)
		$assign($file)
	}
	else $assign($body)
}
foreach ($this->objData AS $key => $val){
	if (str_ends_with($key, '[]')){
		unset($this->objData[$key])
		$this->objData[substr($key, 0, -2)] = is_array($val) ? array_values(array_filter($val, fn($v) => $v !== null)) : [$val]
	}
	elseif (!is_array($val) && substr($key, -2) === '[]') $this->objData[$key] = [$val]
}
foreach (array_unique($arrays) AS $key) if (!isset($this->objData[$key])) $this->objData[$key] = []
}
if ($_FILES) loop($_FILES, fn($f, $key) => $this->$key = is_array($f['name']) ? loop(array_keys($f['name']), fn($i) => $f['error'][$i] ? null : %file($f['tmp_name'][$i], $f['name'][$i], mime: $f['type'][$i], size: $f['size'][$i])) : ($f['error'] ? null : %file($f['tmp_name'], $f['name'], mime: $f['type'], size: $f['size'])))
object

%qr

/phlo/resources/qr.phlo

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

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.

qrcodesvg2faticketlabel
static

qr :: eccPerBlock

line 8
[
	'L' => [0, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
	'M' => [0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
	'Q' => [0, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
	'H' => [0, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
]
static

qr :: blocks

line 14
[
	'L' => [0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
	'M' => [0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
	'Q' => [0, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
	'H' => [0, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81],
]
static

qr :: svg (string $text, string $level = 'M', int $margin = 4, string $color = 'currentColor'):string

line 21
$rows = static::matrix($text, $level)
$path = void
foreach ($rows AS $y => $row){
	for ($x = 0, $size = count($row); $x < $size; $x++){
		if (!$row[$x]) continue
		for ($run = 1; $x + $run < $size && $row[$x + $run]; $run++);
		$path .= 'M'.($x + $margin).space.($y + $margin).'h'.$run.'v1h-'.$run.'z'
		$x += $run
	}
}
$box = count($rows) + 2 * $margin
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 '.$box.space.$box.'" role="img" shape-rendering="crispEdges"><path fill="'.esc($color).'" d="'.$path.'"/></svg>'
static

qr :: matrix (string $text, string $level = 'M', ?int $mask = null):array

line 38
The code as rows of true for dark, without the margin. The mask is the one that scores best,
isset(static::blocks()[$level]) || error("A QR level is L, M, Q or H, not $level")
$version = static::version(strlen($text), $level)
$size = $version * 4 + 17
$modules = array_fill(0, $size, array_fill(0, $size, false))
$function = $modules
static::functionPatterns($modules, $function, $version, $level)
static::place($modules, $function, static::codewords(static::data($text, $version, $level), $version, $level))
if ($mask === null){
	$best = PHP_INT_MAX
	foreach (range(0, 7) AS $try){
		$candidate = static::masked($modules, $function, $try, $level)
		if (($score = static::penalty($candidate)) < $best) [$best, $mask] = [$score, $try]
	}
}
return static::masked($modules, $function, $mask, $level)
static

qr :: capacity (int $version, string $level):int

line 56
intdiv(static::rawModules($version), 8) - static::eccPerBlock()[$level][$version] * static::blocks()[$level][$version]
static

qr :: rawModules (int $version):int

line 58
$result = (16 * $version + 128) * $version + 64
if ($version >= 2){
	$align = intdiv($version, 7) + 2
	$result -= (25 * $align - 10) * $align - 55
	if ($version >= 7) $result -= 36
}
return $result
static

qr :: version (int $bytes, string $level):int

line 69
The smallest version that holds the text: mode, length and bytes, rounded up to whole bytes.
foreach (range(1, 40) AS $version) if (intdiv(4 + ($version <= 9 ? 8 : 16) + $bytes * 8 + 7, 8) <= static::capacity($version, $level)) return $version
error('This text is too long for a QR code', 422)
static

qr :: data (string $text, int $version, string $level):array

line 74
$bits = '0100'.sprintf($version <= 9 ? '%08b' : '%016b', strlen($text))
foreach (str_split($text) AS $char) $text === void || $bits .= sprintf('%08b', ord($char))
$capacity = static::capacity($version, $level)
$bits .= str_repeat('0', min(4, $capacity * 8 - strlen($bits)))
$bits .= str_repeat('0', -strlen($bits) & 7)
$bytes = array_map('bindec', str_split($bits, 8))
for ($pad = 0xEC; count($bytes) < $capacity; $pad ^= 0xFD) $bytes[] = $pad
return $bytes
static

qr :: gfMultiply (int $x, int $y):int

line 85
$z = 0
for ($i = 7; $i >= 0; $i--){
	$z = ($z << 1) ^ (($z >> 7) * 0x11D)
	$z ^= (($y >> $i) & 1) * $x
}
return $z
static

qr :: divisor (int $degree):array

line 94
$result = array_fill(0, $degree, 0)
$result[$degree - 1] = 1
$root = 1
for ($i = 0; $i < $degree; $i++){
	for ($j = 0; $j < $degree; $j++){
		$result[$j] = static::gfMultiply($result[$j], $root)
		if ($j + 1 < $degree) $result[$j] ^= $result[$j + 1]
	}
	$root = static::gfMultiply($root, 2)
}
return $result
static

qr :: remainder (array $data, array $divisor):array

line 108
$result = array_fill(0, count($divisor), 0)
foreach ($data AS $byte){
	$factor = $byte ^ array_shift($result)
	$result[] = 0
	foreach ($divisor AS $i => $coefficient) $result[$i] ^= static::gfMultiply($coefficient, $factor)
}
return $result
static

qr :: codewords (array $data, int $version, string $level):array

line 119
The data in blocks, each with its error correction, read out across the blocks.
$blocks = static::blocks()[$level][$version]
$ecc = static::eccPerBlock()[$level][$version]
$raw = intdiv(static::rawModules($version), 8)
$short = $blocks - $raw % $blocks
$shortLength = intdiv($raw, $blocks)
$divisor = static::divisor($ecc)
$all = []
$at = 0
for ($i = 0; $i < $blocks; $i++){
	$length = $shortLength - $ecc + ($i < $short ? 0 : 1)
	$part = array_slice($data, $at, $length)
	$at += $length
	$tail = static::remainder($part, $divisor)
	if ($i < $short) $part[] = 0
	$all[] = [...$part, ...$tail]
}
$result = []
for ($i = 0, $count = count($all[0]); $i < $count; $i++){
	foreach ($all AS $j => $block) if ($i !== $shortLength - $ecc || $j >= $short) $result[] = $block[$i]
}
return $result
static

qr :: set (array &$modules, array &$function, int $x, int $y, bool $dark):void

line 143
$modules[$y][$x] = $dark
$function[$y][$x] = true
static

qr :: functionPatterns (array &$modules, array &$function, int $version, string $level):void

line 148
$size = count($modules)
for ($i = 0; $i < $size; $i++){
	static::set($modules, $function, 6, $i, $i % 2 === 0)
	static::set($modules, $function, $i, 6, $i % 2 === 0)
}
foreach ([[3, 3], [$size - 4, 3], [3, $size - 4]] AS [$cx, $cy]){
	for ($dy = -4; $dy <= 4; $dy++){
		for ($dx = -4; $dx <= 4; $dx++){
			$distance = max(abs($dx), abs($dy))
			if ($cx + $dx >= 0 && $cx + $dx < $size && $cy + $dy >= 0 && $cy + $dy < $size) static::set($modules, $function, $cx + $dx, $cy + $dy, $distance !== 2 && $distance !== 4)
		}
	}
}
$positions = static::alignment($version)
$last = count($positions) - 1
foreach ($positions AS $i => $cy){
	foreach ($positions AS $j => $cx){
		if (($i === 0 && $j === 0) || ($i === 0 && $j === $last) || ($i === $last && $j === 0)) continue
		for ($dy = -2; $dy <= 2; $dy++) for ($dx = -2; $dx <= 2; $dx++) static::set($modules, $function, $cx + $dx, $cy + $dy, max(abs($dx), abs($dy)) !== 1)
	}
}
static::format($modules, $function, 0, $level)
if ($version < 7) return
$rem = $version
for ($i = 0; $i < 12; $i++) $rem = ($rem << 1) ^ (($rem >> 11) * 0x1F25)
$bits = $version << 12 | $rem
for ($i = 0; $i < 18; $i++){
	$a = $size - 11 + $i % 3
	$b = intdiv($i, 3)
	static::set($modules, $function, $a, $b, (bool)(($bits >> $i) & 1))
	static::set($modules, $function, $b, $a, (bool)(($bits >> $i) & 1))
}
static

qr :: alignment (int $version):array

line 183
if ($version === 1) return []
$count = intdiv($version, 7) + 2
$step = $version === 32 ? 26 : (int)ceil(($version * 4 + 4) / ($count * 2 - 2)) * 2
$result = [6]
for ($position = $version * 4 + 10; count($result) < $count; $position -= $step) array_splice($result, 1, 0, [$position])
return $result
static

qr :: format (array &$modules, array &$function, int $mask, string $level):void

line 192
$data = ['L' => 1, 'M' => 0, 'Q' => 3, 'H' => 2][$level] << 3 | $mask
$rem = $data
for ($i = 0; $i < 10; $i++) $rem = ($rem << 1) ^ (($rem >> 9) * 0x537)
$bits = ($data << 10 | $rem) ^ 0x5412
$size = count($modules)
$bit = fn($i) => (bool)(($bits >> $i) & 1);
for ($i = 0; $i <= 5; $i++) static::set($modules, $function, 8, $i, $bit($i))
static::set($modules, $function, 8, 7, $bit(6))
static::set($modules, $function, 8, 8, $bit(7))
static::set($modules, $function, 7, 8, $bit(8))
for ($i = 9; $i < 15; $i++) static::set($modules, $function, 14 - $i, 8, $bit($i))
for ($i = 0; $i < 8; $i++) static::set($modules, $function, $size - 1 - $i, 8, $bit($i))
for ($i = 8; $i < 15; $i++) static::set($modules, $function, 8, $size - 15 + $i, $bit($i))
static::set($modules, $function, 8, $size - 8, true)
static

qr :: place (array &$modules, array $function, array $data):void

line 209
$size = count($modules)
$i = 0
$total = count($data) * 8
for ($right = $size - 1; $right >= 1; $right -= 2){
	if ($right === 6) $right = 5
	for ($vertical = 0; $vertical < $size; $vertical++){
		for ($j = 0; $j < 2; $j++){
			$x = $right - $j
			$y = (($right + 1) & 2) === 0 ? $size - 1 - $vertical : $vertical
			if (!$function[$y][$x] && $i < $total){
				$modules[$y][$x] = (bool)(($data[$i >> 3] >> (7 - ($i & 7))) & 1)
				$i++
			}
		}
	}
}
static

qr :: masked (array $modules, array $function, int $mask, string $level):array

line 228
foreach ($modules AS $y => $row){
	foreach ($row AS $x => $dark){
		if ($function[$y][$x]) continue
		$flip = match ($mask) {
			0 => ($x + $y) % 2,
			1 => $y % 2,
			2 => $x % 3,
			3 => ($x + $y) % 3,
			4 => (intdiv($x, 3) + intdiv($y, 2)) % 2,
			5 => $x * $y % 2 + $x * $y % 3,
			6 => ($x * $y % 2 + $x * $y % 3) % 2,
			7 => (($x + $y) % 2 + $x * $y % 3) % 2,
		};
		if ($flip === 0) $modules[$y][$x] = !$dark
	}
}
static::format($modules, $function, $mask, $level)
return $modules
static

qr :: penalty (array $modules):int

line 251
The score the standard gives a mask: long runs, blocks, what looks like a finder, and an
$size = count($modules)
$score = 0
$dark = 0
$lines = $modules
for ($x = 0; $x < $size; $x++) $lines[] = array_column($modules, $x)
foreach ($lines AS $line){
	$text = implode(array_map(fn($m) => $m ? '1' : '0', $line))
	preg_match_all('/0{5,}|1{5,}/', $text, $runs)
	foreach ($runs[0] AS $run) $score += strlen($run) - 2
	$score += 40 * preg_match_all('/(?=10111010000|00001011101)/', $text)
}
for ($y = 0; $y < $size; $y++){
	for ($x = 0; $x < $size; $x++){
		$modules[$y][$x] && $dark++
		if ($x + 1 < $size && $y + 1 < $size && $modules[$y][$x] === $modules[$y][$x + 1] && $modules[$y][$x] === $modules[$y + 1][$x] && $modules[$y][$x] === $modules[$y + 1][$x + 1]) $score += 3
	}
}
$total = $size * $size
return $score + 10 * ((int)ceil(abs($dark * 20 - $total * 10) / $total) - 1)
object

%seo

/phlo/resources/seo.phlo

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

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.

seositemaprobotshreflangopengraphmultilingual
route

route GET sitemap.xml

line 9
Deze route genereert een sitemap voor SEO-doeleinden wanneer deze via een GET-verzoek wordt benaderd.
output($this)
route

route GET robots.txt

line 11
Definieert een route die reageert op GET-verzoeken door de inhoud van het robots-bestand in platte tekstformaat met UTF-8-charset uit te geven.
output($this->robots(), type: 'text/plain; charset=utf-8')
method

%seo -> robots:string

line 13
Genereert de inhoud van een robots.txt-bestand op basis van de instellingen van de applicatie, waarbij wordt gespecificeerd welke gebruikersagenten zijn toegestaan of geweerd bij het toegang krijgen tot bepaalde paden, en voegt een link naar de sitemap toe.
if (!(defined('indexable') && indexable)) return 'User-agent: *'.lf.'Disallow: /'.lf
$lines = ['User-agent: *', 'Allow: /']
foreach ((array)(%app->robotsDisallow ?? []) AS $path) $lines[] = 'Disallow: '.$path
$lines[] = 'Sitemap: '.%req->base.slash.'sitemap.xml'
return implode(lf, $lines).lf
method

%seo -> address (string $uri, string $lang):string

line 23
The address of a page in a language. lang.address knows the slugs per language and the prefix;
class_exists('lang_address') ? %lang_address->link($uri ?: slash, $lang) : ($lang === %app->lang ? ($uri ?: slash) : "/$lang".((%app->slugs ?? [])[$uri] ?? $uri))
prop

%seo -> defaultLang:string

line 24
class_exists('lang_address') ? lang_address::default() : (string)(%app->lang ?? 'en')
prop

%seo -> here:string

line 26
The page's own path in the source language, which the alternates in the head start from.
slash.%req->route
prop

%seo -> alternates:bool

line 27
!$this->noLink && count($this->sitemapLangs) > 1 && class_exists('lang_address')
method

%seo -> uri ($page):string

line 32
A sitemap entry is a uri string, or an object carrying that uri plus more.
is_string($page) ? $page : (string)($this->field($page, 'uri') ?? void)
method

%seo -> field ($page, $key):mixed

line 34
if (is_string($page)) return null
return is_array($page) ? ($page[$key] ?? null) : ($page->$key ?? null)
method

%seo -> lastmod ($page):?string

line 44
The date for one entry, or nothing at all when it does not parse.
$mod = $this->field($page, 'lastmod')
($mod === null || $mod === void) && class_exists('lastmod') && $mod = %lastmod->for($this->uri($page))
if ($mod === null || $mod === void) return null
if (is_string($mod) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $mod)) return $mod
$ts = is_int($mod) ? $mod : strtotime((string)$mod)
return $ts ? date('c', $ts) : null
method

%seo -> locale:string

line 53
Deze functie haalt de locale-code op die overeenkomt met de taalinstelling van de applicatie, met 'en' als standaard als deze niet is ingesteld.
$lang = %app->lang ?? 'en'
$map = ['nl' => 'nl_NL', 'en' => 'en_US', 'de' => 'de_DE', 'fr' => 'fr_FR', 'es' => 'es_ES', 'it' => 'it_IT', 'pt' => 'pt_PT', 'pl' => 'pl_PL', 'ru' => 'ru_RU', 'el' => 'el_GR', 'tr' => 'tr_TR', 'zh' => 'zh_CN']
return $map[$lang] ?? $lang
prop

%seo -> ogTitle:string

line 59
Dit haalt de Open Graph-titel op voor SEO-doeleinden met behulp van de title() functie.
title()
prop

%seo -> ogDescr

line 60
Haal de beschrijving van de applicatie op, retourneert void als deze niet is ingesteld.
%app->description ?? void
prop

%seo -> ogImageFile:string

line 61
(string)(%app->image ?? (is_file(www.'icon.webp') ? 'icon.webp' : void))
prop

%seo -> ogImage:string

line 62
$this->ogImageFile === void ? void : %req->base.slash.ltrim($this->ogImageFile, slash)
prop

%seo -> canonical:string

line 63
Dit haalt de canonical URL op voor SEO-doeleinden uit het aanvraagobject.
%req->url
prop

%seo -> ogType:string

line 64
Stelt het Open Graph-type in voor SEO-doeleinden, specifiek op 'website'.
'website'
prop

%seo -> sitemapPages:array

line 65
(array)(%app->pages ?? [''])
prop

%seo -> sitemapLangs:array

line 66
array_keys((array)(%app->langs ?? []))
prop

%seo -> siteName:string

line 67
Deze expressie wijst de waarde van de titel van de app of de id toe aan de variabele $siteName voor SEO-doeleinden.
%app->title ?? id
prop

%seo -> twitterCard:bool

line 68
De seo->$twitterCard eigenschap wordt gebruikt om de Twitter Card metadata voor een view te configureren, waardoor een betere integratie met Twitter deelfunctionaliteiten mogelijk is.
false
prop

%seo -> structuredData

line 73
Schema.org data for this page, as '@type' plus what only your app knows.
%app->structuredData ?? null
method

%seo -> schemaData:?array

line 75
if (!$this->structuredData) return null
$base = [
	'@context' => 'https://schema.org',
	'url' => $this->canonical,
	'inLanguage' => %app->lang ?? 'en',
	'mainEntityOfPage' => ['@type' => 'WebPage', '@id' => $this->canonical],
	'publisher' => ['@type' => 'Organization', 'name' => $this->siteName, 'url' => %req->base],
]
$this->ogDescr && $base['description'] = $this->ogDescr
$this->ogImage && $base['image'] = $this->ogImage
return array_replace($base, (array)$this->structuredData)
prop

%seo -> noIndex:bool

line 92
Whether this response belongs in a search index.
!(defined('indexable') && indexable) || %res->status >= 400 || (%app->noIndex ?? false) || (%app->noLink ?? false)
prop
line 94
Whether this response has a public address worth pointing at, for hreflang alternates.
!(defined('indexable') && indexable) || (%app->noLink ?? false)
view

%seo -> view

line 96
<?xml version=1.0 encoding="UTF-8"?>
<urlset xmlns=http://www.sitemaps.org/schemas/sitemap/0.9 xmlns:xhtml=http://www.w3.org/1999/xhtml xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=http://www.sitemaps.org/schemas/sitemap/0.9+http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd>
	<foreach $this->sitemapPages AS $page>
		{{ $this->page($page) }}
	</foreach>
</urlset>
view

%seo -> page ($page)

line 104
<url>
	<loc>%req->base{[ ($uri = $this->uri($page)) ?: slash ]}</loc>
	<if $stamp = $this->lastmod($page)>
		<lastmod>$stamp</lastmod>
	</if>
	<foreach $this->sitemapLangs AS $lang>
		<if $lang === $this->defaultLang>
			{{ $this->xlink('x-default', $this->address($uri, $lang)) }}
		</if>
		{{ $this->xlink($lang, $this->address($uri, $lang)) }}
	</foreach>
</url>
view
line 118
<xhtml:link rel=alternate hreflang="{[ $lang ]}" href="%req->base{[ $uri ]}"{{ slash }}>
view
line 119
<link rel=alternate hreflang="{[ $lang ]}" href="%req->base{[ $uri ]}">
view

%seo -> head

line 121
<if $this->noIndex>
	<meta name=robots content=noindex,follow>
</if>
<if $this->ogDescr>
	<meta name=description content="{[ $this->ogDescr ]}">
</if>
<meta property=og:site_name content="{[ $this->siteName ]}">
<meta property=og:title content="{[ $this->ogTitle ]}">
<meta property=og:description content="{[ $this->ogDescr ]}">
<meta property=og:type content="{[ $this->ogType ]}">
<meta property=og:url content="{[ $this->canonical ]}">
<if $this->ogImage>
	<meta property=og:image content="{[ $this->ogImage ]}">
</if>
<meta property=og:locale content="{[ $this->locale ]}">
<if $this->twitterCard>
	<meta name=twitter:card content=summary_large_image>
	<meta name=twitter:title content="{[ $this->ogTitle ]}">
	<meta name=twitter:description content="{[ $this->ogDescr ]}">
	<if $this->ogImage>
		<meta name=twitter:image content="{[ $this->ogImage ]}">
	</if>
</if>
<if $data = $this->schemaData>
	<script type="application/ld+json">{{ json_encode($data, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG) }}</script>
</if>
<if !$this->noIndex>
	<link rel=canonical href="{[ $this->canonical ]}">
</if>
<if $this->alternates>
	<foreach $this->sitemapLangs AS $lang>
		{{ $this->link($lang, $this->address($this->here, $lang)) }}
	</foreach>
	{{ $this->link('x-default', $this->address($this->here, $this->defaultLang)) }}
</if>
object

%session

/phlo/resources/session.phlo

Session data object

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.

sessionwebstate
static

session :: objOptions:array

line 8
[]
static

session :: objDefaults:array

line 13
Garbage collection in a shared session directory runs with the lifetime of whichever app triggers
$options = ['cookie_httponly' => true, 'cookie_samesite' => 'Lax', 'cookie_secure' => %req->secure || ini_get('session.cookie_secure'), 'use_strict_mode' => true]
if (ini_get('session.save_handler') !== 'files') return $options
$root = rtrim((string)ini_get('session.save_path'), slash)
str_contains($root, semi) && $root = substr($root, strrpos($root, semi) + 1)
// By its data and not by its code: a new release of an app keeps the people who are signed in.
$own = 'phlo-'.substr(md5(data), 0, 8)
// A worker keeps the ini of its last request, so the path can already be this app's own.
$dir = str_ends_with($root, slash.$own) ? $root : ($root ?: rtrim(sys_get_temp_dir(), slash)).slash.$own
is_dir($dir) || @mkdir($dir, 0700, true)
return [...$options, 'save_path' => $dir]
method

%session -> controller

line 26
ession_start([...static::objDefaults(), ...static::objOptions()])
$this->objData =& $_SESSION
method

%session -> __set ($key, $value)

line 29
Stelt een sessievariabele in met de opgegeven sleutel op de gegeven waarde.
$_SESSION[$key] = $this->objData[$key] = $value
method

%session -> __unset ($key)

line 30
Verwijdert de opgegeven sleutel uit de sessiegegevens en de interne objectgegevens.
unset($this->objData[$key], $_SESSION[$key])
method

%session -> __isset ($key):bool

line 31
Controleert of een sessievariabele die door de gegeven sleutel is geïdentificeerd, is ingesteld en niet null is.
isset($this->objData[$key])
method

%session -> objRegenerateId ($deleteOld = true):void

line 33
session_regenerate_id($deleteOld)
$this->objData =& $_SESSION
object

%stream

/phlo/resources/stream.phlo

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

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.

streambinaryrawdatadownload
function

function stream ($data = null, string $type = 'application/octet-stream', ?string $name = null):void

line 9
$res = %res
$cli = %req->cli
!$res->streaming && $res->done && error('Output already started, invalid stream()')
if (!$res->streaming){
	$res->streaming = true
	$res->type = $type
	$res->header('Cache-Control', 'no-store')
	$res->header('X-Content-Type-Options', 'nosniff')
	$res->header('X-Accel-Buffering', 'no')
	$name === null || $res->header('Content-Disposition', 'attachment; filename="'.str_replace('"', '', $name).'"')
	$res->render()
}
if ($data === null) return
foreach (is_iterable($data) ? $data : [$data] as $part){
	print((string)$part)
	$cli || [@ob_flush(), flush()]
}
view

script

line 29
const streamFilename = disposition => {
	const extended = disposition.match(/(?:^|;)\s*filename\*\s*=\s*UTF-8'[^']*'([^;]+)/i)
	const plain = disposition.match(/(?:^|;)\s*filename\s*=\s*(?:"((?:\\.|[^"])*)"|([^;]+))/i)
	const value = extended?.[1] ?? plain?.[1] ?? plain?.[2]
	if (!value) return null
	const name = value.trim().replace(/\\(.)/g, '$1')
	try { return decodeURIComponent(name) }
	catch (_) { return name }
}

app.stream = async (path, onData = null, async = false, type = null, data = null) => {
	const url = `${location.origin}/${path}`
	const headers = {}
	async && (headers['X-Requested-With'] = 'phlo')
	let body = data
	if (body !== null && !(body instanceof FormData) && !(body instanceof Blob)) [body = JSON.stringify(body), headers['Content-Type'] = 'application/json']
	phlo.log(`⇣ APP.STREAM ${url}`)
	const res = await app.fetch(path, {method: body === null ? 'GET' : 'POST', credentials: 'same-origin', headers, body})
	if (!res.ok) throw new Error(`stream ${url} 🔴 ${res.status}`)
	const mime = (res.headers.get('content-type') ?? '').split(';')[0].trim()
	const kind = type ?? (mime === 'application/x-ndjson' ? 'ndjson' : mime === 'application/json' ? 'json' : mime === 'text/event-stream' ? 'sse' : mime.startsWith('text/') ? 'text' : 'raw')
	const emit = value => onData && onData(value)
	if (kind === 'json'){
		const value = await res.json()
		emit(value)
		return value
	}
	if (kind === 'blob'){
		const blob = await res.blob()
		const name = streamFilename(res.headers.get('content-disposition') ?? '')
		const value = name ? new File([blob], name) : blob
		emit(value)
		return value
	}
	const reader = res.body.getReader()
	const decoder = new TextDecoder()
	const out = []
	const parts = []
	let text = ''
	let buffer = ''
	const line = raw => {
		if (!raw) return
		const value = JSON.parse(raw)
		out.push(value)
		emit(value)
	}
	const frame = raw => {
		if (!raw.trim()) return
		let event = 'message'
		const data = []
		raw.split('\n').forEach(l => l.startsWith('event:') ? event = l.slice(6).trim() : l.startsWith('data:') && data.push(l.slice(5).replace(/^ /, '')))
		const value = {event, data: data.join('\n')}
		out.push(value)
		emit(value)
	}
	while (true){
		const {done, value} = await reader.read()
		if (done) break
		if (kind === 'raw'){
			parts.push(value)
			emit(value)
			continue
		}
		const piece = decoder.decode(value, {stream: true})
		if (kind === 'text'){
			text += piece
			emit(piece)
			continue
		}
		buffer += piece
		if (kind === 'sse'){
			const hold = buffer.endsWith('\r') ? '\r' : ''
			buffer = buffer.slice(0, buffer.length - hold.length).replace(/\r\n?/g, '\n') + hold
		}
		const pieces = buffer.split(kind === 'sse' ? '\n\n' : '\n')
		buffer = pieces.pop()
		pieces.forEach(kind === 'sse' ? frame : line)
	}
	if (kind === 'raw') return new Blob(parts, {type: mime || 'application/octet-stream'})
	const tail = decoder.decode()
	if (kind === 'text'){
		tail && [text += tail, emit(tail)]
		return text
	}
	buffer += tail
	buffer && (kind === 'sse' ? frame(buffer.replace(/\r\n?/g, '\n')) : line(buffer))
	return out
}
object

%tasks

/phlo/resources/tasks.phlo

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

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.

cronscheduletasksscheduler
static

tasks :: dir:string

line 8
Toegang tot het pad van de directory voor taken, specifiek verwijzend naar 'tasks/'.
data.'tasks/'
static

tasks :: run:void

line 10
Voert geplande taken uit door hun vervaldatum te controleren en ze te vergrendelen om gelijktijdige uitvoering te voorkomen. Het slaat de uitvoeringsdetails op en markeert de taak als voltooid na uitvoering.
is_dir(static::dir()) || mkdir(static::dir(), 0755, true)
$now = time()
foreach (%app->tasks ?? [] AS $name => $task){
	$task = (object)$task
	if (!static::due($name, $task, $now)) continue
	if (!static::lock($name)) continue
	$schedule = array_intersect_key((array)$task, array_flip(['every', 'daily', 'weekly']))
	$do = is_string($task->do) ? $task->do : null
	static::saveRun($name, $do, $schedule, static::fire($task->do))
	static::markRun($name, $now)
	static::unlock($name)
}
static

tasks :: saveRun ($name, $do, $schedule, $return)

line 25
Slaat de uitvoergegevens op in een JSON-bestand in de opgegeven map, met de opgegeven naam, do, schema en return-waarden.
json_write(static::dir().$name.'.json', arr(do: $do, schedule: $schedule, return: $return))
static

tasks :: due ($name, $task, $now):bool

line 31
daily and weekly match the exact minute the task names.
$last = static::lastRun($name)
if (isset($task->every)){
	$every = preg_match('/^\d/', $task->every) ? $task->every : '1 '.$task->every
	$seconds = strtotime("+$every", 0) ?: 0
	return $seconds > 0 && ($now - $last) >= $seconds
}
if (isset($task->daily)){
	if (date('H:i', $now) !== $task->daily) return false
	return $last < strtotime('today 00:00', $now)
}
if (isset($task->weekly)){
	if (date('D H:i', $now) !== date('D H:i', strtotime($task->weekly, $now))) return false
	return $last < strtotime('monday this week', $now)
}
return false
static

tasks :: fire ($do)

line 49
Voert een taak uit die is gedefinieerd door een Closure, een 'Class::method' string of een resource-naam string, en retourneert het resultaat van de uitvoering.
if ($do instanceof \Closure) return $do()
if (is_string($do) && str_contains($do, '::')){
	[$class, $method] = explode('::', $do, 2)
	return $class::$method()
}
if (is_string($do)) return phlo($do)
error('Task do must be Closure, "Class::method" string, or resource-name string')
static

tasks :: lastRun ($name):int

line 59
Haal de laatste uitvoeringstijdstempel van een taak op uit een bestand, en retourneer 0 als het bestand niet bestaat.
$file = static::dir().$name.'.last'
return is_file($file) ? (int)file_get_contents($file) : 0
static

tasks :: markRun ($name, $ts):int|false

line 64
Schrijft de tijdstempel van de laatste uitvoering van een taak naar een bestand met de naam van de taak in de opgegeven directory, met gebruik van exclusieve vergrendeling om gelijktijdige schrijfbewerkingen te voorkomen.
file_put_contents(static::dir().$name.'.last', (string)$ts, LOCK_EX)
static

tasks :: lock ($name):bool

line 66
Maakt een lockbestand voor een taak aan als het nog niet bestaat of ouder is dan een uur.
$file = static::dir().$name.'.lock'
if (is_file($file) && (time() - filemtime($file)) < 3600) return false
touch($file)
return true
static

tasks :: unlock ($name):bool

line 73
Verwijdert het vergrendelingsbestand dat aan een taak is gekoppeld, zodat deze opnieuw kan worden uitgevoerd.
@unlink(static::dir().$name.'.lock')
object

%useragent

/phlo/resources/useragent.phlo

User agent information

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.

useragentbrowserosdeviceweb
prop

%useragent -> source:?string

line 8
Deze expressie haalt de user agent-string op uit het aanvraagobject en retourneert null als deze niet is ingesteld.
%req->userAgent ?: null
prop

%useragent -> os:string

line 10
Bepaalt het besturingssysteem op basis van de user agent-string door deze te vergelijken met vooraf gedefinieerde patronen.
if (!$this->source) return 'Unknown'
$list = [
	'Android' => '/Android/i',
	'iPadOS' => '/iPad.*OS/i',
	'iOS' => '/iPhone|iPod/i',
	'Windows' => '/Windows NT/i',
	'macOS' => '/Mac OS X/i',
	'ChromeOS' => '/CrOS/i',
	'Linux' => '/Linux/i',
]
foreach ($list AS $n => $r) if (preg_match($r, $this->source)) return $n
if (preg_match('/iPad/i',$this->source) && preg_match('/Mac OS X/i',$this->source)) return 'iPadOS'
return 'Unknown'
prop

%useragent -> osV:string

line 26
Haalt de versie van het besturingssysteem uit de user agent-string als deze beschikbaar is, en retourneert deze in een schone indeling.
if (!$this->source) return void
if (preg_match('/(?:Android|OS X|OS|Windows NT)\s*([0-9._]+)/i', $this->source, $m)){
	$v = strtr($m[1], [us => dot])
	$v = preg_replace('/[^0-9.].*/', void, $v)
	$v = preg_replace('/(?:\.0)+$/', void, $v)
	return $v
}
return void
prop

%useragent -> osFull:string

line 37
Geeft de volledige naam van het besturingssysteem terug, samen met de versie als deze beschikbaar is; anders retourneert het 'Onbekend' of alleen de naam van het besturingssysteem.
if (!$this->OS) return 'Unknown'
if ($this->OS === 'Windows') return 'Windows'
$v = $this->osV
if (!$v) return $this->OS
$short = preg_replace('/^(\d+\.\d+).*/','$1',$v)
if (preg_match('/\.0$/',$short)) $short = preg_replace('/\.0$/', void, $short)
return trim($this->OS.space.$short)
prop

%useragent -> name:string

line 47
Bepaalt de naam van de webbrowser op basis van de gebruikersagentstring die in de source is opgegeven. Het controleert verschillende patronen om populaire browsers zoals Chrome, Firefox en Safari te identificeren en retourneert 'Onbekend' als er geen overeenkomst wordt gevonden.
if (!$this->source) return 'Unknown'
if (preg_match('/\bwv\b/',$this->source) || (preg_match('/Version\/\d+\.\d+/',$this->source) && strpos($this->source,'Chrome/')!==false && strpos($this->source,'Safari/')!==false && strpos($this->source,' Mobile ')!==false)) return 'Android WebView'
if (preg_match('/CriOS\/([0-9.]+)/',$this->source)) return 'Chrome'
if (preg_match('/FxiOS\/([0-9.]+)/',$this->source)) return 'Firefox'
$list = [
	'Edge' => '/Edg\/([0-9.]+)/',
	'Opera' => '/OPR\/([0-9.]+)/',
	'Samsung Internet' => '/SamsungBrowser\/([0-9.]+)/i',
	'Chrome' => '/Chrome\/([0-9.]+)/',
	'Firefox' => '/Firefox\/([0-9.]+)/',
	'Safari' => '/Version\/([0-9.]+).*Safari/i',
]
foreach ($list AS $n => $r) if (preg_match($r, $this->source)) return $n
return 'Unknown'
prop

%useragent -> version:string

line 64
Haalt het versienummer uit de user agent-string als deze overeenkomt met specifieke browserpatronen, en retourneert het schoongemaakte versienummer of void als er geen overeenkomst is.
if (!$this->source) return void
if (preg_match('/(?:Edg|OPR|Chrome|Firefox|Version|CriOS|FxiOS|SamsungBrowser)\/([0-9.]+)/', $this->source, $m)){
	$v = $m[1]
	$v = preg_replace('/[^0-9.].*/', void, $v)
	$v = preg_replace('/(?:\.0)+$/', void, $v)
	return $v
}
return void
prop

%useragent -> full:string

line 75
Geeft de volledige user agent-string terug, inclusief de naam en versie van de user agent, geformatteerd om onnodige delen uit te sluiten.
if (!$this->name) return 'Unknown'
$v = $this->version
if (!$v) return $this->name
$short = preg_replace('/^(\d+\.\d+).*/','$1',$v)
if (preg_match('/\.0$/',$short)) $short = preg_replace('/\.0$/', void, $short)
return rtrim($this->name.space.$short)
prop

%useragent -> device:string

line 84
Bepaalt het type apparaat (Tablet, Telefoon of Desktop) op basis van de user agent-string die is opgeslagen in de source-eigenschap.
if (!$this->source) return 'Unknown'
if (preg_match('/iPad|Tablet|Tab|SM-T|Nexus 7|Nexus 10/i', $this->source)) return 'Tablet'
if (preg_match('/Mobile|iPhone|Android.*Mobile|SM-G|Pixel [0-9]/i', $this->source)) return 'Phone'
return 'Desktop'
object

%visitors

/phlo/resources/visitors.phlo

Visitor tracking via heartbeat

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.

visitorsanalyticsheartbeattracking
static

visitors :: table:string

line 10
De 'visitors::$table' verwijst naar de database tabel die is gekoppeld aan de 'visitors' resource in Phlo.
'visitors'
static

visitors :: columns

line 11
Definieert de kolommen voor de visitors resource, waarbij de te gebruiken attributen voor gegevensbewerkingen worden gespecificeerd.
'id,token,host,page,lang,IP,browser,os,device,active_seconds,state,width,height,referrer,created,changed'
static

visitors :: history:array

line 13
Haal een geschiedenis op van bezoekersaantallen, gegroepeerd op datum en tel unieke tokens en totale bezoeken.
static::records(columns: 'FROM_UNIXTIME(changed, "%Y-%m-%d") AS date,COUNT(DISTINCT token) AS visitors,COUNT(id) AS visits', group: 'date', order: 'date DESC')
static

visitors :: online:int

line 14
Dit haalt het aantal unieke online bezoekers op die in de afgelopen 9 seconden zijn veranderd.
static::item(columns: 'COUNT(DISTINCT token)', where: 'changed >= (UNIX_TIMESTAMP() - 9)')
static

visitors :: lastHour:int

line 15
Haal het aantal unieke bezoekers (tokens) op die in het afgelopen uur zijn veranderd.
static::item(columns: 'COUNT(DISTINCT token)', where: 'changed >= (UNIX_TIMESTAMP() - 3600)')
static

visitors :: dayKey (?string $day = null):?string

line 19
Without consent a visitor is keyed with a random key of the day, which the next day replaces under a lock, so two
$day ??= date('Ymd')
if ($key = static::heldKey($file = data.'visitors.key', $day)) return $key
if (!$lock = @fopen($file.'.lock', 'c')) return null
flock($lock, LOCK_EX)
if (!$key = static::heldKey($file, $day)){
	$tmp = $file.'.'.bin2hex(random_bytes(4)).'.tmp'
	$new = bin2hex(random_bytes(32))
	@touch($tmp) && @chmod($tmp, 0600) && @file_put_contents($tmp, json_encode(arr(day: $day, key: $new))) && @rename($tmp, $file) ? $key = $new : @unlink($tmp)
}
flock($lock, LOCK_UN)
fclose($lock)
return $key ?: null
static

visitors :: heldKey (string $file, string $day):?string

line 34
is_array($held = json_decode((string)@file_get_contents($file), true)) && ($held['day'] ?? null) === $day && is_string($held['key'] ?? null) ? $held['key'] : null
static

visitors :: visitorToken (bool $consent, string $who, ?string $key = null):string

line 36
token(20, $consent ? $who : hash_hmac('sha256', $who, (string)($key ?? static::dayKey() ?? error('visitors has no key of the day: data/ is not writable', 500))))
static

visitors :: isBot (?string $ua):bool

line 38
Bepaalt of de user agent-string aangeeft dat de bezoeker een bot is door deze te vergelijken met een vooraf gedefinieerd regex-patroon.
if (!$ua) return false
return (bool)preg_match('/bot|crawl|spider|slurp|baiduspider|facebookexternalhit|twitterbot|linkedinbot|curl|wget|python-requests|go-http-client|java\//i', $ua)
static

visitors :: parseReferrer (string $url):string

line 43
Analyseert de referrer-URL om de gebruikte zoekmachine te identificeren en retourneert een geformatteerde string die de zoekmachine aangeeft of de host als er geen overeenkomst wordt gevonden.
static $engines = ['google' => 'Google', 'bing' => 'Bing', 'duckduckgo' => 'DuckDuckGo', 'yahoo' => 'Yahoo', 'baidu' => 'Baidu', 'yandex' => 'Yandex', 'ecosia' => 'Ecosia', 'startpage' => 'Startpage', 'brave' => 'Brave', 'kagi' => 'Kagi']
$host = strtolower(preg_replace('/^www\./', void, (string)(parse_url($url, PHP_URL_HOST) ?? void)))
foreach ($engines AS $key => $name) if (str_contains($host, $key)) return 'search:'.$name
return $host ?: substr($url, 0, 100)
route

route PUT heartbeat @n,v,l,u,w,h,a,p,r,c,s,pp,ps

line 50
if (static::isBot(%useragent->source)) return
$consent = (bool)%payload->c
if (!$consent && !$key = static::dayKey()) return
$n = strlen(%payload->n) === 8 ? %payload->n : date('Ymd')
$id = $consent ? token(20, $n.space.%cookies->token.space.%useragent->source) : static::visitorToken(false, $n.space.%cookies->token.space.%req->ip, $key)
$delta = max(0, min(120, (int)%payload->s))
$prevDelta = max(0, min(120, (int)%payload->ps))
$lang = strlen(%payload->l) === 2 ? %payload->l : %app->lang ?? 'en'
$referrer = ($r = (string)%payload->r) && !str_contains($r, host) ? static::parseReferrer($r) : null
static::DB()->query('INSERT INTO '.static::$table.' (id, token, host, page, lang, IP, browser, os, device, active_seconds, state, width, height, referrer, created, changed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE token = VALUES(token), host = VALUES(host), page = VALUES(page), lang = VALUES(lang), IP = VALUES(IP), browser = VALUES(browser), os = VALUES(os), device = VALUES(device), active_seconds = active_seconds + VALUES(active_seconds), state = VALUES(state), width = VALUES(width), height = VALUES(height), referrer = IF(referrer IS NULL OR referrer = '.sq.sq.', VALUES(referrer), referrer), changed = VALUES(changed)', $id, static::visitorToken($consent, (string)(%cookies->token ?? %payload->n), $key ?? null), host, %payload->u, $lang, $consent ? %req->ip : void, $consent ? %useragent->full.(%payload->a ? ' App' : void) : substr(md5((string)%useragent->source), 0, 8), $consent ? %useragent->osFull : void, $consent ? %useragent->device : void, $delta + $prevDelta, %payload->v, %payload->w, %payload->h, $referrer, time(), time())
$pages = preg_replace('/visitors$/', 'visitor_pages', (string)static::$table)
if (strlen((string)%payload->p) >= 8){
	$pv = token(20, $id.space.%payload->p)
	static::DB()->query('INSERT INTO '.$pages.' (id, visitor, host, page, lang, active_seconds, beats, created, changed) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE active_seconds = active_seconds + VALUES(active_seconds), beats = beats + 1, changed = VALUES(changed)', $pv, $id, host, %payload->u, $lang, $delta, 1, time(), time())
}
if (strlen((string)%payload->pp) >= 8){
	$ppv = token(20, $id.space.%payload->pp)
	static::DB()->query('UPDATE '.$pages.' SET active_seconds = active_seconds + ?, beats = beats + 1, changed = ? WHERE id = ?', $prevDelta, time(), $ppv)
}
view

script

line 72
let curpath = app.path
let pv = phlo.token(12)
let hbTimer, activeMs = 0, activeAt = null, prev = null
const visible = () => document.visibilityState === 'visible'
const accrue = () => {
	if (activeAt === null) return
	activeMs += performance.now() - activeAt
	activeAt = visible() ? performance.now() : null
}
const flush = beacon => {
	accrue()
	const consent = document.cookie.includes('cookieChoice=all')
	window.name ||= phlo.token(8)
	const s = Math.floor(activeMs / 1000)
	activeMs -= s * 1000
	const body = JSON.stringify({n: window.name, v: app.state, l: obj('html').lang ?? 'en', u: app.path, w: innerWidth, h: innerHeight, a: app.mode, p: pv, r: (r = document.referrer) ? (r === `${location.origin}/` ? null : r) : null, c: consent ? 1 : 0, s, pp: prev ? prev.p : null, ps: prev ? prev.s : null})
	prev = null
	app.fetch('heartbeat', {method: 'PUT', headers: {'Content-Type': 'application/json'}, body, keepalive: !!beacon})
}
const heartbeat = () => delay('heartbeat', 333, () => {
	clearTimeout(hbTimer)
	flush()
	if (visible()) hbTimer = setTimeout(heartbeat, 20000)
})
document.addEventListener('visibilitychange', () => {
	if (!visible()) return flush(true)
	activeAt = performance.now()
	heartbeat()
})
addEventListener('resize', heartbeat)
addEventListener('pagehide', () => flush(true))
app.updates.push(() => {
	if (curpath === app.path) return
	if (prev) flush()
	accrue()
	prev = {p: pv, s: Math.floor(activeMs / 1000)}
	pv = phlo.token(12)
	activeMs = 0
	curpath = app.path
	heartbeat()
})
if (visible()) activeAt = performance.now()
heartbeat()
object

%websocket

/phlo/resources/websocket.phlo

Server-side WebSocket handler via phloWS

Enable this class only when websockets are configured for the host

websocketrealtimewsserver
static

websocket :: connect ($wsHost, $wsToken, $wsSocket):bool

line 8
Stelt een WebSocket-verbinding tot stand met behulp van de opgegeven host, token en socketparameters.
!function_exists('wsConnect') || wsConnect($wsHost, $wsToken, $wsSocket)
static

websocket :: auth ($wsHost, $wsToken, $wsSocket):bool

line 9
Controleert of de 'wsAuth'-functie bestaat en roept deze, indien niet, aan met de opgegeven parameters voor WebSocket-authenticatie.
!function_exists('wsAuth') || wsAuth($wsHost, $wsToken, $wsSocket)
static

websocket :: receive ($wsHost, $wsToken, $wsSocket, $data):bool

line 10
Ontvangt gegevens van een WebSocket-verbinding met behulp van de opgegeven host, token en socket, en verwerkt de binnenkomende gegevens als JSON.
function_exists('wsReceive') && wsReceive($wsHost, $wsToken, $wsSocket, ...json_decode($data, true))
static

websocket :: close ($wsHost, $wsToken, $wsSocket):bool

line 11
Sluit een WebSocket-verbinding met behulp van de opgegeven host, token en socket.
function_exists('wsClose') && wsClose($wsHost, $wsToken, $wsSocket)
object

%WhatsApp

/phlo/resources/WhatsApp.phlo

WhatsApp client for phloWA using whatsapp-web.js

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.

whatsappmessagingapi
method

%WhatsApp -> __construct (public string $url, public string $secret)

line 9
Initialiseert een WhatsApp-instantie met een opgegeven URL en geheim, waarbij wordt gegarandeerd dat de URL eindigt met een schuine streep.
$this->url = rtrim($url, slash).slash
static

WhatsApp :: channel ($channel):static

line 11
Maakt een nieuwe instantie van het WhatsApp-kanaal met de opgegeven URL en geheim, standaard 'http://localhost:8081' en 'void' als niet gespecificeerd.
new static($channel->configData->url ?? 'http://localhost:8081', $channel->secretData->secret ?? void)
method

%WhatsApp -> number ($contact):string

line 13
Extraheert het telefoonnummer uit een WhatsApp-contactstring en retourneert een fout als het formaat ongeldig is.
($pos = strpos($contact, '@')) ? substr($contact, 0, $pos) : error('Invalid contact: '.esc($contact))
method

%WhatsApp -> isGroup ($contact):bool

line 14
Controleert of de opgegeven contactpersoon een WhatsApp-groep is door te verifiëren of de contactpersoon een '@g' achtervoegsel bevat.
last($this->number($contact), (bool)strpos($contact, '@g'))
method

%WhatsApp -> status:obj

line 16
Haal de huidige status van WhatsApp op met een GET-verzoek.
$this->request('status', GET: true)
method

%WhatsApp -> health:obj

line 17
Controleert de gezondheidsstatus van de WhatsApp-service door een GET-verzoek te verzenden.
$this->request('health', GET: true)
method

%WhatsApp -> qr:obj

line 18
Stuurt een verzoek om de QR-code voor WhatsApp-authenticatie op te halen.
$this->request('qr', GET: true)
method

%WhatsApp -> disconnect:obj

line 19
Verbreekt de huidige WhatsApp-sessie door een verbreekverzoek te sturen.
$this->request('disconnect')
method

%WhatsApp -> read ($chat):obj

line 21
Stuurt een verzoek om berichten te lezen uit een opgegeven WhatsApp-chat.
$this->request('read', chat: $chat)
method

%WhatsApp -> reaction ($msg, $emoji):obj

line 22
Stuurt een reactie-emoticon naar een specifiek bericht in WhatsApp.
$this->request('reaction', msg: $msg, emoji: $emoji)
method

%WhatsApp -> text ($to, $text):obj

line 24
Verzendt een tekstbericht naar de opgegeven ontvanger via WhatsApp.
$this->request('text', to: $to, text: $text)
method

%WhatsApp -> image ($to, file $file, $text = void):obj

line 25
Verzendt een afbeeldingsbericht via WhatsApp naar de opgegeven ontvanger, met de optie om een tekstbericht toe te voegen.
$this->request('image', to: $to, filename: $file->name, image: $file->src, text: $text)
method

%WhatsApp -> location ($to, $lat, $lon, $text):obj

line 26
Verzendt een locatiebericht via WhatsApp naar de opgegeven ontvanger met breedtegraad, lengtegraad en optionele tekst.
$this->request('location', to: $to, lat: $lat, lon: $lon, text: $text)
method

%WhatsApp -> document ($to, file $file, $text = void):obj

line 27
Verzendt een document via WhatsApp naar de opgegeven ontvanger, inclusief een optioneel tekstbericht.
$this->request('document', to: $to, filename: $file->name, document: $file->src, text: $text)
method

%WhatsApp -> audio ($to, file $file):obj

line 29
Verzendt een audiobericht naar een opgegeven ontvanger met het opgegeven audiobestand.
$this->request('audio', to: $to, audio: $file->src)
method

%WhatsApp -> voice ($to, file $file):obj

line 30
Verzendt een spraakbericht naar een opgegeven ontvanger met behulp van het opgegeven audiobestand.
$this->request('voice', to: $to, audio: $file->src)
method

%WhatsApp -> poll ($to, $name, array $options, bool $multi = false):obj

line 32
Verzendt een peilingbericht naar een opgegeven WhatsApp-ontvanger met de gegeven opties, met de mogelijkheid voor meerdere selecties indien opgegeven.
$this->request('poll', to: $to, name: $name, options: $options, multi: $multi)
method

%WhatsApp -> startTyping ($to):obj

line 34
Start de typindicator voor een opgegeven ontvanger in WhatsApp.
$this->request('typing/start', to: $to)
method

%WhatsApp -> stopTyping ($to):obj

line 35
Stop de typindicator voor een specifieke ontvanger in WhatsApp.
$this->request('typing/stop', to: $to)
method

%WhatsApp -> request ($action, ...$data):obj

line 37
$get = $data['GET'] ?? false
unset($data['GET'])
$raw = trim((string)HTTP($this->url.$action, ['secret: '.$this->secret], true, $get ? null : $data))
if (strtolower($raw) === 'ok') return obj(ok: true)
$res = json_decode($raw)
if ($res instanceof \stdClass) return WhatsApp::asObj($res)
if (is_array($res)) return obj(ok: true, items: $res)
if (is_scalar($res)) return obj(ok: (bool)$res, value: $res)
if ($raw !== void) return obj(ok: false, error: $raw)
return obj(ok: false, error: 'Empty WhatsApp response')
static

WhatsApp :: asObj (\stdClass $data):obj

line 54
Turns the decoded answer into the obj every method here promises.
$out = obj()
foreach ((array)$data AS $key => $value) $out->$key = $value
return $out

Functions

function

active(bool $cond, string $classList = void):string

/phlo/resources/active.phlo line 8

Build active class attribute for UI state

Writes the whole class attribute, or nothing at all when there is nothing to say, so a link needs no ternary in the view. Because it emits the attribute rather than a class name, it goes into the tag itself and not inside another class attribute.

activeclassuiviewhtml
Genereert een class-attribuutstring voor HTML-elementen, waarbij 'active' aan de opgegeven classlijst wordt toegevoegd als de voorwaarde waar is.
$cond || $classList ? ' class="'.$classList.($cond ? ($classList ? space : void).'active' : void).'"' : void
function

age(int $time):int

/phlo/resources/age.phlo line 8

Get age in seconds since a given timestamp

Seconds since a timestamp, so an expiry or a cache check reads as a comparison. Nothing more than that: use time_human for something a reader sees.

agetimetimestamp
Berechnet de leeftijd door de gegeven tijd van de huidige tijd af te trekken.
time() - $time
function

age_human(int $age):string

/phlo/resources/age.human.phlo line 9

Convert age in seconds to human readable text

The reader-facing side of age(): give it an age in seconds and it gives a label like 3 hours. Pass an age here and a timestamp to time_human; the two are easy to swap and both give an answer, only the wrong one.

agehumantimeformat
Berechnet een leesbare tijdsduur op basis van de gegeven leeftijd in seconden.
time_human(time() - $age)
function

apcu(string $key, callable $cb, int $duration = 3600, bool $log = true):mixed

/phlo/resources/apcu.phlo line 17

Cache callback results in APCu

Wraps a callback in APCu with one line, and the callback only runs when the value is not there; apcu_forget($key) drops it. Keys are scoped to the app, so apps sharing a server never read each other's values; use apcu_key() for a key you pass to the apcu_* functions yourself. The cache lives in one server's shared memory and is gone after a restart, and a CLI run has its own unless apc.enable_cli is on, which makes it right for something expensive and reproducible and wrong for something authoritative. Key it on everything the answer depends on, or two different questions get the same answer.

cacheapcuperformance
apcu_entry holds a lock on the key for the length of the callback.
	// On the command line APCu is usually off. Then there is nothing to keep it in, and a job still needs the value.
	if (!apcu_enabled()) return $cb($key)
	$value = apcu_entry(apcu_key($key), fn() => $cb($key), $duration)
	$log && debug('C: '.(strlen($key) > 58 ? substr($key, 0, 55).'...' : $key).(is_array($value) ? ' ('.count($value).')' : (is_numeric($value) ? ":$value" : (is_string($value) ? ':string:'.strlen($value) : colon.gettype($value)))))
	return $value
function

apcu_forget(string $key):bool

/phlo/resources/apcu.phlo line 25

Cache callback results in APCu

Wraps a callback in APCu with one line, and the callback only runs when the value is not there; apcu_forget($key) drops it. Keys are scoped to the app, so apps sharing a server never read each other's values; use apcu_key() for a key you pass to the apcu_* functions yourself. The cache lives in one server's shared memory and is gone after a restart, and a CLI run has its own unless apc.enable_cli is on, which makes it right for something expensive and reproducible and wrong for something authoritative. Key it on everything the answer depends on, or two different questions get the same answer.

cacheapcuperformance
apcu_delete(apcu_key($key))
function

apcu_key(string $key):string

/phlo/resources/apcu.phlo line 11

Cache callback results in APCu

Wraps a callback in APCu with one line, and the callback only runs when the value is not there; apcu_forget($key) drops it. Keys are scoped to the app, so apps sharing a server never read each other's values; use apcu_key() for a key you pass to the apcu_* functions yourself. The cache lives in one server's shared memory and is gone after a restart, and a CLI run has its own unless apc.enable_cli is on, which makes it right for something expensive and reproducible and wrong for something authoritative. Key it on everything the answer depends on, or two different questions get the same answer.

cacheapcuperformance
One server process serves every app on it and APCu is shared between them, so a key carries the
substr(md5(app), 0, 8).colon.$key
function

await(...$jobs):array

/phlo/resources/await.phlo line 9

Run app targets in parallel, via the daemon pool or one-shot CLI processes

Runs several app targets at once and returns their results in the order you asked, so three slow calls take as long as the slowest instead of their sum. Under the daemon they run in the pool; without it each becomes a CLI process. The whole wait is bounded, five minutes unless await_timeout says otherwise, and a child still running is killed rather than waited for, so one hung job cannot hold a request.

awaitparallelcliprocessdaemon
Wacht op meerdere taken om te voltooien, beheert hun uitvoer en fouten, en retourneert de resultaten. Het beheert kindprocessen en zorgt ervoor dat ze niet eindeloos blokkeren.
	if (daemon) return daemon::await($jobs)
	$children = []
	$open = []
	foreach ($jobs AS $i => $job){
		[$cb, $args] = is_array($job) ? [$job[0], array_slice($job, 1)] : [$job, []]
		$cmd = cli.space.escapeshellarg($_SERVER['SCRIPT_FILENAME']).space.escapeshellarg($cb).loop($args, fn($a) => space.escapeshellarg((string)$a), void)
		$desc = [0 => ['pipe','r'], 1 => ['pipe','w'], 2 => ['pipe','w']]
		$proc = proc_open($cmd, $desc, $pipes)
		fclose($pipes[0])
		stream_set_blocking($pipes[1], false)
		stream_set_blocking($pipes[2], false)
		$children[$i] = obj(proc: $proc, out: $pipes[1], err: $pipes[2], stdout: void, stderr: void)
		$open['o'.$i] = $pipes[1]
		$open['e'.$i] = $pipes[2]
	}
	// Drain every child's stdout AND stderr together: reading one stream to EOF before the
	// other deadlocks a child that fills the unread pipe. Bound the whole wait so a hung
	// child cannot block the caller forever.
	$deadline = time() + (defined('await_timeout') ? await_timeout : 300)
	while ($open){
		$read = $open
		$write = $except = []
		if (@stream_select($read, $write, $except, 1) === false) break
		foreach ($read AS $key => $stream){
			$chunk = fread($stream, 65536)
			if ($chunk === void || $chunk === false){
				feof($stream) && $open = array_diff_key($open, [$key => 1])
				continue
			}
			$i = substr($key, 1)
			if ($key[0] === 'o') $children[$i]->stdout .= $chunk
			else $children[$i]->stderr .= $chunk
		}
		if (time() >= $deadline) break
	}
	// Terminate any child still running (deadline or a stream_select error). SIGKILL cannot
	// be ignored, so proc_close below will not block on a process that drops SIGTERM.
	foreach ($children AS $child) (proc_get_status($child->proc)['running'] ?? false) && proc_terminate($child->proc, 9)
	$results = []
	foreach ($children AS $i => $child){
		fclose($child->out)
		fclose($child->err)
		$code = proc_close($child->proc)
		$err = trim($child->stderr)
		if ($err !== void){
			$ej = json_decode($err, true)
			$results[$i] = json_last_error() === JSON_ERROR_NONE ? $ej : $err
			continue
		}
		if ($code !== 0){
			$results[$i] = obj(error: 'CLI process failed', code: $code)
			continue
		}
		$json = json_decode($child->stdout, true)
		$results[$i] = json_last_error() === JSON_ERROR_NONE ? $json : $child->stdout
	}
	return $results
function

button(...$args):string

/phlo/resources/tags.form.phlo line 9

DOM form tags for button, input, select and textarea

button(), input(), select() and textarea() are tag() with the name filled in, so they take the same named arguments and the same escaping. They exist because these four appear so often that the name is noise.

formtagshtmlview
Maakt een knop element met de opgegeven argumenten die als props worden doorgegeven.
tag('button', ...$args)
function

camel(string $text):string

/phlo/resources/camel.phlo line 8

Convert text to camelCase

Turns a sentence into camelCase, for making a property or key name out of a title. It splits on spaces, so a hyphen or an underscore survives into the result.

camelcasestringformat
Converteert een gegeven string naar camel case door de eerste letter van elk woord te kapitaliseren en spaties te verwijderen.
lcfirst(str_replace(space, void, ucwords(lcfirst($text))))
function

chunk(...$cmds):void

/phlo/resources/chunk.phlo line 9

Stream JSON chunks over CLI or Server-Sent Events

Sends a piece of a response now instead of at the end, so long work reports as it goes. The first call switches the response to a stream and fixes the content type, so anything printed after it is part of that stream and a normal return can no longer be made. In the browser these arrive as commands; on the CLI they are plain lines.

chunkstreamssecliasync
	$res = %res
	$cli = %req->cli
	!$res->streaming && $res->done && error('Output already started, invalid chunk()')
	if (debug){
		$res->dump && [$cmds['dump'] = $res->dump, $res->dump = []]
		$res->debug && [$cmds['debug'] = $res->debug, $res->debug = []]
	}
	if (!$res->streaming){
		$res->streaming = true
		$res->type = 'application/x-ndjson'
		$res->header('Cache-Control', 'no-store')
		$res->header('X-Content-Type-Options', 'nosniff')
		$res->render()
	}
	print(json_encode($cmds, jsonFlat).lf)
	$cli || [@ob_flush(), flush()]
function

create(iterable $items, \Closure $keyCb, ?\Closure $valueCb = null):array

/phlo/resources/create.phlo line 8

Create associative array from iterable using callbacks

Turns a list into a keyed array in one pass: the first callback makes the key, the optional second makes the value. Keys that repeat overwrite each other, so this doubles as a way to fold a list into its unique entries.

createarrayiterablecallback
Maakt een associatieve array door de waarden uit de iterable als sleutels te gebruiken en de optionele waarde callback te gebruiken om de bijbehorende waarden te bepalen.
array_combine(loop($items, $keyCb), $valueCb ? loop($items, $valueCb) : $items)
function

en($text, ...$args):string

/phlo/resources/lang.phlo line 10

Language and translation resource

%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.

langtranslationi18nai
Deze functie haalt een vertaling op voor de opgegeven tekst in het Engels, en kan optioneel worden opgemaakt met extra argumenten.
%lang->translation('en', $text, ...$args)
function

exec_stream(string $cmd, ?int $timeoutSec = 0):Generator

/phlo/resources/exec.stream.phlo line 11

Stream shell command output via yielding

Yields a shell command's output line by line, with error true on the lines that came from stderr, so a failure can be shown as it happens instead of after. It reads stdout and stderr together, which is what keeps a command that writes a lot to one of them from deadlocking. Pass a timeout for anything that could hang; zero waits forever.

streamshellcliprocessyield
Reads stdout and stderr in one select loop rather than one after the other.
	$desc = [0 => ['pipe','r'], 1 => ['pipe','w'], 2 => ['pipe','w']]
	$proc = proc_open($cmd, $desc, $pipes)
	if (!is_resource($proc)) return
	stream_set_blocking($pipes[1], false)
	stream_set_blocking($pipes[2], false)
	$bufOut = void
	$bufErr = void
	while (true){
		$status = proc_get_status($proc)
		$running = $status['running']
		$read = []
		$w = null
		$e = null
		if (!feof($pipes[1])) $read[] = $pipes[1]
		if (!feof($pipes[2])) $read[] = $pipes[2]
		if ($read) @stream_select($read, $w, $e, 0, 200000)
		foreach ($read AS $r){
			$chunk = fread($r, 8192)
			if ($chunk === void || $chunk === false) continue
			if ($r === $pipes[1]){
				$bufOut .= $chunk
				while (($pos = strpos($bufOut, lf)) !== false){
					$line = substr($bufOut, 0, $pos)
					$bufOut = substr($bufOut, $pos + 1)
					yield obj(data: $line)
				}
			}
			else {
				$bufErr .= $chunk
				while (($pos = strpos($bufErr, lf)) !== false){
					$line = substr($bufErr, 0, $pos)
					$bufErr = substr($bufErr, $pos + 1)
					yield obj(data: $line, error: true)
				}
			}
		}
		if (!$running) break
		if ($timeoutSec > 0 && ($status['running_time'] ?? 0) > $timeoutSec){
			proc_terminate($proc)
			yield obj(data: 'process timeout', error: true)
			break
		}
	}
	if ($bufOut !== void) yield obj(data: $bufOut)
	if ($bufErr !== void) yield obj(data: $bufErr, error: true)
	foreach ($pipes AS $p) @fclose($p)
	proc_close($proc)
function

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)

/phlo/resources/HTTP.phlo line 14

HTTP request helper via cURL

One function for a whole request: a URL and headers is a GET, and POST, PUT, PATCH, QUERY or DELETE named as an argument decides the rest. Pass an array with JSON true and it is sent as JSON. The timeout is fifteen seconds and it is a real limit, so raise it deliberately for a slow API rather than by accident. Pass response by reference to see the status and the headers, which is the only way to tell an empty answer from a failure. For a URL that came from outside, such as a webhook or an image to fetch, pass public: true: it reaches only a public address, the one it checked, and follows no redirect, so a visitor cannot aim it at a service inside your network.

httpcurlrequestapi
Follows redirects on its own and raises only when the transport itself fails.
	$curl = curl_init($url)
	// A URL from outside reaches only the public internet, at the address that was checked.
	if ($public){
		($ip = public_address($url)) || error('HTTP: not a public address: '.$url, 400)
		$parts = parse_url($url)
		curl_setopt($curl, CURLOPT_RESOLVE, [trim($parts['host'], '[]').colon.($parts['port'] ?? (strtolower($parts['scheme']) === 'https' ? 443 : 80)).colon.(str_contains($ip, colon) ? "[$ip]" : $ip)])
	}
	if ($POST !== null || $PUT !== null || $PATCH !== null || $QUERY !== null){
		if (!is_null($POST)) [$method = 'POST', $content = $POST]
		elseif (!is_null($PUT)) [$method = 'PUT', $content = $PUT]
		elseif (!is_null($PATCH)) [$method = 'PATCH', $content = $PATCH]
		elseif (!is_null($QUERY)) [$method = 'QUERY', $content = $QUERY]
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method)
		if ($JSON) [!is_string($content) && $content = json_encode($content), array_push($headers, 'Content-Type: application/json', 'Content-Length: '.strlen($content))]
		curl_setopt($curl, CURLOPT_POSTFIELDS, $content)
	}
	elseif ($DELETE) curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE')
	$agent && curl_setopt($curl, CURLOPT_USERAGENT, $agent === true ? phlo('req')->userAgent : $agent)
	if ($cookies !== false) [$jar = $cookies === true ? data.'cookies.txt' : $cookies, curl_setopt($curl, CURLOPT_COOKIEFILE, $jar), curl_setopt($curl, CURLOPT_COOKIEJAR, $jar)]
	$resHeaders = []
	curl_setopt_array($curl, [CURLOPT_HTTPHEADER => $headers, CURLOPT_FOLLOWLOCATION => $follow && !$public, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => $timeout, CURLOPT_ENCODING => void, CURLOPT_HEADERFUNCTION => function($ch, $line) use (&$resHeaders){
		$parts = explode(colon, $line, 2)
		count($parts) === 2 && $resHeaders[strtolower(trim($parts[0]))] = trim($parts[1])
		return strlen($line)
	}])
	$res = curl_exec($curl)
	$status = (int)curl_getinfo($curl, CURLINFO_RESPONSE_CODE)
	$response = obj(ok: $res !== false && $status >= 200 && $status < 300, status: $status, headers: $resHeaders, error: $res === false ? curl_error($curl) : null)
	if ($res === false) error('HTTP error: '.curl_error($curl))
	return $res
function

input(...$args):string

/phlo/resources/tags.form.phlo line 10

DOM form tags for button, input, select and textarea

button(), input(), select() and textarea() are tag() with the name filled in, so they take the same named arguments and the same escaping. They exist because these four appear so often that the name is noise.

formtagshtmlview
Maakt een invoerelement in de view met de opgegeven argumenten.
tag('input', ...$args)
function

n8n($webhook, ?array $data = null, $test = false)

/phlo/resources/n8n.phlo line 9

Call n8n webhook endpoint

Fires an n8n workflow from your app, with test true to hit the test URL that only listens while the editor is open. It posts and returns what came back; n8n itself decides whether that is the result or just an acknowledgement, so a long workflow is better answered by a callback than by waiting here.

n8nwebhookhttpautomation
Stuurt een HTTP POST-verzoek naar een n8n webhook met optionele gegevens en een testvlag.
HTTP(%creds->n8n->server.'webhook'.($test ? '-test' : '').'/'.$webhook, POST: $data)
function

nl($text, ...$args):string

/phlo/resources/lang.phlo line 9

Language and translation resource

%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.

langtranslationi18nai
Vertaal de gegeven tekst naar het Nederlands met de opgegeven argumenten voor opmaak.
%lang->translation('nl', $text, ...$args)
function

notify(string $title, string $body = void, string $type = 'info', string $level = 'info', ?string $user = null):void

/phlo/resources/notify.phlo line 8

Notification to the central hub: POST to [notify].url (secret header) via Phlo's HTTP() function. No-op without [notify] config.

One line to send a notification to the central hub, and quietly nothing at all when no hub is configured, so the same code runs on a laptop and on a server. That silence cuts both ways: a missing config gives no error, so check the hub itself when a message fails to arrive.

Verzendt een melding met een opgegeven titel, inhoud, type, niveau en optionele gebruiker naar een geconfigureerde URL via HTTP.
	$cfg = %creds->notify ?? null
	if (!$cfg) return
	$url = $cfg->url ?? void
	$secret = $cfg->secret ?? void
	if ($url === void || $secret === void) return
	try {
		HTTP($url, ['secret: '.$secret], true, [
			'app' => (string)($cfg->app ?? (defined('id') ? id : 'app')),
			'server' => $cfg->server ?? 'local',
			'host' => %req->host ?? void,
			'type' => $type,
			'level' => $level,
			'title' => $title,
			'body' => $body,
			'user' => $user,
		])
	}
	catch (\Throwable $e){}
function

phlo(?string $phloName = null, ...$args):mixed

/phlo/phlo.php line 245
static $list = [];
if ($phloName === 'tech/reset'){
	obj::$classProps = [];
	return array_keys($list = array_filter($list, static fn($obj) => $obj->objPers));
}
if ($phloName === null) return array_keys($list);
$class = strtr($phloName, [slash => us]);
$handle = method_exists($class, '__handle') ? $class::__handle(...$args) : ($args ? null : $phloName);
if ($handle === true){
	if (isset($list[$phloName])) return $list[$phloName]->objImport(...$args);
	$handle = $phloName;
}
elseif ($handle && isset($list[$handle])) return $list[$handle];
$object = new $class(...$args);
if ($handle) $list[$handle] = $object;
if ($object->objHasMethod('controller') && (!phlo('req')->cli || $phloName !== 'app')) $object->controller();
return $object;
function

phlo_app(...$args):void

/phlo/phlo.php line 39
Initialiseert een Phlo-applicatie door de omgeving in te stellen, noodzakelijke klassen en functies te laden, en verschillende runtime-parameters te configureren op basis van de opgegeven argumenten.
if ($args['trace'] ??= false) require_once __DIR__.'/classes/trace.php';
require_once __DIR__.'/functions'.($args['trace'] ? '.trace.php' : '.php');
require_once __DIR__.'/classes/obj.php';
require_once __DIR__.'/classes/req.php';
require_once __DIR__.'/classes/res.php';
$args['app']       ??  error('No "app" path defined');
$args['debug']     ??= false;
$args['build']     ??= false;
$args['host']      ??= null;
$args['control']   ??= ($args['build'] && $args['debug']) ? 'phlo' : false;
$args['auth']      ??= false;
$args['data']      ??= $args['app'].'data/';
$args['php']       ??= $args['app'].'php/';
$args['www']       ??= $args['app'].'www/';
$args['cli']       ??= ZEND_THREAD_SAFE ? 'php-zts' : 'php';
$args['thread']    ??= false;
$args['daemon']    ??= false;
$args['build'] && $args['thread'] && error('Phlo build and thread mode cannot be combined');
$args['build'] && !is_file($args['data'].'app.json') && error('Phlo build mode requires data/app.json');
$args['auth'] && !$args['build'] && error('Auth requires build mode');
foreach ($args as $key => $value) define($key, $value);
define('engine', __DIR__.slash);
if ($args['debug']) require_once __DIR__.'/debug.php';
if ($args['build']) require_once __DIR__.'/classes/changed.php';
if ($args['daemon']) require_once __DIR__.'/classes/daemon.php';
if ($args['trace']) trace::boot($args['app']);
set_error_handler(static function(int $level, string $msg, string $file = '', int $line = 0):bool {
	if (!(error_reporting() & $level)) return false;
	throw new ErrorException($msg, 0, $level, $file, $line);
});
set_exception_handler('phlo_exception');
spl_autoload_register(static function(string $class):void {
	static $map = null, $mtime = null;
	$file = php.'classmap.php';
	if ($map === null || $mtime !== (is_file($file) ? filemtime($file) : null)){
		$map   = is_file($file) ? require $file : [];
		$mtime = is_file($file) ? filemtime($file) : null;
	}
	if (isset($map[$class])){ require_once php.$map[$class]; return; }
});
if ($args['build']){
	$engineMap = ['build' => 'build', 'reflect' => 'reflect', 'build_file' => 'file', 'build_node' => 'node', 'build_builder' => 'builder', 'build_css' => 'css', 'build_icons' => 'icons'];
	spl_autoload_register(static function(string $class) use ($engineMap):void {
		$name = $engineMap[strtolower($class)] ?? null;
		if ($name !== null) require_once engine.'classes/'.$name.'.php';
	});
}
defined('composer') && spl_autoload_register(static function(string $class):void {
	static $loaded = false;
	if ($loaded) return;
	$loaded = true;
	require_once composer.'vendor/autoload.php';
	foreach (spl_autoload_functions() as $fn){
		if (is_array($fn) && ($fn[0] ?? null) instanceof \Composer\Autoload\ClassLoader){
			spl_autoload_unregister($fn);
			spl_autoload_register($fn);
			$fn[0]->loadClass($class);
			return;
		}
	}
});
if ($args['thread'] !== false && PHP_SAPI !== 'cli'){
	ignore_user_abort(true);
	$handle = static function():void { phlo_thread(); };
	for ($i = 1; !$args['thread'] || $i <= $args['thread']; ++$i){
		$keepRunning = frankenphp_handle_request($handle);
		phlo('tech/reset');
		if (session_status() === PHP_SESSION_ACTIVE) session_write_close();
		gc_collect_cycles();
		if (!$keepRunning) break;
	}
	return;
}
phlo_thread();
function

phlo_async(string $cb, ...$args):bool

/phlo/resources/phlo.async.phlo line 9

Run an app target in the background, via the daemon pool or a one-shot CLI process

Fire and forget: it starts an app target and returns at once, so nothing that follows can see the result or whether it went well. Use it for work a visitor should not wait on, and let the job write its own outcome somewhere you can read back. Use phlo_sync when you need the answer, await when you need several.

asynccliprocessbackgroundappdaemon
Voert een callbackfunctie asynchroon uit, waarbij eventuele extra argumenten worden doorgegeven, en retourneert de proces-ID als het succesvol is.
	if (daemon) return daemon::fire($cb, $args)
	$cmd = cli.space.escapeshellarg($_SERVER['SCRIPT_FILENAME']).space.escapeshellarg($cb).loop($args, fn($a) => space.escapeshellarg((string)$a), void).' > /dev/null 2>&1 & echo $!'
	exec($cmd, $r)
	return isset($r[0]) && ctype_digit($r[0]) && (int)$r[0] > 0
function

phlo_cli(array $args):void

/phlo/phlo.php line 191
if (!$args) return;
$target = array_shift($args);
$result = phlo_dispatch($target, $args);
if (isset($result)) print(json_encode($result, jsonFlat).lf);
function

phlo_dispatch(string $target, array $args = []):mixed

/phlo/phlo.php line 178
if (str_contains($target, dot)){
	[$object, $method] = explode(dot, $target, 2);
	$handle = phlo($object);
	return $args ? $handle->$method(...$args) : ($handle->objHasMethod($method) ? $handle->$method() : $handle->$method);
}
if (str_contains($target, '::')){
	[$class, $method] = explode('::', $target, 2);
	return $class::$method(...$args);
}
return $target(...$args);
function

phlo_exception(Throwable $e):void

/phlo/phlo.php line 34
Behandelt uitzonderingen door het Throwable-object door te geven aan de phlo_error_handle functie voor verwerking.
require_once engine.'error.php';
phlo_error_handle($e);
function

phlo_exists(string $obj):bool

/phlo/resources/phlo.exists.phlo line 8

Check if compiled Phlo class exists

Asks whether a Phlo object was built, by looking for the generated PHP rather than by loading anything, so it costs nothing and triggers no autoload. Use it to make a resource optional: check first, then call. This is a build question, not a runtime one, so a resource added after the last build answers no until it is rebuilt.

phloexistsclassbuildruntime
Controleert of een specifiek PHP-bestand bestaat op het opgegeven objectpad.
is_file(php.strtr($obj, [us => dot]).'.php')
function

phlo_load(bool $http):void

/phlo/phlo.php line 154
Laadt de noodzakelijke runtime-bestanden voor de applicatie, waarbij ervoor wordt gezorgd dat de applicatie slechts eenmaal wordt geladen en dat het juiste contenttype wordt ingesteld voor HTTP-responses.
static $loaded = false, $loadedApp = null;
if ($loaded && $loadedApp === app){
	if ($http && !phlo('res')->type) phlo('res')->type = 'text/html; charset=UTF-8';
	return;
}
if (build && (!is_file(php.'functions.php') || !is_file(php.'app.php') || build_base::changed())){
	debug('Builder started');
	$changed = build::run();
	$changed && debug('Built '.implode(', ', array_map('basename', $changed)).' ('.count($changed).')');
}
if (!is_file(php.'functions.php') || !is_file(php.'app.php')) error('Compiled runtime not available');
if (!$loaded){
	require_once php.'functions.php';
	$loaded = true;
}
if ($loadedApp !== app){
	require_once php.'app.php';
	$loadedApp = app;
}
if ($http && !phlo('res')->type) phlo('res')->type = 'text/html; charset=UTF-8';
function

phlo_serve():void

/phlo/phlo.php line 198
ini_set('display_errors', 'stderr');
stream_set_blocking(STDIN, true);
fwrite(STDOUT, json_encode(['t' => 'ready']).lf);
while (($line = fgets(STDIN)) !== false){
	$line = trim($line);
	if ($line === void) continue;
	$msg    = json_decode($line, true) ?: [];
	$id     = $msg['id']     ?? null;
	$target = (string)($msg['target'] ?? void);
	$args   = (array)($msg['args'] ?? []);
	$stream = (bool)($msg['stream'] ?? false);
	$lineBuf = void;
	$streamError = null;
	$emit = static function(string $chunk) use (&$lineBuf, &$streamError, $id):string {
		$lineBuf .= $chunk;
		while (($pos = strpos($lineBuf, lf)) !== false){
			$out = substr($lineBuf, 0, $pos);
			$lineBuf = substr($lineBuf, $pos + 1);
			if ($streamError !== null) continue;
			try { fwrite(STDOUT, json_encode(['id' => $id, 't' => 'line', 'data' => $out], jsonFlat | JSON_THROW_ON_ERROR).lf); }
			catch (JsonException $e){ $streamError = $e; }
		}
		return void;
	};
	try {
		if ($target === void) error('No target');
		if ($stream){
			ob_start($emit, 1);
			$result = phlo_dispatch($target, $args);
			while (ob_get_level()) ob_end_flush();
			if ($streamError !== null) throw $streamError;
			if ($lineBuf !== void) fwrite(STDOUT, json_encode(['id' => $id, 't' => 'line', 'data' => $lineBuf], jsonFlat | JSON_THROW_ON_ERROR).lf);
		}
		else $result = phlo_dispatch($target, $args);
		fwrite(STDOUT, json_encode(['id' => $id, 't' => 'done', 'result' => $result], jsonFlat | JSON_THROW_ON_ERROR).lf);
	}
	catch (Throwable $e){
		while (ob_get_level()) ob_end_clean();
		fwrite(STDOUT, json_encode(['id' => $id, 't' => 'error', 'message' => $e->getMessage()], jsonFlat | JSON_INVALID_UTF8_SUBSTITUTE).lf);
	}
	phlo('tech/reset');
	if (session_status() === PHP_SESSION_ACTIVE) session_write_close();
	gc_collect_cycles();
}
function

phlo_stream(string $cb, ...$args):Generator

/phlo/resources/phlo.stream.phlo line 9

Stream an app target's output line by line, via the daemon pool or a one-shot CLI process

For a job whose output you want while it runs rather than at the end: it yields line by line, so a foreach can pass every line straight to chunk() and a page fills up as the work happens. The generator only advances while you read it, so a caller that stops reading stops the job.

streamphlocliprocessyielddaemon
Stroomt uitvoer van een callbackfunctie, waardoor asynchrone verwerking van gegevens mogelijk is. Het kan in een daemon-modus werken of een opdracht in de CLI-context uitvoeren.
	if (daemon){
		yield from daemon::stream($cb, $args)
		return
	}
	yield from exec_stream(cli.space.escapeshellarg($_SERVER['SCRIPT_FILENAME']).space.escapeshellarg($cb).loop($args, fn($a) => space.escapeshellarg((string)$a), void))
function

phlo_sync(string $cb, ...$args)

/phlo/resources/phlo.sync.phlo line 9

Run an app target synchronously, via the daemon pool or a one-shot CLI process

Runs an app target and gives you its return value, in the pool under the daemon and as a CLI process without one. JSON output is decoded, anything else comes back as text, and a job that answers with an error field raises it here, so a failure surfaces in the caller rather than being swallowed.

synccliprocessappdaemon
Voert een callbackfunctie synchronisch uit, waarbij eventuele extra argumenten worden doorgegeven, en retourneert het resultaat als een JSON-object of een foutmelding als de uitvoering mislukt.
	if (daemon) return daemon::run($cb, $args)
	$cmd = cli.space.escapeshellarg($_SERVER['SCRIPT_FILENAME']).space.escapeshellarg($cb).loop($args, fn($a) => space.escapeshellarg((string)$a), void)
	exec($cmd.' 2>&1', $r, $code)
	$out = implode(lf, $r)
	if ($code !== 0) error('Could not execute "'.esc($cb).'" via CLI')
	$j = json_decode($out, true)
	if (json_last_error() !== JSON_ERROR_NONE) return $out
	if (is_array($j) && isset($j['error'])) error($j['error'])
	return $j
function

phlo_thread():void

/phlo/phlo.php line 116
try {
	$req = phlo('req');
	if ($req->cli){
		$target = $req->args[0] ?? void;
		if (str_starts_with($target, 'build::') || str_starts_with($target, 'reflect::')){
			phlo_cli($req->args);
			return;
		}
		phlo_load(false);
		phlo('app');
		phlo_cli($req->args);
		return;
	}
	$isControl = build && debug && control && str_starts_with($req->path.slash, control.slash);
	if (auth && !$isControl){
		phlo_auth('site', 'Phlo App - '.host);
		if (phlo('res')->done) return;
	}
	if ($isControl){
		require_once engine.'control.php';
		phlo_control::handle(substr($req->path, strlen(control) + 1));
		phlo('res')->render();
		return;
	}
	phlo_load(true);
	phlo('app');
	phlo('res')->render();
}
catch (RuntimeException $e){
	if ($e->getMessage() === 'PhloDump') return;
	phlo_exception($e);
}
catch (Throwable $e){
	phlo_exception($e);
}
function

public_address(string $url):?string

/phlo/resources/HTTP.phlo line 50

HTTP request helper via cURL

One function for a whole request: a URL and headers is a GET, and POST, PUT, PATCH, QUERY or DELETE named as an argument decides the rest. Pass an array with JSON true and it is sent as JSON. The timeout is fifteen seconds and it is a real limit, so raise it deliberately for a slow API rather than by accident. Pass response by reference to see the status and the headers, which is the only way to tell an empty answer from a failure. For a URL that came from outside, such as a webhook or an image to fetch, pass public: true: it reaches only a public address, the one it checked, and follows no redirect, so a visitor cannot aim it at a service inside your network.

httpcurlrequestapi
The address a URL reaches when every address its host resolves to is public: not loopback,
	$parts = parse_url($url)
	if (!in_array(strtolower((string)($parts['scheme'] ?? void)), ['http', 'https'], true) || !($host = trim((string)($parts['host'] ?? void), '[]'))) return null
	$ips = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : array_merge(gethostbynamel($host) ?: [], array_column(@dns_get_record($host, DNS_AAAA) ?: [], 'ipv6'))
	foreach ($ips AS $ip){
		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) return null
		if (preg_match('/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./', $ip) || preg_match('/^::ffff:/i', $ip)) return null
	}
	return $ips[0] ?? null
function

sanitize_allow():array

/phlo/resources/sanitize.phlo line 22

HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places

sanitize_html($html) keeps the markup of a mail, an editor or an import that is text and layout, and removes what can run: script, style, frames, forms, svg and every event handler and style attribute. An unknown tag is unwrapped, so its text stays; href and src go only to http, https, mailto, tel or a relative path, and src also to a data: image. Pass your own allowlist, tag => attributes, to keep less or more. Run it on input that becomes HTML; text you show as text only needs esc().

htmlsanitizexsssecurityallowlist
	$cell = ['colspan', 'rowspan']
	$tags = array_fill_keys(['p', 'br', 'hr', 'strong', 'b', 'em', 'i', 'u', 's', 'sub', 'sup', 'small', 'mark', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'span', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'caption'], [])
	return [...$tags, 'a' => ['href', 'title'], 'img' => ['src', 'alt', 'title', 'width', 'height'], 'th' => $cell, 'td' => $cell]
function

sanitize_html(string $html, ?array $allow = null):string

/phlo/resources/sanitize.phlo line 9

HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places

sanitize_html($html) keeps the markup of a mail, an editor or an import that is text and layout, and removes what can run: script, style, frames, forms, svg and every event handler and style attribute. An unknown tag is unwrapped, so its text stays; href and src go only to http, https, mailto, tel or a relative path, and src also to a data: image. Pass your own allowlist, tag => attributes, to keep less or more. Run it on input that becomes HTML; text you show as text only needs esc().

htmlsanitizexsssecurityallowlist
	if (trim($html) === void) return void
	$allow ??= sanitize_allow()
	$dom = new DOMDocument
	@$dom->loadHTML('<?xml encoding="UTF-8"><div>'.$html.'</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NONET)
	$root = $dom->getElementsByTagName('div')->item(0)
	if (!$root) return void
	sanitize_walk($root, $allow)
	$out = void
	foreach ($root->childNodes AS $child) $out .= $dom->saveHTML($child)
	return $out
function

sanitize_url(string $url, bool $image = false):bool

/phlo/resources/sanitize.phlo line 55

HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places

sanitize_html($html) keeps the markup of a mail, an editor or an import that is text and layout, and removes what can run: script, style, frames, forms, svg and every event handler and style attribute. An unknown tag is unwrapped, so its text stays; href and src go only to http, https, mailto, tel or a relative path, and src also to a data: image. Pass your own allowlist, tag => attributes, to keep less or more. Run it on input that becomes HTML; text you show as text only needs esc().

htmlsanitizexsssecurityallowlist
A link without a scheme stays on the site; one with a scheme goes only where nothing runs.
	$url = preg_replace('/[\x00-\x20\x7f]+/', void, html_entity_decode($url, ENT_QUOTES | ENT_HTML5, 'UTF-8'))
	if (!preg_match('/^([a-z][a-z0-9+.-]*):/i', $url, $m)) return true
	return in_array(strtolower($m[1]), ['http', 'https', 'mailto', 'tel'], true) || ($image && (bool)preg_match('~^data:image/(?:png|jpe?g|gif|webp);base64,~i', $url))
function

sanitize_walk(DOMNode $node, array $allow):void

/phlo/resources/sanitize.phlo line 30

HTML from outside made safe to show: an allowlist of tags and attributes, scripts and handlers gone, links only to safe places

sanitize_html($html) keeps the markup of a mail, an editor or an import that is text and layout, and removes what can run: script, style, frames, forms, svg and every event handler and style attribute. An unknown tag is unwrapped, so its text stays; href and src go only to http, https, mailto, tel or a relative path, and src also to a data: image. Pass your own allowlist, tag => attributes, to keep less or more. Run it on input that becomes HTML; text you show as text only needs esc().

htmlsanitizexsssecurityallowlist
A tag whose content is code goes with its content, an unknown tag is unwrapped so its text stays,
	foreach (iterator_to_array($node->childNodes) AS $child){
		if ($child instanceof DOMElement){
			$tag = strtolower($child->tagName)
			if (in_array($tag, ['script', 'style', 'iframe', 'frame', 'frameset', 'object', 'embed', 'applet', 'form', 'input', 'button', 'select', 'textarea', 'svg', 'math', 'noscript', 'template', 'head', 'link', 'meta', 'base', 'title'], true)){
				$node->removeChild($child)
				continue
			}
			sanitize_walk($child, $allow)
			if (!isset($allow[$tag])){
				while ($child->firstChild) $node->insertBefore($child->firstChild, $child)
				$node->removeChild($child)
				continue
			}
			foreach (iterator_to_array($child->attributes) AS $attr){
				$name = strtolower($attr->name)
				$keep = in_array($name, $allow[$tag], true) && (!in_array($name, ['href', 'src'], true) || sanitize_url($attr->value, $name === 'src'))
				$keep || $child->removeAttribute($attr->name)
			}
		}
		elseif (!($child instanceof DOMText)) $node->removeChild($child)
	}
function

select(...$args):string

/phlo/resources/tags.form.phlo line 11

DOM form tags for button, input, select and textarea

button(), input(), select() and textarea() are tag() with the name filled in, so they take the same named arguments and the same escaping. They exist because these four appear so often that the name is noise.

formtagshtmlview
Maakt een 'select' HTML-element met de opgegeven argumenten als attributen en opties.
tag('select', ...$args)
function

setting(?string $key = null, $value = null):mixed

/phlo/resources/settings.phlo line 9

Persistent app settings in data/settings.json: setting() lists everything, setting(key) reads one value or null, setting(key, value) writes

Three shapes in one function: setting() gives everything, setting(key) reads one value or null, setting(key, value) writes and saves at once. It is meant for the handful of choices an app keeps, in data/settings.json, not for data with a life of its own; anything you would want to query or relate belongs in a model.

settingsconfigstoragejson
	$store = %JSON('settings', assoc: true)
	if ($key === null) return $store->objData
	if (func_num_args() > 1){
		$store->$key = $value
		$store->objChanged && $store->objWrite($store->objData)
	}
	return $store->$key
function

slug(string $text):string

/phlo/resources/slug.phlo line 8

Convert text to URL slug

Makes a URL slug: accents are folded to their ascii letter, everything else becomes a dash. Two different titles can produce the same slug, so check for a collision before you use one as an id.

slugurlstringformat
Converteert een gegeven string naar een URL-vriendelijke slug door niet-alfanumerieke tekens te verwijderen, naar kleine letters om te zetten en spaties door streepjes te vervangen.
trim(preg_replace('/[^a-z0-9]+/', dash, strtolower(iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text))), dash)
function

stream($data = null, string $type = 'application/octet-stream', ?string $name = null):void

/phlo/resources/stream.phlo line 9

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

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.

streambinaryrawdatadownload
	$res = %res
	$cli = %req->cli
	!$res->streaming && $res->done && error('Output already started, invalid stream()')
	if (!$res->streaming){
		$res->streaming = true
		$res->type = $type
		$res->header('Cache-Control', 'no-store')
		$res->header('X-Content-Type-Options', 'nosniff')
		$res->header('X-Accel-Buffering', 'no')
		$name === null || $res->header('Content-Disposition', 'attachment; filename="'.str_replace('"', '', $name).'"')
		$res->render()
	}
	if ($data === null) return
	foreach (is_iterable($data) ? $data : [$data] as $part){
		print((string)$part)
		$cli || [@ob_flush(), flush()]
	}
function

tag(string $tagName, ?string $inner = null, ...$args):string

/phlo/resources/tag.phlo line 9

Generate HTML tag string with attributes

One function for every element: attributes are named arguments, an underscore becomes a dash, so data_id turns into data-id, and true gives a bare attribute like required. Values are escaped, and an attribute with null is left out, which is what lets an optional attribute be written without a condition around it. Pass no inner content and you get a single tag without a closing one.

taghtmlrenderview
Genereert een HTML-tag met de opgegeven naam, optionele inhoud en extra attributen.
"<$tagName".loop(array_filter($args, fn($value) => !is_null($value)), fn($value, $key) => space.strtr($key, [us => dash]).($value === true ? void : '="'.esc($value).'"'), void).'>'.(is_null($inner) ? void : "$inner</$tagName>")
function

textarea(...$args):string

/phlo/resources/tags.form.phlo line 12

DOM form tags for button, input, select and textarea

button(), input(), select() and textarea() are tag() with the name filled in, so they take the same named arguments and the same escaping. They exist because these four appear so often that the name is noise.

formtagshtmlview
Maakt een 'textarea' HTML-element met de opgegeven argumenten.
tag('textarea', ...$args)
function

time_human(?int $time = null):string

/phlo/resources/time.human.phlo line 8

Convert timestamp age to human label

Rounds a timestamp to one unit that reads well, so a moment ago and last year both come out short. Define tsLabels to say it in another language; the frontend has the same trick with app.tsLabels, so both sides can speak the visitor's language.

timehumanageformat
Converteert een gegeven tijdstempel naar een leesbaar tijdsverschil formaat, zoals '2 dagen' of '3 uur'. Als er geen tijdstempel wordt opgegeven, wordt de huidige tijd gebruikt.
	static $labels
	$labels ??= last($labels = arr(seconds: 60, minutes: 60, hours: 24, days: 7, weeks: 4, months: 13, years: 1), defined('tsLabels') && $labels = array_combine(tsLabels, $labels), $labels)
	$age = time() - $time
	foreach ($labels AS $range => $multiplier){
		if ($age / $multiplier < 1.6583) break
		$age /= $multiplier
	}
	return round($age)." $range"
function

wsCast($wsTarget = 'all', $wsHost = host, $wsPort = daemon, $wsExcept = void, ...$data):int

/phlo/resources/wsCast.phlo line 11

Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels

Sends a message to connected clients from anywhere in the backend, without a socket of your own: it goes over the daemon's bridge. wsTarget picks who: all, token:<t>, token:not:<t>, socket:<s> or channel:<name>, a channel the app filled with wsJoin(); wsExcept leaves one connection out, which is how you avoid echoing an action back to the person who caused it. It returns how many connections it reached, and without a running daemon that is 0: it never throws, so a cast cannot break the request that sends it.

websocketcastrealtimehttpdaemon
A cast is a notification, never a reason for the request to fail: without a daemon it reaches
	try {
		$answer = HTTP('http://127.0.0.1:'.$wsPort.'/message', JSON: true, POST: arr(host: $wsHost, target: $wsTarget, except: $wsExcept, data: $data))
	}
	catch (\Throwable $e){
		return 0
	}
	return (int)(json_decode((string)$answer, true)['sent'] ?? 0)
function

wsChannel(string $action, string $channel, string $socket, string $token, $host, $port):int

/phlo/resources/wsCast.phlo line 28

Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels

Sends a message to connected clients from anywhere in the backend, without a socket of your own: it goes over the daemon's bridge. wsTarget picks who: all, token:<t>, token:not:<t>, socket:<s> or channel:<name>, a channel the app filled with wsJoin(); wsExcept leaves one connection out, which is how you avoid echoing an action back to the person who caused it. It returns how many connections it reached, and without a running daemon that is 0: it never throws, so a cast cannot break the request that sends it.

websocketcastrealtimehttpdaemon
	try {
		$answer = HTTP('http://127.0.0.1:'.$port.slash.$action, JSON: true, POST: array_filter(arr(host: $host, channel: $channel, socket: $socket, token: $token)))
	}
	catch (\Throwable $e){
		return 0
	}
	return (int)(json_decode((string)$answer, true)['members'] ?? 0)
function

wsJoin(string $channel, string $wsSocket = void, string $wsToken = void, $wsHost = host, $wsPort = daemon):int

/phlo/resources/wsCast.phlo line 24

Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels

Sends a message to connected clients from anywhere in the backend, without a socket of your own: it goes over the daemon's bridge. wsTarget picks who: all, token:<t>, token:not:<t>, socket:<s> or channel:<name>, a channel the app filled with wsJoin(); wsExcept leaves one connection out, which is how you avoid echoing an action back to the person who caused it. It returns how many connections it reached, and without a running daemon that is 0: it never throws, so a cast cannot break the request that sends it.

websocketcastrealtimehttpdaemon
Puts a socket, or every socket a token has now, in a channel, so a cast to channel:<name> reaches it;
wsChannel('join', $channel, $wsSocket, $wsToken, $wsHost, $wsPort)
function

wsLeave(string $channel = void, string $wsSocket = void, string $wsToken = void, $wsHost = host, $wsPort = daemon):int

/phlo/resources/wsCast.phlo line 26

Broadcast a message to WebSocket clients via the daemon's cast bridge, and put sockets in channels

Sends a message to connected clients from anywhere in the backend, without a socket of your own: it goes over the daemon's bridge. wsTarget picks who: all, token:<t>, token:not:<t>, socket:<s> or channel:<name>, a channel the app filled with wsJoin(); wsExcept leaves one connection out, which is how you avoid echoing an action back to the person who caused it. It returns how many connections it reached, and without a running daemon that is 0: it never throws, so a cast cannot break the request that sends it.

websocketcastrealtimehttpdaemon
wsChannel('leave', $channel, $wsSocket, $wsToken, $wsHost, $wsPort)

Laatst bijgewerkt op 30-10-2026

We gebruiken essentiële cookies om deze site te laten werken. Met uw toestemming gebruiken we ook analytics om de site te verbeteren.