Zum Inhalt springen

MediaWiki - Automatischer Alt-Text für Bilder

Aus LHlab Wiki
MediaWiki 2020 logo

Um die Barrierefreiheit im MediaWiki zu verbessern, kann Bildern mit fehlendem alt-Attribut dieses automatisch hinzugefügt werden. Dazu wird ein kleiner PHP-Hook in der LocalSettings.php definiert, der direkt vor der HTML-Ausgabe des <img>-Tags ausgeführt wird.

Beschreibung

Der Hook prüft:

  • ob bereits ein alt-Attribut gesetzt ist – dann wird nichts verändert.
  • ob eine Bildunterschrift (Caption) vorhanden ist – dann wird diese als Alt-Text genutzt.
  • wenn keine Caption vorhanden ist – wird der Dateiname (ohne Namespace) als Alt-Text verwendet.
  • als letzte Absicherung wird ein generischer Fallback gesetzt, damit niemals ein komplett leeres alt entsteht.

PHP-Code für die LocalSettings.php

Der folgende Code kann ans Ende der LocalSettings.php eingefügt werden. Die Kommentare im Code sind absichtlich auf Englisch gehalten.

/**
 * MediaWiki: Ensure images always have an alt attribute.
 *
 * This hook runs right before MediaWiki produces the final <img> HTML.
 * - If an explicit alt is already set, we keep it.
 * - Otherwise we try to use the caption as alt text.
 * - If there is no caption, we fall back to the file title (file name).
 */
$wgHooks['ImageBeforeProduceHTML'][] = function (
    $unused,
    &$title,
    &$file,
    array &$frameParams,
    array &$handlerParams,
    &$time,
    &$res,
    $parser,
    &$query,
    &$widthOption
) {
    // If alt already set and non-empty, do nothing.
    if (
        isset( $frameParams['alt'] ) &&
        trim( (string)$frameParams['alt'] ) !== ''
    ) {
        return true;
    }

    $alt = null;

    // 1) Try to derive alt text from caption, if present.
    if ( isset( $frameParams['caption'] ) ) {
        $caption = $frameParams['caption'];

        // Caption can be string or something more complex, we handle the simple case.
        if ( is_string( $caption ) ) {
            $captionText = trim( strip_tags( $caption ) );
            if ( $captionText !== '' ) {
                $alt = $captionText;
            }
        }
    }

    // 2) If no caption-based alt, use the file title (without namespace).
    if ( $alt === null && $title ) {
        // Get the plain title, e.g. "GitHub-Logo.png"
        $raw = $title->getText();

        // Remove file extension
        $base = preg_replace( '/\.[a-zA-Z0-9]+$/', '', $raw );

        // Replace hyphens and underscores with spaces
        $base = strtr( $base, [
            '-' => ' ',
            '_' => ' ',
        ] );

        // Capitalize first letter (optional)
        $alt = ucfirst( $base );
    }
    // 3) Final fallback to avoid an empty alt.
    if ( $alt === null || trim( $alt ) === '' ) {
        $alt = 'Image'; // generic fallback
    }

    // Store alt back into the frame/handler params so the HTML generator picks it up.
    $frameParams['alt'] = $alt;
    $handlerParams['alt'] = $alt;

    // Optional: Debug log to verify the hook runs (check PHP error log).
    // error_log( 'LHlabAlt: set alt="'. $alt .'" for ' . $title->getPrefixedText() );

    return true; // continue normal processing
};

Integration in die LocalSettings.php

  1. Die Datei LocalSettings.php im MediaWiki-Installationsverzeichnis öffnen.
  2. Den oben gezeigten Codeblock ans Ende der Datei einfügen (unterhalb der anderen $wgHooks-Definitionen).
  3. Die Datei speichern.
  4. Eine Seite mit eingebundenen Bildern aufrufen und mit ?action=purge neu rendern lassen, damit der Parser-Cache aktualisiert wird.
  5. Mit den Entwicklertools des Browsers (z. B. Safari Web Inspector) prüfen, ob die erzeugten <img>-Tags nun ein sinnvolles alt-Attribut besitzen.

Damit erhalten Bilder im LHlab wiki, die bisher kein explizites alt-Attribut hatten, automatisch einen Alternativtext auf Basis der Bildunterschrift oder des Dateinamens.