Manual:Developing extensions
- Manual:Developing extensions
This article provides a beginner-friendly guide to developing extensions for MediaWiki, the software powering Wikipedia and countless other wikis. Extensions allow you to customize and extend the functionality of your wiki beyond its core features. This guide will cover the fundamental concepts, setup, basic structure, and essential steps involved in creating a simple extension. It assumes limited prior PHP knowledge, but some familiarity with web development concepts will be helpful.
What are MediaWiki Extensions?
MediaWiki extensions are packages of PHP code, SQL schemas, and other resources (like JavaScript, CSS, and images) that modify or add to the core functionality of a MediaWiki installation. They can do almost anything, from adding new special pages and parser functions to integrating with external services and modifying the user interface. Think of them as plugins for your wiki.
Why develop extensions?
- **Customization:** Modify the wiki to fit specific needs.
- **New Features:** Introduce entirely new functionality.
- **Integration:** Connect your wiki to other systems.
- **Community Contribution:** Share your work with the broader MediaWiki community.
Prerequisites
Before you begin, ensure you have the following:
- **A MediaWiki Installation:** You'll need a working MediaWiki installation to test your extension. A local development environment is *highly* recommended. See Manual:How to install MediaWiki for installation instructions.
- **PHP Knowledge:** Basic understanding of PHP syntax is crucial. Familiarity with object-oriented programming (OOP) will be beneficial. Resources like [1](https://www.php.net/docs.php) are invaluable.
- **SQL Knowledge:** Understanding of SQL for database schema modifications is needed for more complex extensions.
- **Text Editor/IDE:** A good text editor or Integrated Development Environment (IDE) such as VS Code, PHPStorm, or Sublime Text will greatly improve your development experience.
- **Git (Optional but Recommended):** For version control and collaboration. [2](https://git-scm.com/)
Setting up a Development Environment
It is strongly advised to develop extensions on a *local* MediaWiki installation. This prevents accidental disruption of a live wiki and allows for rapid testing.
1. **Install MediaWiki Locally:** Follow the instructions at Manual:How to install MediaWiki to set up a local instance. 2. **Configure Local Settings:** Edit `LocalSettings.php` in your MediaWiki installation directory. 3. **Enable Developer Mode:** Add the following line to `LocalSettings.php`:
```php $wgDeveloperMode = true; ```
This enables more detailed error reporting and debugging information.
4. **Set up a dedicated extension directory:** While you *can* put extension code directly into the `extensions/` directory, it is better practice to create a separate directory for development. For example, `extensions/MyExtension`. This simplifies cleanup and version control.
Basic Extension Structure
A typical MediaWiki extension consists of the following files:
- **Extension.json:** A JSON file containing metadata about the extension, such as its name, description, version, and dependencies. This is *required* in MediaWiki 1.32 and later.
- **extension.php:** The main PHP file that registers the extension with MediaWiki.
- **SpecialPage/ (optional):** A directory containing PHP files for custom special pages.
- **includes/ (optional):** A directory for custom PHP classes and functions.
- **languages/ (optional):** A directory for translation files.
- **skins/ (optional):** A directory for custom skins.
- **resources/ (optional):** A directory for CSS, JavaScript, and images.
Creating a Simple "Hello World" Extension
Let's create a very basic extension that displays "Hello, World!" on a special page.
1. **Create the Extension Directory:** Create a directory named `MyHelloWorld` within the `extensions/` directory of your MediaWiki installation.
2. **Create `Extension.json`:** Inside `MyHelloWorld`, create a file named `Extension.json` with the following content:
```json { "name": "MyHelloWorld", "version": "1.0", "description": "A simple extension that displays 'Hello, World!'", "author": "Your Name", "license": "GPL-2.0-or-later", "type": "extension" } ```
3. **Create `extension.php`:** Inside `MyHelloWorld`, create a file named `extension.php` with the following content:
```php <?php
if ( !defined( 'MEDIAWIKI' ) ) { die( 'Not a valid entry point' ); }
class MyHelloWorld {
public static function onSetup( &$updater ) { $updater->addExtension( __DIR__ ); }
public static function onSpecialPages( &$specialPages ) { $specialPages['HelloWorld'] = 'MyHelloWorldSpecialPage'; } }
$wgHooks['Setup'][] = 'MyHelloWorld::onSetup'; $wgHooks['SpecialPages'][] = 'MyHelloWorld::onSpecialPages';
class MyHelloWorldSpecialPage extends SpecialPage {
public function __construct() { parent::__construct( 'HelloWorld', 'helloworld' ); //name, subpage name }
public function execute( $par ) {
$this->output()->addHTML( '
Hello, World!
' );
} }
```
4. **Register the Extension:** Log in to your MediaWiki installation as an administrator. Go to Special:Extensions and click "Install" next to "MyHelloWorld".
5. **Access the Special Page:** Navigate to `https://yourwiki/wiki/Special:HelloWorld` (replace `yourwiki` with your wiki's domain). You should see "Hello, World!" displayed on the page.
Explanation of the Code
- `if ( !defined( 'MEDIAWIKI' ) ) { die( 'Not a valid entry point' ); }`: This line ensures that the file is only executed within the MediaWiki environment.
- `class MyHelloWorld { ... }`: This defines the main class for the extension.
- `public static function onSetup( &$updater ) { $updater->addExtension( __DIR__ ); }`: The `onSetup` hook is called during the extension installation process. `$updater->addExtension( __DIR__ )` tells MediaWiki to load the extension's resources.
- `public static function onSpecialPages( &$specialPages ) { $specialPages['HelloWorld'] = 'MyHelloWorldSpecialPage'; }`: The `onSpecialPages` hook registers a new special page named "HelloWorld" and associates it with the `MyHelloWorldSpecialPage` class.
- `$wgHooks['Setup'][] = 'MyHelloWorld::onSetup';`: This registers the `onSetup` hook.
- `$wgHooks['SpecialPages'][] = 'MyHelloWorld::onSpecialPages';`: This registers the `onSpecialPages` hook.
- `class MyHelloWorldSpecialPage extends SpecialPage { ... }`: This defines the class for the special page.
- `public function __construct() { parent::__construct( 'HelloWorld', 'helloworld' ); }`: The constructor initializes the special page. The first argument is the name displayed in the Special Pages list, and the second is the URL path used to access the page.
- `public function execute( $par ) { $this->output()->addHTML( '
Hello, World!
' ); }`: The `execute` method is called when the special page is accessed. It adds an HTML heading to the output.
Important Hooks and Variables
MediaWiki provides a powerful hook system that allows extensions to interact with the core functionality. Some commonly used hooks include:
- **`Setup`:** Called during extension installation.
- **`PersonalUrls`:** Allows adding custom links to the personal tools menu.
- **`ArticleViewBeforeEdit`:** Called before an article is displayed in edit mode.
- **`ParserGetCategories`:** Used to modify the categories assigned to a page.
- **`BeforeDisplayNoarticle`:** Called when a page does not exist.
- **`LoadExtensionSchema`:** Used to load database schemas.
Useful global variables:
- **`$wgUser`:** The current user object.
- **`$wgTitle`:** The current page's title object.
- **`$wgOut`:** The output object, used for adding HTML, CSS, and JavaScript to the page.
- **`$wgRequest`:** The request object, providing access to GET and POST parameters.
- **`$wgServices`:** Provides access to various MediaWiki services.
Advanced Concepts
- **Database Integration:** Extensions often need to store data in the database. Use the `LoadExtensionSchema` hook to define your database tables. See Manual:Database access for details.
- **Parser Functions:** Create custom parser functions that can be used within wiki pages. See Manual:Parser functions for more information.
- **Special Pages:** Develop custom special pages for administrative tasks or unique functionality.
- **API Integration:** Interact with external APIs to fetch data or perform actions. Utilize PHP's `curl` library or similar.
- **JavaScript and CSS:** Enhance the user interface with custom JavaScript and CSS. Use the `ResourceLoader` to manage these resources.
- **Internationalization (i18n):** Make your extension translatable into multiple languages. Use the `getMessage()` function and create language files in the `languages/` directory.
Debugging and Error Handling
- **Enable Developer Mode:** As mentioned earlier, `$wgDeveloperMode = true;` is crucial for detailed error reporting.
- **Error Logging:** Use PHP's error logging functions (`error_log()`) to record errors and warnings.
- **Debugging Tools:** Use a debugger (like Xdebug) to step through your code and inspect variables.
- **Check MediaWiki Logs:** The MediaWiki logs (accessible through the administrative interface) often contain valuable information about errors and warnings.
Best Practices
- **Follow Coding Standards:** Adhere to the PHP coding standards and MediaWiki's coding conventions.
- **Use Namespaces:** Use namespaces to avoid naming conflicts with other extensions.
- **Security:** Be mindful of security vulnerabilities, especially when handling user input or interacting with external systems. Sanitize all user input and use secure coding practices. [3](https://owasp.org/) is a valuable resource.
- **Documentation:** Document your code thoroughly.
- **Version Control:** Use Git or another version control system.
- **Testing:** Test your extension thoroughly before deploying it to a live wiki.
- **Community Engagement:** Share your extension with the MediaWiki community and solicit feedback. [4](https://www.mediawiki.org/wiki/Extension_directory) is where you can submit your extension.
Resources
- **MediaWiki Developer Documentation:** [5](https://www.mediawiki.org/wiki/Developer_documentation)
- **MediaWiki Extension Directory:** [6](https://www.mediawiki.org/wiki/Extension_directory)
- **PHP Documentation:** [7](https://www.php.net/docs.php)
- **OWASP (Open Web Application Security Project):** [8](https://owasp.org/)
Further Learning
Consider exploring these topics to deepen your understanding:
- **Technical Analysis:** [9](https://www.investopedia.com/terms/t/technicalanalysis.asp)
- **Moving Averages:** [10](https://www.investopedia.com/terms/m/movingaverage.asp)
- **Fibonacci Retracements:** [11](https://www.investopedia.com/terms/f/fibonacciretracement.asp)
- **Bollinger Bands:** [12](https://www.investopedia.com/terms/b/bollingerbands.asp)
- **Relative Strength Index (RSI):** [13](https://www.investopedia.com/terms/r/rsi.asp)
- **MACD (Moving Average Convergence Divergence):** [14](https://www.investopedia.com/terms/m/macd.asp)
- **Trend Lines:** [15](https://www.investopedia.com/terms/t/trendline.asp)
- **Support and Resistance Levels:** [16](https://www.investopedia.com/terms/s/supportandresistance.asp)
- **Chart Patterns:** [17](https://www.investopedia.com/terms/c/chartpattern.asp)
- **Candlestick Patterns:** [18](https://www.investopedia.com/terms/c/candlestick.asp)
- **Elliott Wave Theory:** [19](https://www.investopedia.com/terms/e/elliottwavetheory.asp)
- **Ichimoku Cloud:** [20](https://www.investopedia.com/terms/i/ichimokucloud.asp)
- **Parabolic SAR:** [21](https://www.investopedia.com/terms/p/parabolicsar.asp)
- **Stochastic Oscillator:** [22](https://www.investopedia.com/terms/s/stochasticoscillator.asp)
- **Volume Weighted Average Price (VWAP):** [23](https://www.investopedia.com/terms/v/vwap.asp)
- **Average True Range (ATR):** [24](https://www.investopedia.com/terms/a/atr.asp)
- **Donchian Channels:** [25](https://www.investopedia.com/terms/d/donchianchannel.asp)
- **Keltner Channels:** [26](https://www.investopedia.com/terms/k/keltnerchannels.asp)
- **Heikin Ashi:** [27](https://www.investopedia.com/terms/h/heikinashi.asp)
- **Pivot Points:** [28](https://www.investopedia.com/terms/p/pivotpoints.asp)
- **Market Sentiment Analysis:** [29](https://www.investopedia.com/terms/m/marketsentiment.asp)
- **Trend Following Strategies:** [30](https://www.investopedia.com/articles/trading/06/trendfollowing.asp)
- **Mean Reversion Strategies:** [31](https://www.investopedia.com/articles/trading/07/mean-reversion.asp)
- **Breakout Strategies:** [32](https://www.investopedia.com/articles/active-trading/030415/trading-breakouts-and-breakdowns.asp)
Manual:Configuration, Manual:Hooks, Manual:API, Manual:Skins, Manual:Parser functions, Manual:Database access, Manual:How to install MediaWiki, Manual:Administering MediaWiki, Manual:Extension directory, Special:Extensions
Start Trading Now
Sign up at IQ Option (Minimum deposit $10) Open an account at Pocket Option (Minimum deposit $5)
Join Our Community
Subscribe to our Telegram channel @strategybin to receive: ✓ Daily trading signals ✓ Exclusive strategy analysis ✓ Market trend alerts ✓ Educational materials for beginners