menu_book Navigation menu

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 SignatureDescription
resolveCascadingPath(string $path): string\|falseResolves 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): stringReturns the public URL for static assets (CSS, JS, images). Automatically handles the cascade and extension resources.
getMediaPath(string $relativePath): stringReturns the absolute URL for a media file located in the site's media/ directory.
getMediaUrl(int $id, string $size = 'large'): ?stringRetrieves the direct URL of a specific image variant (thumbnail, medium, etc.) by its Media ID.
getUploadUrlForAdmin(string $path): stringGenerates 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): stringGenerates a fully localized, SEO-friendly URL based on a Route Handle. Injects parameters into URL placeholders.
getLinkForContent(string $type, int|string $id): stringAutomatically resolves the public URL for any entity (Route, Entry, Taxonomy Term, User) based on its blueprint.
getPlatformLink(string $pattern, array $params = []): stringGenerates a URL for the central Admin Platform (e.g., sites/edit/12).
getPlatformUrl(): stringReturns the root URL of the Admin Platform by resolving the domain mapping.
isActiveRouteHandle(string $handle, array $params = []): stringReturns 'active' if the current request matches the handle/params. Supports prefix matching (e.g., admin.entries.).

Translation

Function SignatureDescription
getTranslation(string $key, array $params = [], bool $ucfirst = true, ?callable $transform = null): stringTranslates a string using the current language dictionary. Supports {placeholders}, pluralization via \|, and custom callback transformations.

Templates & UI Components

Function SignatureDescription
find_template_file(string $path): ?stringFinds the absolute path of a template file following the priority: Theme > Site > Extension > Core.
render_template(string $path, array\|object $data = []): stringRenders a template. Automatically detects if it should use the native PHP engine or the Twig engine.
include_styles(array $styles): voidInjects <link rel="stylesheet"> tags. Supports simple strings or arrays for attributes like media, integrity, or defer.
include_scripts(array $scripts): voidInjects <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(): stringGenerates 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 = []): stringGenerates hierarchical HTML for a menu handle. Supports custom wrappers, icons, and media images per item.
renderFooterCredits(): stringGenerates the HTML for the site copyright and "Powered by" credits based on CMS settings.

Images & Icons

Function SignatureDescription
renderImage(int\|array $media, string $size = 'large', array $attrs = []): voidOutputs a <picture> tag with AVIF/WebP sources, srcset for responsive sizes, and native lazy-loading.
renderIcon(string $library, string $name): stringReturns 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 SignatureDescription
buildTree(array $elements, string $idKey, string $parentKey): arrayHigh-performance iterative function to convert flat database rows into a nested hierarchical array.
renderTreeAsSelectOptions(array $tree, ...): voidRecursively outputs <option> tags with visual indentation for hierarchical dropdowns.
renderTreeAsCheckboxes(array $tree, ...): voidRecursively outputs nested checkboxes, ideal for category selection in forms.
renderTreeAsUl(array $tree, string $nameKey): voidRenders a simple nested <ul> / <li> structure from a tree array.
formatTime(int $minutes): stringFormats a duration into a human-readable string (e.g., "1 h 15").
truncateText(string $text, int $max = 160): stringStrips HTML and truncates a string, adding an ellipsis.
mb_ucfirst(string $str): stringMultibyte version of ucfirst(). Correctfully capitalizes accented characters (e.g., "é" -> "É").
generateAutoDescription(string $content, int $limit = 160): stringExtracts 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 SignatureDescription
recursiveFiles(string $dir, array $exts = ['php']): arrayScans a directory and returns all file paths matching the given extensions.
copy_recursive(string $src, string $dst): boolDeep copies a directory and its entire contents to a new destination.
delete_recursive(string $dir): boolRecursively deletes a directory and all its files/subfolders.
getDirectorySize(string $path): intCalculates the total size of a directory in bytes.
getDirectoryFileCount(string $dir): intReturns the total number of files within a directory tree.
formatBytes(int\|float $bytes, string $lang = 'en'): stringConverts bytes into KB, MB, GB, etc., with localized separators.
registerSystemNotifications(): voidRuns global system checks (Imagick availability, updates) and registers Admin notifications.

Helper Functions (Logic & API)

Function SignatureDescription
sendJsonResponse(bool $success, ...): voidThe universal API exit point. Sets headers, HTTP codes, and outputs a standardized JSON schema.
is_api_request(): boolDetects if the current request is an AJAX call or expects a JSON response via headers.
findTitleForSlug(?string $type, string $slug): stringQueries the database to find the translated title of a content item based on its slug.
getTitleForRouteHandle(string $handle): stringHeuristically determines a title for a route (e.g., "front.articles.index" -> "Articles").
generatePaginationUrl(int $page, string $param = 'page'): stringModifies the current query string to update the pagination index while preserving other filters.
renderPagination(int $curr, int $total, ...): stringOutputs smart HTML pagination with ellipsis (1 ... 4 5 6 ... 20).
generate_slug(string $text, ?array $uniqueness): stringTransliterates text to URL-friendly slugs. Can check DB tables to ensure uniqueness.
generate_uuid(): stringGenerates a cryptographically secure RFC 4122 Version 4 UUID.
send_email(string $from, ..., string $tpl, array $data): boolWrapper for PHPMailer. Handles SMTP, encryption, attachments, and template rendering.

SEO & Sitemap

Function SignatureDescription
update_listing_page_sitemap_for_route(string $handle): voidForces an XML sitemap update for a specific listing/archive route across all languages.
update_taxonomy_term_sitemap_entry(int $termId): voidUpdates or removes a specific taxonomy term from the XML sitemap based on its status.

Security & Errors

Function SignatureDescription
sanitizeHTML(string $html, string $preset = 'default'): stringHigh-performance HTMLPurifier wrapper. Uses presets (e.g., icon for <i> only) to strip XSS.
isPasswordValid(string $password): true\|arrayValidates 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.