Skip to content

lib/ namespace map ​

Everything in lib/ is a reusable library class. Controllers in controllers/ consume these classes; they never access the database or filesystem directly without going through a lib/ abstraction.


Namespace overview ​

Namespace / filePathRole
Bdus\Applib/Bdus/App.phpApplication orchestrator
Bdus\Routerlib/Bdus/Router.phpFastRoute dispatcher + privilege map
Bdus\Dispatcherlib/Bdus/Dispatcher.phpAuth gate + DI + controller invocation
Bdus\Controllerlib/Bdus/Controller.phpAbstract base for all controllers
Bdus\Utilslib/Bdus/Utils.phpStatic utility helpers
Auth\CurrentUserlib/Auth/CurrentUser.phpRequest-scoped authenticated user
Auth\ApiKeyAuthlib/Auth/ApiKeyAuth.phpAPI key authentication
Auth\RateLimiter, Auth\ClientIplib/Auth/RateLimiter.php, lib/Auth/ClientIp.phpRequest limits for API keys and failed logins; client address behind a trusted proxy
Record\Purgelib/Record/Purge.phpRetention: delete or anonymise old records and their version history (bin/purge-records.php)
Auth\Authorizationlib/Auth/Authorization.phpPrivilege check helpers
Auth\Channellib/Auth/Channel.phpWhere the request comes from (web, api, mcp, import, cli), recorded with every history entry
Auth\WriteGatelib/Auth/WriteGate.phpMay the principal write to this record? Tier or rule, ownership, row scope, locks; a plugin row follows its host
Auth\Accesslib/Auth/Access.phpTable- and row-level access: group rules and locks (Groups & permissions)
Auth\Passwordlib/Auth/Password.phpbcrypt hash / verify
JWT\JwtManagerlib/JWT/JwtManager.phpJWT issue / verify / peek
Config\Configlib/Config/Config.phpConfig facade (dot-notation access)
Config\Loadlib/Config/Load.phpConfig bootstrap — picks DB or file loader
Config\LoadFromDBlib/Config/LoadFromDB.phpDB-backed config reader
Config\ToDBlib/Config/ToDB.phpPersists config changes to DB
Config\ToFileslib/Config/ToFiles.phpConfig → JSON file writer (legacy fallback)
Config\AppSettingslib/Config/AppSettings.phpApp-level settings reader
Config\GeofaceConfiglib/Config/GeofaceConfig.phpGeoFace / map layer config
Config\CharPalettelib/Config/CharPalette.phpChar maps (strip of special characters under long_text / md): built-in presets, name resolution, validation of the application's own (bdus_cfg_app.char_maps, M056)
Config\ConfigExceptionlib/Config/ConfigException.phpConfig-specific exception
DB\DBlib/DB/DB.phpPDO wrapper (SQLite / MySQL / PostgreSQL)
DB\DBInterfacelib/DB/DBInterface.phpDB contract
DB\DBExceptionlib/DB/DBException.phpDB exceptions
DB\Inspectlib/DB/Inspect.phpEngine-dispatch for schema introspection
DB\Inspect\Mysqllib/DB/Inspect/Mysql.phpMySQL introspection
DB\Inspect\Postgreslib/DB/Inspect/Postgres.phpPostgreSQL introspection
DB\Inspect\Sqlitelib/DB/Inspect/Sqlite.phpSQLite introspection
DB\Alterlib/DB/Alter.phpEngine-dispatch for schema modification
DB\Alter\Mysqllib/DB/Alter/Mysql.phpMySQL ALTER operations
DB\Alter\Postgreslib/DB/Alter/Postgres.phpPostgreSQL ALTER operations
DB\Alter\Sqlitelib/DB/Alter/Sqlite.phpSQLite ALTER operations
DB\Export\Exportlib/DB/Export/Export.phpExport orchestrator
DB\Export\CSVlib/DB/Export/CSV.phpCSV export
DB\Export\JSONlib/DB/Export/JSON.phpJSON export
DB\Export\XLSXlib/DB/Export/XLSX.phpExcel export
DB\Validate\Validatelib/DB/Validate/Validate.phpValidation runner
DB\Validate\DbCfgAlignlib/DB/Validate/DbCfgAlign.phpDB ↔ config schema alignment
DB\Validate\DumpExistslib/DB/Validate/DumpExists.phpChecks backup tool availability
DB\Validate\Filesystemlib/DB/Validate/Filesystem.php.htaccess / filesystem sanity
DB\Validate\Infolib/DB/Validate/Info.phpApp info collector
DB\Validate\Resplib/DB/Validate/Resp.phpValidation response builder
DB\Validate\SystemTableslib/DB/Validate/SystemTables.phpChecks required system tables
DB\System\Managelib/DB/System/Manage.phpCRUD on system/data tables
DB\System\CreateApplib/DB/System/CreateApp.phpNew application wizard
DB\System\Migratelib/DB/System/Migrate.phpSchema migration runner
DB\System\Upgraderlib/DB/System/Upgrader.phpApplies the pending minor migrations of one app (admin endpoint and bin/upgrade-app.php); refuses a major upgrade
DB\System\Migrations\Mxxxlib/DB/System/Migrations/24 migration classes (M001–M024)
DB\Engines\AvailableEngineslib/DB/Engines/AvailableEngines.phpLists supported DB engines
DB\LogDBHandlerlib/DB/LogDBHandler.phpMonolog handler → bdus_log table
SQL\QueryFromRequestlib/SQL/QueryFromRequest.phpMain query builder — converts $request array to SQL
SQL\QueryObjectlib/SQL/QueryObject.phpLow-level fluent query builder (internal)
SQL\Filter\JsonFilterlib/SQL/Filter/JsonFilter.phpDirectus-style filter → SQL WHERE
SQL\Filter\FilterExceptionlib/SQL/Filter/FilterException.phpFilter-specific exception
SQL\Validatorlib/SQL/Validator.phpField / operator allow-list checks
SQL\SqlExceptionlib/SQL/SqlException.phpSQL-layer exception
Record\Readlib/Record/Read.phpFetches record + plugins + links + files
Record\Expandlib/Record/Expand.phpfields= of the record list: parses rel.* tokens, nests plugin rows / lookup rows in batch (one IN query per relation, group rules applied)
Record\Editlib/Record/Edit.phpValidates + prepares record edits
Record\Persistlib/Record/Persist.phpLow-level persistence (INSERT/UPDATE/DELETE)
Record\Savelib/Record/Save.phpCreate or update one record with its plugin rows: access gate, payload shape, enforced values, validation, write. Request-independent
Record\Deletelib/Record/Delete.phpDelete one record after the access gate; request-independent
Record\Rslib/Record/Rs.phpAdd and remove stratigraphic relations (bdus_rs) after the checks; the relation codes and their inverses; shared by the REST endpoints and the MCP tools
Record\Validatorlib/Record/Validator.phpValidates a record payload against the table configuration; never writes
Record\FieldOptionslib/Record/FieldOptions.phpValues a field offers (table column, lookup table, vocabulary, static list), limited to readable rows
Config\TableSchemalib/Config/TableSchema.phpA table's schema as clients need it: fields, plugin tables, features
Template\Loaderlib/Template/Loader.phpLoads Twig print templates from DB
Mcp\Serverlib/Mcp/Server.phpMCP protocol layer: one JSON-RPC message in, status + body out; both protocol generations (MCP server)
Mcp\Tool, Mcp\Context, Mcp\ToolErrorlib/Mcp/Contract of a tool, what it receives, how it refuses
Mcp\ValidationTokenlib/Mcp/ValidationToken.phpThe token of the validate → write pairs (scope records, rs)
Mcp\Prompts, Mcp\PromptErrorlib/Mcp/The prompts of an application (bdus_mcp_prompts, M054): validation, order, rendering
Mcp\Tools\*lib/Mcp/Tools/The generic tools: guide, schema, vocabulary, records_read, aggregate, resolve, history, rs_read, records_validate, records_write, rs_validate, rs_write, records_delete
SQL\Aggregatelib/SQL/Aggregate.phpCOUNT / SUM / AVG / MIN / MAX over the rows of a QueryFromRequest request, grouped by up to two fields; used by the charts and by the MCP aggregate tool
Template\Assignlib/Template/Assign.phpRecord layouts per group: which templates a user's groups assign
Image\Resizerlib/Image/Resizer.phpResize / convert an uploaded image in place (Intervention)
Image\Presetslib/Image/Presets.phpDerived-image presets: validation, built-in thumb, lookup
Image\Watermarklib/Image/Watermark.phpOptional text watermark of a preset: validation, text resolution, rendering (bundled DejaVu Sans)
Image\Derivativelib/Image/Derivative.phpGenerates a preset version into cache/, purges it
Zotero\Clientlib/Zotero/Client.phpZotero API HTTP client
Zotero\ZoteroExceptionlib/Zotero/ZoteroException.phpZotero-specific exception
Pleiades\Clientlib/Pleiades/Client.phpPleiades gazetteer API HTTP client
Pleiades\PleiadesExceptionlib/Pleiades/PleiadesException.phpPleiades-specific exception
—lib/bootstrap.phpConstants, DB connection, auth setup
—lib/version.phpBDUS_VERSION constant

Namespace detail ​

Auth\ — Request authentication ​

CurrentUser is a static request-scoped store. Populated once in constants.php from validated JWT claims (or API key record), then read anywhere:

php
Auth\CurrentUser::id()              // int|null
Auth\CurrentUser::privilege()       // int|null  (1=superadmin … 40=readonly)
Auth\CurrentUser::isAuthenticated() // bool
Auth\CurrentUser::isApiKey()        // bool (false for JWT users)

ApiKeyAuth handles Authorization: Bearer {key} auth (the ?api_key= query-string form was removed: it ended up in access logs). Plain-text keys are never stored — only SHA-256 hashes in bdus_api_keys.


JWT\ — Token management ​

JwtManager is a thin wrapper around firebase/php-jwt.

MethodPurpose
generate(user, app)Issues a signed JWT (1-day expiry)
decode(token, app)Verifies signature + expiry, returns claims
peekApp(token)Reads app claim without verifying (loads the right secret)
refresh(token, app)Issues a new token from a still-valid one

Per-app secrets live at projects/{app}/.jwt_secret (mode 0600), generated on first use if absent. The legacy location projects/{app}/cfg/.jwt_secret is probed for backwards compatibility.


Config\ — Application configuration ​

Config provides dot-notation access to the merged config:

php
$cfg->get('main.status')           // app status string, e.g. 'on'
$cfg->get('tables.0.name')         // first table name
$cfg->get('geoface.layers.0.url')  // first map layer URL

Config is stored in DB (since M011) in bdus_cfg_* tables. Config\Load reads from DB; Config\ToDB / Config\ToFiles persist changes.

See Config & access control for the full schema.


DB\ — Database abstraction ​

DB\DB wraps PDO and dispatches schema operations to engine-specific implementations. Key method:

php
$db->query($sql, $params, 'read')      // returns rows array
$db->query($sql, $params, 'boolean')   // returns true|false
$db->query($sql, $params, 'id')        // returns last insert id

DB\Inspect introspects the live schema (column list, indexes, …). DB\Alter modifies the schema (add/rename/drop columns and tables). Both dispatch to engine-specific Mysql, Postgres, or Sqlite classes.

DB\System\Manage is the high-level CRUD layer for system and data tables:

php
$mgr = new Manage($db);
$mgr->getBySQL('bdus_users', 'email = ?', [$email]);
$mgr->editRow('bdus_users', $id, ['oauth_sub' => $sub]);

DB\System\CreateApp orchestrates new-application creation: creates the DB, installs system tables, seeds initial config.

DB\System\Migrate runs pending migrations. See DB migrations.

See Database layer for the full reference.


SQL\ — Query building ​

SQL\QueryFromRequest is the main entry point for all data queries. It converts a structured $request PHP array (with a type key: all, fast, sqlExpert, or filter) into a PDO-prepared SELECT statement. See SQL layer.

SQL\Filter\JsonFilter parses Directus-style filter arrays (['field' => ['_eq' => 'value']]) into SQL WHERE clauses.

SQL\QueryObject is the low-level fluent builder used internally by QueryFromRequest. Not called directly by controllers.


Record\ — Record lifecycle ​

Record\Read assembles a complete record response: fields + plugin rows + manual links + files.

Record\Edit stages changes on the model and delegates to Record\Persist.

Record\Save is the whole write path of one record (gate, validation with Record\Validator, then Edit / Persist), independent of the HTTP request.

Record\Persist writes a single atomic change: INSERT / UPDATE / DELETE.

See Record lifecycle.


Auth\ — Access control ​

Auth\Authorization holds the numeric privilege constants and can(), the single check used by controllers. Privilege levels:

LevelConstantMeaning
1Authorization::SUPERADMSuper admin — full access including schema changes
10Authorization::ADMAdmin — user management, backups, logs
20Authorization::UPDATEWriter — read + update records
25Authorization::CREATESelf writer — read + create, edit own records
30Authorization::READReader — read-only
39Authorization::ENTERCan log in, no data access

See Config & access control.


Template\ — Print templates ​

Template\Loader reads Twig template source from bdus_cfg_templates (DB-backed since M011). Provides compiled templates for print / preview.

Template\Assign resolves the templates a user's groups oblige them to use on a table (bdus_groups.layouts, M051): union over groups, unknown names ignored, null = no restriction. See Groups & permissions.


Image\ — Image handling ​

Image\Resizer uses intervention/image (GD) to downscale and/or convert an uploaded image in place, according to the app settings (maxImageSize, imageConvert, …).

Image\Presets validates and normalises the derived-image presets ({name, width, height, fit, format, quality}; fit is cover or inside), resolves the effective list (the built-in thumb is added when not defined) and finds one by name. The list is stored as JSON in bdus_cfg_app.image_presets (read and written by Config\AppSettings, exposed as main.imagePresets, saved by Config::save_app_properties).

Image\Watermark owns the optional watermark of a preset ({text, position, color, background, opacity, margin, size}): normalize() validates it when the preset is saved (called by Presets::normalize), resolveText() expands and sanitises the result at render time (no text when the template needs an attribution the file lacks), apply() draws box and text with the bundled font lib/Image/fonts/DejaVuSans.ttf (GD needs a font file and FreeType, both present in the image).

Image\Derivative builds one version of one file: generate($src, $dest, $preset, $attribution) decodes, crops (cover) or scales down (inside), encodes WebP/JPG into a hidden temp file and renames it into place. It refuses unreadable sources, unsupported types and sources over 100 megapixels. purgeFile($projDir, $uuid) removes every version of a file (projects/{app}/cache/*/{uuid}.*, failure markers included); purgePreset() empties a preset's folder.

Naming: File\Store. The single source of truth for where a binary lives: projects/{app}/files/{uuid}.{ext}, with bdus_files.uuid a random v4 value (Store::newUuid()) and the integer id only the internal key. Store::path() validates both parts (a canonical lower-case uuid, an extension of letters and digits) because the result is a filesystem path; Store::create() inserts the bdus_files row and returns {id, uuid}; Store::remove() deletes the binary and its derived versions (best effort). Nothing else builds a file path.

Repair and checks. File\UuidBackfill (assign missing uuids, rename binaries named by id, drop the id-keyed cache; plan() is the dry run) is the work of M060 and of bin/files-backfill-uuid.php; File\LegacyUrls finds old-style addresses (projects/{app}/files/{id}.ext, /api/file/{preset}/{id}.webp) in text fields, templates and the welcome text, read-only (--scan-urls); the migration verifier reports files without a uuid or whose binary is still named by id (file_uuids).

Presets (Image\Presets) carry access (public | inherit, default inherit) and enabled (default true; the system thumb is always enabled). File::serveDerived serves anonymously only when the preset is public and bdus_files.public = 1; otherwise it needs a principal who may read the file (FileAccess::mayRead); a disabled preset is a 404 for everyone. Dispatcher identifies the caller on this public route without ever requiring it (Router::OPTIONAL_AUTH_ROUTES: token, key or cookie when sent; a revoked or stale session is just anonymous). Presets::renderKey() is what a cache invalidation compares: a change of access or enabled keeps the cache. Migration M062 gives existing presets public + enabled.

Who may do what: Auth\FileAccess (see groups & permissions), how a file is sent: File\Delivery (content type, inline only for plain media, nosniff, sandbox CSP, safe Content-Disposition; HTML and anything that could run is only ever downloaded) and File::download (GET /api/file/{uuid}, plain 404 for anything unreadable, ETag revalidation, Cache-Control: private, no-cache). Cookie: Auth\SessionCookie, accepted by Dispatcher only for the GET routes listed in Router::COOKIE_ROUTES (today: the file download), carrying the same signed token as the header so revocation (token_version) applies. File\ConfigSeed seeds the configuration of the files table.

Serving and lifecycle. File::serveDerived (GET /api/file/{preset}/{uuid}.{ext}, public; the integer id is not an address) looks the preset up, generates on first request into cache/{preset}/{uuid}.{ext} and answers with ETag revalidation. A failure is a plain 404; a source that failed leaves {uuid}.{ext}.fail and is not retried until it changes. The versions are a rebuildable mirror: purgeFile is called wherever a file or its metadata changes (File::replaceFile, File::updateFile, Record::deleteFile, Persist record delete; all of them name the file by its uuid through File\Store), and Config::save_app_properties purges the folder of a preset that was changed or removed. cache/ is excluded from docker-backup.sh.