Global Helpers & Functions
Pragma CMS provides a library of globally available PHP functions (functions.php). These helpers are designed to accelerate theme and extension development by abstracting complex core logic (caching, security, fallback hierarchies) into simple, one-line calls.
Paths & URLs
These functions manage the Pragma CMS file override system (Extension > Theme > Site > Core) and generate internal or external URLs.
| Function Signature | Description |
|---|---|
resolveCascadingPath(string $path): string\|false | Resolves a relative path to an absolute path using the Site -> Core hierarchy. Uses static memory caching for performance. |
getAssetsPath(string $path, bool $isTheme = false, ?string $ext = null): string | Returns the public URL for static assets (CSS, JS, images). Automatically handles the cascade and extension resources. |
getMediaPath(string $relativePath): string | Returns the absolute URL for a media file located in the site's media/ directory. |
getMediaUrl(int $id, string $size = 'large'): ?string | Retrieves the direct URL of a specific image variant (thumbnail, medium, etc.) by its Media ID. |
getUploadUrlForAdmin(string $path): string | Generates a URL for files in the uploads/ directory (typically used for non-public files in the back-office). |
getLink(string $handle, array $params = [], ?string $lang = null): string | Generates a fully localized, SEO-friendly URL based on a Route Handle. Injects parameters into URL placeholders. |
getLinkForContent(string $type, int|string $id): string | Automatically resolves the public URL for any entity (Route, Entry, Taxonomy Term, User) based on its blueprint. |
getPlatformLink(string $pattern, array $params = []): string | Generates a URL for the central Admin Platform (e.g., sites/edit/12). |
getPlatformUrl(): string | Returns the root URL of the Admin Platform by resolving the domain mapping. |
isActiveRouteHandle(string $handle, array $params = []): string | Returns 'active' if the current request matches the handle/params. Supports prefix matching (e.g., admin.entries.). |
Translation
| Function Signature | Description |
|---|---|
getTranslation(string $key, array $params = [], bool $ucfirst = true, ?callable $transform = null): string | Translates a string using the current language dictionary. Supports {placeholders}, pluralization via \|, and custom callback transformations. |
Templates & UI Components
| Function Signature | Description |
|---|---|
find_template_file(string $path): ?string | Finds the absolute path of a template file following the priority: Theme > Site > Extension > Core. |
render_template(string $path, array\|object $data = []): string | Renders a template. Automatically detects if it should use the native PHP engine or the Twig engine. |
include_styles(array $styles): void | Injects <link rel="stylesheet"> tags. Supports simple strings or arrays for attributes like media, integrity, or defer. |
include_scripts(array $scripts): void | Injects <script> tags. Automatically attaches the global CSP $nonce to each tag for security. |
renderHeader($page, $isTheme = true, $isAdmin = false) | Outputs the site or admin header based on context and theme availability. |
renderFooter($page, $isTheme = true, $isAdmin = false) | Outputs the site or admin footer with fallback logic. |
renderAdminPanel(): string | Generates the floating Admin Toolbar for logged-in users, featuring the responsive previewer and notifications. |
renderAdminSidebarLeft($page) | Outputs the standard left navigation sidebar for the Site Admin interface. |
renderAdminPlatformSidebarLeft() | Outputs the left navigation sidebar for the central Platform interface. |
renderMenu(string $handle, array $options = []): string | Generates hierarchical HTML for a menu handle. Supports custom wrappers, icons, and media images per item. |
renderFooterCredits(): string | Generates the HTML for the site copyright and "Powered by" credits based on CMS settings. |
Images & Icons
| Function Signature | Description |
|---|---|
renderImage(int\|array $media, string $size = 'large', array $attrs = []): void | Outputs a <picture> tag with AVIF/WebP sources, srcset for responsive sizes, and native lazy-loading. |
renderIcon(string $library, string $name): string | Returns HTML for icons (Material Symbols, FontAwesome, Flag Icons). Extensible via RENDER_CUSTOM_ICON hook. |
Formatting & Data Display
Helpers for transforming data and rendering complex UI structures like trees.
| Function Signature | Description |
|---|---|
buildTree(array $elements, string $idKey, string $parentKey): array | High-performance iterative function to convert flat database rows into a nested hierarchical array. |
renderTreeAsSelectOptions(array $tree, ...): void | Recursively outputs <option> tags with visual indentation for hierarchical dropdowns. |
renderTreeAsCheckboxes(array $tree, ...): void | Recursively outputs nested checkboxes, ideal for category selection in forms. |
renderTreeAsUl(array $tree, string $nameKey): void | Renders a simple nested <ul> / <li> structure from a tree array. |
formatTime(int $minutes): string | Formats a duration into a human-readable string (e.g., "1 h 15"). |
truncateText(string $text, int $max = 160): string | Strips HTML and truncates a string, adding an ellipsis. |
mb_ucfirst(string $str): string | Multibyte version of ucfirst(). Correctfully capitalizes accented characters (e.g., "é" -> "É"). |
generateAutoDescription(string $content, int $limit = 160): string | Extracts plain text from either raw HTML or Editor.js JSON block structures for SEO meta tags. |
array_insert_after(array &$arr, string $key, string $newK, $newV) | Injects a key-value pair into an associative array immediately after a specific target key. |
Filesystem & System
| Function Signature | Description |
|---|---|
recursiveFiles(string $dir, array $exts = ['php']): array | Scans a directory and returns all file paths matching the given extensions. |
copy_recursive(string $src, string $dst): bool | Deep copies a directory and its entire contents to a new destination. |
delete_recursive(string $dir): bool | Recursively deletes a directory and all its files/subfolders. |
getDirectorySize(string $path): int | Calculates the total size of a directory in bytes. |
getDirectoryFileCount(string $dir): int | Returns the total number of files within a directory tree. |
formatBytes(int\|float $bytes, string $lang = 'en'): string | Converts bytes into KB, MB, GB, etc., with localized separators. |
registerSystemNotifications(): void | Runs global system checks (Imagick availability, updates) and registers Admin notifications. |
Helper Functions (Logic & API)
| Function Signature | Description |
|---|---|
sendJsonResponse(bool $success, ...): void | The universal API exit point. Sets headers, HTTP codes, and outputs a standardized JSON schema. |
is_api_request(): bool | Detects if the current request is an AJAX call or expects a JSON response via headers. |
findTitleForSlug(?string $type, string $slug): string | Queries the database to find the translated title of a content item based on its slug. |
getTitleForRouteHandle(string $handle): string | Heuristically determines a title for a route (e.g., "front.articles.index" -> "Articles"). |
generatePaginationUrl(int $page, string $param = 'page'): string | Modifies the current query string to update the pagination index while preserving other filters. |
renderPagination(int $curr, int $total, ...): string | Outputs smart HTML pagination with ellipsis (1 ... 4 5 6 ... 20). |
generate_slug(string $text, ?array $uniqueness): string | Transliterates text to URL-friendly slugs. Can check DB tables to ensure uniqueness. |
generate_uuid(): string | Generates a cryptographically secure RFC 4122 Version 4 UUID. |
send_email(string $from, ..., string $tpl, array $data): bool | Wrapper for PHPMailer. Handles SMTP, encryption, attachments, and template rendering. |
SEO & Sitemap
| Function Signature | Description |
|---|---|
update_listing_page_sitemap_for_route(string $handle): void | Forces an XML sitemap update for a specific listing/archive route across all languages. |
update_taxonomy_term_sitemap_entry(int $termId): void | Updates or removes a specific taxonomy term from the XML sitemap based on its status. |
Security & Errors
| Function Signature | Description |
|---|---|
sanitizeHTML(string $html, string $preset = 'default'): string | High-performance HTMLPurifier wrapper. Uses presets (e.g., icon for <i> only) to strip XSS. |
isPasswordValid(string $password): true\|array | Validates a password against enterprise rules (12+ chars, mixed case, numbers, special symbols). |
logError(string $msg, string $lvl = 'ERROR', bool $forUser = false) | Logs errors to application.log. If $forUser is true, pushes the message to the frontend $page->errors array. |
displayError(?string $msg, int $code = 404, bool $json = false) | Terminates execution and displays a localized error page (403, 404, 500) or a JSON error response. |