You need to enable JavaScript to run this app.

Ana içeriğe geç

MyBB Plugin Development: Hook System, Secure Queries, and Settings

MyBB Plugin Development: Hook System, Secure Queries, and Settings

Administrator
MyBB Plugin Development: Hook System, Secure Queries, and Settings
MyBB Plugin Development: Hook System, Secure Queries, and Settings

MyBB’s enduring popularity among custom community builders stems from how effortlessly developers can extend core functionality without ever touching a single core PHP file. Through its lightweight, event-driven Plugin Hook System, standardized database abstraction layer, and self-contained installation lifecycle, a single clean PHP file dropped into /inc/plugins/ can introduce custom user awards, automated Discord/Telegram webhooks, advanced thread prefixes, or external single sign-on bridges. Yet hastily written plugins are also the single largest source of SQL injection flaws, Cross-Site Request Forgery (CSRF) exploits, and N+1 database bottlenecks on production forums. Mastering MyBB’s hook priorities, $mybb->get_input() sanitization, $db->escape_string() query safety, and clean settings/template lifecycle hooks separates fragile hacks from enterprise-ready MyBB extensions.

In 2026, authoring professional MyBB plugins requires strict adherence to PHP 8.3+ type safety, deterministic database schema migrations, batched query execution, and zero-residue uninstall routines.



1. The Event-Driven Hook Architecture: $plugins->add_hook()

Unlike heavyweight frameworks that rely on reflection-based dependency injection containers, MyBB uses an explicit, zero-overhead hook registry powered by inc/class_plugins.php. Throughout core controllers (global.php, showthread.php, newreply.php, member.php), MyBB executes $plugins->run_hooks('hook_name') at hundreds of strategic execution milestones.

Developers attach custom callbacks via $plugins->add_hook($hook, $function, $priority = 10, $file = ''):
  • Global vs. Conditional Hook Registration: Never attach heavy postbit or newreply_do_newreply_end hooks blindly on every page request. Wrap endpoint-specific hooks inside if(defined('THIS_SCRIPT')) checks (for example, checking THIS_SCRIPT == 'showthread.php') so irrelevant controllers execute zero unnecessary plugin registration code.
  • How Arguments Pass by Reference in MyBB Hooks: In MyBB’s hook dispatcher, single array arguments (such as $post inside the postbit hook or $thread inside forumdisplay_thread) are passed by reference automatically—allowing your function signature function myplugin_postbit(&$post) to mutate post arrays and inject custom template variables directly without return boilerplate.
  • Execution Priority Ordering: When multiple plugins modify the same output stream—such as custom BBCode parsers hooking into parse_message_start and parse_message_end—use explicit priority integers (e.g., 5 to run early before core sanitization, or 20 to run after standard formatting completes).

Alıntı:A well-engineered MyBB plugin behaves like a disciplined guest: it registers hooks only on the scripts that need them, batches its database queries outside loops, escapes every input and output, and leaves zero database debris when uninstalled.

2. Plugin Lifecycle Management: Install, Activate, Deactivate, and Uninstall

Every MyBB plugin file inside /inc/plugins/myplugin.php must begin with an explicit direct-access guard (if(!defined('IN_MYBB')) { die('Direct initialization of this file is not allowed.'); }) and expose five standardized lifecycle functions:

A. myplugin_info() (Metadata Descriptor)
Returns an associative array defining name, description, website, author, authorsite, version, codename (used for official MyBB Extend version checking), and compatibility (18*). Keep this function pure and fast—never run database queries inside _info(), because Admin CP calls it repeatedly when listing installed plugins.

B. myplugin_install() & myplugin_is_installed()
Use _install() strictly for one-time structural provisioning: creating custom InnoDB database tables (checking $db->table_exists() first), inserting setting groups into mybb_settinggroups and individual settings into mybb_settings, and calling rebuild_settings() so $mybb->settings['myplugin_enabled'] becomes immediately available across the Datacache.

C. myplugin_activate() & myplugin_deactivate()
Reserve _activate() and _deactivate() for reversible presentation changes—such as inserting custom master templates (sid = -2) into mybb_templates and injecting template variables via find_replace_templatesets() (included from MYBB_ROOT . 'inc/adminfunctions_templates.php'), then reversing those template replacements cleanly in _deactivate() without deleting user data.

D. myplugin_uninstall() (Clean Removal)
When an administrator clicks Uninstall, drop custom tables via $db->drop_table(), delete plugin rows from mybb_settings, mybb_settinggroups, and mybb_templates, purge custom cache keys from $cache, and invoke rebuild_settings().

3. Security Engineering: Input Sanitization, Escaping, and CSRF Defense

Because MyBB plugins run with full PHP and database privileges, every external input must pass through MyBB’s native defensive APIs:

  1. Strict Type Casting with $mybb->get_input(): Never access raw $_GET, $_POST, or $_REQUEST superglobals directly. Always retrieve typed inputs using $mybb->get_input('tid', MyBB::INPUT_INT) for integers, MyBB::INPUT_STRING for strings, and MyBB::INPUT_ARRAY for array payloads—preventing array-injection type errors in PHP 8.3+.
  2. SQL Injection Prevention via $db Abstraction Methods: Prefer MyBB’s parameterized helper methods—$db->insert_query(), $db->update_query(), and $db->delete_query()—which handle column quoting cleanly. When constructing custom SELECT or JOIN statements via $db->simple_select() or $db->query(), cast every numeric ID with (int) and wrap every string literal inside $db->escape_string().
  3. Cross-Site Scripting (XSS) Output Escaping: Before interpolating any user-controlled string—such as custom thread tags, badge titles, or external API descriptions—into an eval($templates->render(...)) template, sanitize it with htmlspecialchars_uni() so malicious <script> tags render harmlessly as literal text.
  4. Cross-Site Request Forgery (CSRF) Verification: Any front-end action, quick-toggle button, or XMLHTTP endpoint that modifies state must include {$mybb->post_code} in the request URL/payload and enforce verify_post_check($mybb->get_input('my_post_key')) as its very first instruction.

4. High-Performance Query Patterns and Caching Inside Plugins

Poorly designed plugins frequently ruin forum performance by firing repetitive database queries inside loops:
  • Batching Data in showthread_start Instead of postbit: If your plugin displays custom user badges or reputation stats next to every post on showthread.php, never run a SQL query inside postbit. Instead, hook into showthread_start (or postbit_prev / showthread_linear after $pids are collected), gather all unique uid values on the current page, execute one single SELECT query using WHERE uid IN (...), store results in a static PHP lookup map, and read from memory inside postbit.
  • Leveraging $cache->read() and $cache->update() for Global Plugin Data: If your plugin maintains small global lookup tables—such as custom prefix definitions, badge tiers, or partner domain rules—persist them inside MyBB’s $cache store so Redis or Memcached serves them in sub-millisecond RAM with zero MySQL queries per pageview.
  • Supporting Both MySQLi and Strict SQL Modes: Always test plugins with MySQL STRICT_TRANS_TABLES and ONLY_FULL_GROUP_BY enabled—providing explicit default values for every non-nullable column during $db->insert_query() calls.

5. Amateur Copy-Paste Plugin vs. Production MyBB Plugin Engineering

Comparing fragile community snippets against disciplined plugin engineering clarifies why code architecture determines stability and security:
  • Input Retrieval & Database Queries:
    Amateur plugins concatenate raw $_GET['uid'] into $db->query() strings, whereas production plugins enforce $mybb->get_input(..., MyBB::INPUT_INT), $db->escape_string(), and structured insert_query() helpers.

  • Template & Postbit Query Efficiency:
    Unoptimized plugins execute 20 separate SQL queries across a 20-post thread page inside postbit, while engineered plugins batch-fetch relational records once per page via indexed IN() queries or Datacache keys.

  • State Mutation & CSRF Protection:
    Insecure AJAX/GET endpoints execute moderator actions without token checks, whereas hardened plugins validate verify_post_check($mybb->get_input('my_post_key')) before mutating any record.

  • Lifecycle & Uninstall Cleanliness:
    Sloppy scripts leave orphaned tables, broken template edits, and leftover settings behind after removal, while clean plugins separate _install(), _activate(), _deactivate(), and _uninstall() deterministically.

6. Outlook: Building Sustainable Extensions for the MyBB Ecosystem

MyBB’s plugin architecture rewards engineering restraint and clarity. By scoping hook registrations strictly to active controllers, enforcing $mybb->get_input() and htmlspecialchars_uni() boundaries, validating my_post_key CSRF tokens on every state change, eliminating N+1 postbit query loops, and respecting clean install/uninstall lifecycles, developers can build rock-solid extensions that scale effortlessly across large communities and future MyBB versions.
İşin Doğrusu Youtube Kanalı