Manuale:Sviluppo estensioni

This page is a translated version of the page Manual:Developing extensions and the translation is 48% complete.
Outdated translations are marked like this.
Estensioni di MediaWiki

This page is a guide to developing extensions for MediaWiki. Before you start, browse the list of extensions to see if an extension already exists for your use case.

Extension development consists of these parts:

  1. Configurazione
  2. Implementation
  3. Localizzazione
  4. Publication

Installazione

To set up a new extension, start by setting up a local development environment for MediaWiki , and follow the instructions to install and copy the BoilerPlate extension.

Durante lo sviluppo, potresti disabilitare la cache impostando $wgMainCacheType = CACHE_NONE e $wgCacheDirectory = false, altrimenti i messaggi di sistema ed altre variazioni potrebbero non essere mostrate.

Structure

Un'estensione minimale consisterà nella seguente struttura:

MyExtension/extension.json
Salva le istruzioni d'installazione. Il nome del file deve essere extension.json. (In versioni anteriori a MediaWiki 1.25, le istruzioni di installazione stavano in file MyExtension/MyExtension.php con il nome dell'estensione. Molte estensioni hanno ancora retro-compatibilità con questo file PHP.)
MyExtension/includes/ (or MyExtension/src/)
Salva il codice PHP di esecuzione dell'estensione.
MyExtension/resources/ (or MyExtension/modules/)
Salva le risorse del lato client come JavaScript, CSS e LESS per l'estensione.
MyExtension/i18n/*.json
Salva le informazioni di localizzazione dell'estensione.
MyExtension/README.md
Good practice is to add a README file with basic info about how to install and configure the extension. Use either plain text or Markdown. For a plain text example, see the Phabricator Diffusion page for the Extension:Page Forms . If markdown is used, add the file extension .md. For example, see the README.md file for Parsoid on Phabricator Diffusion.

Quando sviluppi un'estensione, sostituisci la scritta MyExtension con il nome della tua estensione. Usa nomi nella convenzione UpperCamelCase per la cartella esterna per i tuoi file PHP. Questa è la convenzione generale per i nomi dei file.[1]

Registration

Versione MediaWiki:
1.25

The extension.json file contains the configuration data for the extension. Here is an example of a minimal extension.json:

{
	"name": "MyExtension",
	"author": "John Doe",
	"url": "https://www.mediawiki.org/wiki/Extension:MyExtension",
	"description": "This extension is an example.",
	"version": "1.5",
	"license-name": "GPL-2.0-or-later",
	"type": "validextensiontype",
	"manifest_version": 2
}

Molti campi sono facoltativi, ma è comunque una buona norma compilarli. For a more complete example of extension.json, see the BoilerPlate extension.

Il manifest_version si riferisce alla versione dello schema su cui è scritto il file extension.json . Le versioni disponibili sono 1 e 2. Vedere qui per la documentazione su questa funzionalità. A meno che non sia necessario supportare una versione precedente di MediaWiki, scegliere la versione più recente.

Once you have an extension.json file set up for your extension, the extension will appear on your local Special:Version page.

Licenza


MediaWiki is an open-source project and users are encouraged to make any MediaWiki extensions under an Open Source Initiative (OSI) approved license compatible with GPL-2.0-or-later (Wikimedia's standard software license).

We recommend adopting one of the following compatible licenses for your projects in Gerrit:

For extensions that have a compatible license, you can request developer access to the MediaWiki source repositories for extensions. To specify the licence in code and with "license-name" a key should be used to provide its short name, e.g. "GPL-2.0-or-later" or "MIT" adhering to the list of identifiers at spdx.org.

Rendere l'estensione configurabile dall'utente

Ideally, users should be able to install your extension by adding only one line to LocalSettings.php:

wfLoadExtension( 'MyExtension' );

Se vuoi rendere l'estensione configurabile all'utente, devi definire e documentare alcuni parametri di configurazione e la configurazione dell'utente dovrebbe assomigliare a questa:

wfLoadExtension( 'MyExtension' );
$wgMyExtensionConfigThis = 1;
$wgMyExtensionConfigThat = false;

Se si desidera che l'utente sia in grado di configurare l'estensione, è necessario provvedere una o più variabili di configurazione. È buona norma dare un nome univoco a tali variabili. Queste dovrebbero anche seguire le convenzioni nomi di MediaWiki (e.g. le variabili globali devono iniziare con $wg).

Ad esempio, se l'estensione si chiama "MyExtension", si consiglia di dare a tutte le variabili di configurazione un nome che inizi con $wgMyExtension. È importante che nulla del nucleo di MediaWiki inizalizzi le sue variabili in questo modo e che si sia fatto un ragionevole lavoro di controllo per verificare che nessuna delle estensioni pubblicate inizalizzi le proprie variabili in questo modo. Gli utenti non accetteranno di dover scegliere tra la tua estensione e alcune altre estensioni perché i nomi di variabili scelte si sovrappongono ad altre esistenti.

È inoltre buona norma includere nelle note di installazione un'ampia documentazione delle variabili di configurazione.

Here is an example of how to set up a configuration variable in extension.json:

{
	"config": {
		"BoilerPlateEnableFoo": {
			"value": true,
			"description": "Enables the foo functionality"
		}
	}
}

Si noti che dopo aver chiamato wfLoadExtension( 'BoilerPlate' ); la variabile globale $wgBoilerPlateEnableFoo non esiste. Se si imposta la variabile, ad es. in LocalSettings.php allora il valore predefinito dato in extension.json non sarà usato.

Per ulteriori dettagli su come utilizzare una variabile globale all'interno di una estensione personalizzata, si prega di fare riferimento a Configuration for developers .

Preparare le classi per il caricamento automatico

Se si sceglie di utilizzare le classi per implementare la propria estensione, MediaWiki fornisce un meccanismo semplificato per aiutare PHP a trovare il file sorgente in cui si trova la classe. Nella maggior parte dei casi questo dovrebbe eliminare la necessità di scrivere il proprio metodo __autoload($classname).

Per utilizzare il meccanismo di autocaricamento di MediaWiki, si aggiungono voci al campo AutoloadClasses . La chiave di ogni elemento è il nome della classe; il valore è il file che contiene la definizione della classe. Per un'estensione semplice a una classe, di solito alla classe viene dato lo stesso nome dell'estensione, quindi la sezione di caricamento automatico potrebbe apparire come questa (l'estensione si chiama MyExtension):

{
	"AutoloadClasses": {
		"MyExtension": "includes/MyExtension.php"
	}
}

Il nome del file è relativo alla directory in cui si trova il file extension.json.

Per estensioni più complesse, si deve considerare namespaces. Vedere Manual:Extension.json/Schema#AutoloadNamespaces per dettagli.

Handling dependencies

Assume that an extension requires the presence of another extension, for example because functionalities or database tables are to be used and error messages are to be avoided in case of non-existence.

For example the extension CountingMarker requires the presence of the extension HitCounters for certain functions.

One way to specify this would be by using the requires key in extension.json .

Another option is using ExtensionRegistry (available since MW 1.25):

	if ( ExtensionRegistry::getInstance()->isLoaded( 'HitCounters', '>=1.1' ) {
		/* do some extra stuff, if extension HitCounters is present in version 1.1 and above */
	}

Currently (as of February 2024, MediaWiki 1.41.0) the name of the extension-to-be-checked needs to exactly match the name in their extension.json.[2][3]

Example: if you want to check the load status of extension OpenIDConnect, you have to use it with a space

	if ( ExtensionRegistry::getInstance()->isLoaded( 'OpenID Connect' ) {
    ...
	}

Implementation

For an overview of code architecture, structure, and conventions for extensions, see Le migliori pratiche per le estensioni .

Extension points

MediaWiki core provides several ways for extensions to change the behavior, functionality, and appearance of a wiki. Most extensions use more than one of these extension points. For a complete list of extension points supported in extension.json, see the schema reference .

General

  • Hooks : Inject custom code at key points in MediaWiki core code, such as when a user logs in or saves a page. Extensions can also define new hooks.
  • API modules : Define API modules based on the Action API or REST API . These modules can be called by bots or clients.
  • Jobs : Add jobs to MediaWiki's JobQueue to perform process-intensive tasks asynchronously, such as sending notification emails.

Pages

  • Display a special page : Special pages provide dynamically generated content, often based on system state, database queries, and user inputs.
  • Perform a page action : The action URL parameter generates a custom page based on the current page, usually to provide information (such as page history) or to perform an action (such as edit the page). In addition to the default actions provided by MediaWiki core, extensions can define a new page action.
  • Add a tracking category : Help users find pages with similar characteristics by automatically adding pages to custom categories.

Content

  • Extend wiki markup : Extensions can add custom functionality to MediaWiki's wikitext markup using template syntax ({{...}}) or tags (‎<example />). These customizations are used to generate content and to interact with MediaWiki during page rendering.
  • Support a content model : By default, wiki pages can be stored using a few standard content models, such as wikitext and JSON. Extensions can provide support for new content models by adding a content handler.
  • Support a media type : Extensions can add to the default set of supported media file types by adding a media handler.

Moderation tools

  • Log a user or system action : On wiki, actions are tracked for transparency and collaboration. To support this feature, extensions can add custom entries and functionality to Special:Log.
  • Add a recent-changes flag : Extensions can add custom flags to the following special pages to help moderators track page changes: Special:RecentChanges, Special:Watchlist, Special:RecentChangesLinked
  • Add a revision tag : Extensions can add annotations associated with a revision or log entry, such as for edits made using the VisualEditor extension.

Authentication

  • Add a provider : Extensions can add support for new login mechanisms and session management methods.

Aggiungere tabelle del database

Make sure the extension doesn't modify the core database tables. Instead, extension should create new tables with foreign keys to the relevant MW tables.

  Attenzione: Se l'estensione viene utilizzata su un wiki WMF di produzione, seguire la guida alla modifica dello Schema.

Se l'estensione ha bisogno di aggiungere le proprie tabelle del database, usare l'hook LoadExtensionSchemaUpdates . Vedere la pagina del manuale per più informazioni sull'utilizzo.

Registering attributes for other extensions

Attributes allow extensions to register something, such as a module, with another extension. For example, extensions can use attributes to register a plugin module with the VisualEditor extension. For more information, see Extension registration .

Localizzazione

Durante lo sviluppo, si consiglia di disabilitare entrambe le cache impostando $wgMainCacheType = CACHE_NONE e $wgCacheDirectory = false, altrimenti le modifiche ai messaggi di sistema potrebbero non essere visualizzate.

Se si vuole che l'estensione venga utilizzata su wiki che hanno un pubblico multilingue, è necessario aggiungere il supporto per la localizzazione alla propria estensione.

Archiviare messaggi in <language-key>.json

Archivia le definizioni dei messaggi in un file JSON di localizzazione, uno per ogni chiave linguistica in cui l'estensione è tradotta. I messaggi vengono salvati con una chiave messaggio e il messaggio stesso utilizzando il formato standard JSON. Ogni id del messaggio deve essere minuscolo e non può contenere spazi. Ogni chiave deve iniziare con l'estensione del nome in minuscolo. Un esempio si può trovare nell'[$url estensione MobileFrontend]. Ecco un esempio di file JSON minimale (in questo caso en.json):

en.json

{
	"myextension-desc": "Adds the MyExtension great functionality.",
	"myextension-action-message": "This is a test message"
}

Archiviare la documentazione messaggi in qqq.json

La documentazione per le chiavi dei messaggi può essere memorizzata nel file JSON per lo pseudolinguaggio con il codice qqq. Una documentazione dell'esempio sopra può essere:

qqq.json:

{
	"myextension-desc": "The description of MyExtension used in Extension credits.",
	"myextension-action-message": "Adds 'message' after 'action' triggered by user."
}

Caricare il file di localizzazione

Nel file extension.json, definire la posizione dei file dei messaggi (ad esempio, nella cartella i18n/):

{
	"MessagesDirs": {
		"MyExtension": [
			"i18n"
		]
	}
}

Uso di wfMessage in PHP

Nel codice di configurazione e implementazione, sostituire ogni uso letterale del messaggio con una chiamata a wfMessage( $msgID, $param1, $param2, ... ). Nelle classi che implementa IContextSource (come pure in certe altre sottoclassi di SpecialPage), si può invece utilizzare $this->msg( $msgID, $param1, $param2, ... ). Esempio:

wfMessage( 'myextension-addition', '1', '2', '3' )->parse()

Uso di mw.message in JavaScript

È possibile utilizzare le funzioni di internazionalizzazione anche in JavaScript. Vedi Manual:Messages API per i dettagli.

Pubblicazione

Per autocategorizzare e standardizzare la documentazione dell'estensione esistente, vedere Template:Estensione . Per aggiungere la tua nuova estensione a questa Wiki:


A developer sharing their code in the MediaWiki code repository should expect:

Feedback / Criticism / Code reviews
Review and comments by other developers on things like framework use, security, efficiency and usability.
Developer tweaking
Other developers modifying your submission to improve or clean-up your code to meet new framework classes and methods, coding conventions and translations.
Improved access for wiki sysadmins
If you do decide to put your code on the wiki, another developer may decide to move it to the MediaWiki code repository for easier maintenance. You may then create a developer account to continue maintaining it.
Future versions by other developers
New branches of your code being created automatically as new versions of MediaWiki are released. You should backport to these branches if you want to support older versions.
Incorporation of your code into other extensions with duplicate or similar purposes — incorporating the best features from each extension.
Credit
Credit for your work being preserved in future versions — including any merged extensions.
Similarly, you should credit the developers of any extensions whose code you borrow from — especially when performing a merger.

Any developer who is uncomfortable with any of these actions occurring should not host in the code repository. You are still encouraged to create a summary page for your extension on the wiki to let people know about the extension, and where to download it.

Distribuzione e registrazione

Se si intende distribuire la propria estensione sui siti Wikimedia (compresa eventualmente Wikipedia), è necessario un ulteriore controllo in termini di prestazioni e sicurezza. Consultare Writing an extension for deployment .

Se l'estensione aggiunge dei namespace, si potrebbe voler registrare i suoi namespace predefiniti; allo stesso modo, se aggiungono tabelle o campi del database, si potrebbe volerli registrare a database field prefixes .

Si tenga presente che la revisione e la distribuzione di nuove estensioni sui siti Wikimedia può essere estremamente lenta e in alcuni casi ha richiesto più di due anni.[4]

Documentazione di aiuto

Dovreste fornire documentazione di aiuto di dominio pubblico per le funzioni fornite dalla vostra estensione. The convention is for extensions to have their user-focused help pages under a pseudo-namespace of Help:Extension:<ExtensionName>, with whatever subpages are required (the top level page will be automatically linked from the extension infobox if it exists). Help:CirrusSearch è un buono esempio. Si dovrebbe fornire agli utenti un link alla documentazione tramite la funzione addHelpLink() .

Releasing updates

There are a number of common approaches to releasing updates to extensions. These are generally defined according to the compatibility policy of the extension (master, rel, or ltsrel):

  • masterReleases may be tagged with version numbers on the master branch, and documentation provided on the extension's homepage describing which extension versions are compatible with which core versions. Release branches will still be created automatically, and you may wish to delete these if they are not intended to be used.
  • rel e ltsrelRelease by backporting changes to the REL1_* branches (either all changes, or only critical ones). Version numbers are generally not needed unless the extension is a dependency of another (the version number can then be provided in the other extension's configuration to ensure that incompatible combinations aren't installed). Many extensions will stay at the same version number for years.

Supporto per altre versioni core

Esistono due convenzioni diffuse per il supporto delle vecchie versioni del nucleo di MediaWiki:

  • Master: il ramo master dell'estensione è compatibile con il maggior numero possibile di vecchie versioni di core. Questo comporta un onere di manutenzione (gli hack per la retrocompatibilità devono essere mantenuti a lungo e le modifiche all'estensione devono essere testate con diverse versioni di MediaWiki), ma i siti che utilizzano vecchie versioni di MediaWiki beneficiano delle funzionalità aggiunte di recente all'estensione.
  • Rami di rilascio: i rami di rilascio dell'estensione sono compatibili con i rami corrispondenti del nucleo, ad esempio i siti che usano MediaWiki 1.43 devono usare il ramo REL1_43 dell'estensione. (Per le estensioni ospitate su gerrit, questi rami vengono creati automaticamente quando vengono rilasciate nuove versioni di MediaWiki). Ciò si traduce in un codice più pulito e in uno sviluppo più rapido, ma gli utenti delle vecchie versioni del nucleo non beneficiano delle correzioni di bug e delle nuove funzionalità, a meno che non vengano ricompilati manualmente.

I manutentori delle estensioni dovrebbero dichiarare con il parametro compatibility policy del template {{Estensione }} quale convenzione seguono.

Fornire supporto / collaborazione

Gli sviluppatori di estensioni devono aprire un account su Wikimedia Phabricator , e richiedere un nuovo progetto per l'estensione. Questo fornisce un luogo pubblico in cui gli utenti possono inviare problemi e suggerimenti e voi potete collaborare con gli utenti e gli altri sviluppatori per risolvere i bug e pianificare le funzionalità della vostra estensione.

Vedi anche

Learn by example


Note