Extension:BetaFeatures

From mediawiki.org
This page is a translated version of the page Extension:BetaFeatures and the translation is 75% complete.
Outdated translations are marked like this.
Manual de extensiones de MediaWiki
BetaFeatures
Estado de lanzamiento: estable
Implementación Multimedia, Gancho , Base de datos
Descripción Permite a otras extensiones registrar sus funcionalidades beta en las preferencias del usuario
Autor(es) Mark Holmquist (MarkTraceurdiscusión)
Última versión 0.1 (Continous updates)
Política de compatibilidad Lanzamientos de screenshots junto con MediaWiki. Master no es compatible con versiones anteriores.
MediaWiki 1.25+
PHP 5.4+
Cambios de la base de datos
Tablas betafeatures_user_counts
Licencia GNU Licencia Pública general 2.0 o posterior
Descarga Template:WikimediaDownload/gerritonly
Ejemplo Special:Preferences#mw-prefsection-betafeatures
Special
  • $wgBetaFeatures
  • $wgBetaFeaturesAllowList
Descargas trimestrales 82 (Ranked 67th)
Wikis públicos que lo utilizan 1,031 (Ranked 249th)
Traduce la extensión BetaFeatures si está disponible en translatewiki.net
Asuntos Tareas abiertas · Reportar un bug

La extensión BetaFeatures permite a otras extensiones de MediaWiki registrar funciones beta con la lista de preferencias de usuario en la wiki. Utiliza la arquitectura de preferencias del usuario existente y algunas páginas especiales para realizar su función.

Instalación

  • Descarga y extrae los archivos en un directorio denominado «BetaFeatures» dentro de la carpeta extensions/.
    Developers and code contributors should install the extension from Git instead, using:cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/BetaFeatures
  • Añade el siguiente código en la parte final de tu archivo LocalSettings.php :
    wfLoadExtension( 'BetaFeatures' );
    
  • Ejecuta la secuencia de actualización, que creará automáticamente las tablas de la base de datos que necesita esta extensión.
  • Configurar como sea necesario.
  • Yes Hecho – Navega a Special:Version en el wiki para verificar que la extensión se haya instalado correctamente.

Usando los nuevos ganchos en tu extensión

Usar esta extensión para respaldar tu función beta es fácil. Registre un gancho de tipo "GetBetaFeaturePreferences " en su archivo de extension.json ; la sintaxis es casi idéntica a la del gancho de GetPreferences , con pequeños cambios para admitir el tipo de preferencia que necesitamos en este caso.

En extension.json:

    "Hooks": {
        "GetBetaFeaturePreferences": "MediaWiki\\Extension\\MyExtension\\Hooks::onGetBetaFeaturePreferences"
    },

En MyExtension/includes/Hooks.php:

namespace MediaWiki\Extension\MyExtension;
class Hooks {
    public static function onGetBetaFeaturePreferences( User $user, array &$betaPrefs ) {
        $extensionAssetsPath = MediaWikiServices::getInstance()
			->getMainConfig()
			->get( 'ExtensionAssetsPath' );
        $betaPrefs['myextension-awesome-feature'] = [
            // The first two are message keys
            'label-message' => 'myextension-awesome-feature-message',
            'desc-message' => 'myextension-awesome-feature-description',
            // Paths to images that represents the feature.
            // The image is usually different for ltr and rtl languages.
            // Images for specific languages can also specified using the language code.
            'screenshot' => array(
                'ru' => "$extensionAssetsPath/MyExtension/images/screenshot-ru.png",
                'ltr' => "$extensionAssetsPath/MyExtension/images/screenshot-ltr.png",
                'rtl' => "$extensionAssetsPath/MyExtension/images/screenshot-rtl.png",
            ),
            // Link to information on the feature - use subpages on mw.org, maybe?
            'info-link' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:MyExtension/MyFeature',
            // Link to discussion about the feature - talk pages might work
            'discussion-link' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/Help_talk:Extension:MyExtension/MyFeature',
        ];
    }
}
Por ahora, 'etiqueta-mensaje', 'desc-mensaje', 'info-enlaza', y 'discusión-enlaza' son necesarios. Asegúrese de utilizarlos todos.

Luego, puedes utilizar la función de conveniencia proporcionada por FuncionesBeta para verificar si la función está habilitada.

// SpecialMyExtension.php
class SpecialMyExtension extends SpecialPage {

    public function execute() {
        if ( BetaFeatures::isFeatureEnabled( $this->getUser(), 'my-awesome-feature' ) ) {
            // Implement the feature!
        }
    }
}

También puede usar una verificación de preferencia normal, pero no verifique con valores verdaderos o falsos; use los valores de la clase de CampodeCaracterísticasHTML.

// SpecialMyExtension.php
class SpecialMyExtension extends SpecialPage {

    public function execute() {
        if ( $this->getUser()->getOption( 'my-awesome-feature' ) === HTMLFeatureField::OPTION_ENABLED ) {
            // Implement the feature!
        }
    }
}

Dado que la BetaFeatures debería estar presente en todas partes, podrías utilizar la función conveniente en cualquier hook, página especial o cualquier otra cosa que quisieras. Sólo ten en cuenta los posibles problemas de rendimiento o de caché que puedas introducir con esos cambios.

Si quiere utilizar también su extensión sin BetaFeatures, deberá comprobar también su existencia, por ejemplo:

if (
    !ExtensionRegistry::getInstance()->isLoaded( 'BetaFeatures' )
    || \BetaFeatures::isFeatureEnabled( $user, 'my-awesome-feature' )
) {
    // Implement the feature!
}

Configuración

La variable de configuración $wgBetaFeaturesWhitelist puede utilizarse para limitar las características beta que se muestran en las preferencias. Por defecto está vacío, y se muestran todas las características beta.

Si se utiliza, para que una función beta aparezca en las preferencias debe figurar en la lista blanca. Este config la variable acepta una variedad de cuerdas. Cada cadena debe ser el nombre de una característica beta tal y como se especifica en la definición de preferencias pasada a onGetBetaFeaturePreferences(). For example, in the code given above, the name of the beta feature is myextension-awesome-feature, so you would need to add that string to the $wgBetaFeaturesWhitelist array in your wiki's configuration:

$wgBetaFeaturesWhitelist = [
        'myextension-awesome-feature' 
];

Uso avanzado

¿Quieres ver algo realmente genial?

Auto-enroll groups

With this example, we register a preference that's an "auto-enroll" one - if a user checks this, and new features come out that are in a particular group, the user will be automatically enrolled in those features.

// MyExtensionHooks.php
class MyExtensionHooks {

    static function getPreferences( $user, &$prefs ) {
        global $wgExtensionAssetsPath;

        $prefs['my-awesome-feature-auto-enroll'] = array(
            // The first two are message keys
            'label-message' => 'beta-feature-autoenroll-message',
            'desc-message' => 'beta-feature-autoenroll-description',
            // Link to information on the feature - use subpages on mw.org, maybe?
            'info-link' => 'https://wwww.mediawiki.org/wiki/Special:MyLanguage/MyFeature',
            // Link to discussion about the feature - talk pages might work
            'discussion-link' => 'https://www.mediawiki.org/wiki/Talk:MyFeature',
            // Enable auto-enroll for this group
            'auto-enrollment' => 'my-awesome-feature-group',
        );

        $prefs['my-awesome-feature'] = array(
            // The first two are message keys
            'label-message' => 'beta-feature-message',
            'desc-message' => 'beta-feature-description',
            // Paths to images that represents the feature.
            // The image is usually different for ltr and rtl languages.
            // Images for specific languages can also specified using the language code.
            'screenshot' => array(
                'ru' => "$wgExtensionAssetsPath/MyExtension/images/screenshot-ru.png",
                'ltr' => "$wgExtensionAssetsPath/MyExtension/images/screenshot-ltr.png",
                'rtl' => "$wgExtensionAssetsPath/MyExtension/images/screenshot-rtl.png",
            ),
            // Link to information on the feature - use subpages on mw.org, maybe?
            'info-link' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:MyExtension/SomeFeature',
            // Link to discussion about the feature - talk pages might work
            'discussion-link' => 'https://www.mediawiki.org/wiki/Extension_talk:MyExtension/SomeFeature',
            // Add feature to this group
            'group' => 'my-awesome-feature-group',
        );
    }
}

Administración de dependencias

Next up, we can actually define dependency management per-feature. To do this we first register the name of a hook that we want to use for this with the hook "GetBetaFeatureDependencyHooks ", then we register a hook of that type that checks some dependency, and returns true if it's met or false if not.

// MyExtension.php
$wgAutoloadClasses['MyExtensionHooks'] = __DIR__ . '/MyExtensionHooks.php';
Hooks::register( 'GetBetaFeaturePreferences', 'MyExtensionHooks::getPreferences' );
Hooks::register( 'GetBetaFeatureDependencyHooks', 'MyExtensionHooks::getDependencyCallbacks' );
Hooks::register( 'CheckDependenciesForMyExtensionFeature', 'MyExtensionHooks::checkDependencies' );
// MyExtensionHooks.php
class MyExtensionHooks {

    static function getPreferences( $user, &$prefs ) {
        global $wgExtensionAssetsPath;

        $prefs['my-awesome-feature'] = array(
            // The first two are message keys
            'label-message' => 'beta-feature-message',
            'desc-message' => 'beta-feature-description',
            // Paths to images that represents the feature.
            // The image is usually different for ltr and rtl languages.
            // Images for specific languages can also specified using the language code.
            'screenshot' => array(
                'ru' => "$wgExtensionAssetsPath/MyExtension/images/screenshot-ru.png",
                'ltr' => "$wgExtensionAssetsPath/MyExtension/images/screenshot-ltr.png",
                'rtl' => "$wgExtensionAssetsPath/MyExtension/images/screenshot-rtl.png",
            ),
            // Link to information on the feature - use subpages on mw.org, maybe?
            'info-link' => 'https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:MyExtension/SomeFeature',
            // Link to discussion about the feature - talk pages might work
            'discussion-link' => 'https://www.mediawiki.org/wiki/Extension_talk:MyExtension/SomeFeature',
            // Mark as dependent on something
            'dependent' => true,
        );
    }

    static function getDependencyCallbacks( &$depHooks ) {
        $depHooks['my-awesome-feature'] = 'CheckDependenciesForMyExtensionFeature';
        return true;
    }

    static function checkDependencies() {
        $dependenciesMet = false;
        // Do some fancy checking and return the result
        return $dependenciesMet;
    }
}

You can abuse use this feature to do per-wiki disabling of features, if they're marked as dependent. But that sounds really hacky. You probably shouldn't. I can hear you thinking about it right now, just stop it.

Consideraciones sobre la base de datos

There's a database table (betafeatures_user_counts) defined, and used, by BetaFeatures. But you might get confused by it if you try to use it locally.

We use the job queue to run updates for this table, when the cache expires (30 minutes TTL). If your wiki is configured to run jobs on each request, this will make about one request every 30 minutes reeeeeeally slow, but the rest will be relatively fast. If you configure your wiki to run jobs via cron, things will work much better.

Véase también