Comment 1 for bug 1953086

Revision history for this message
Scott Verbeek (scottverbeek) wrote :

I've come up with a bug fix for this. I still need to test and make it use Mahara functions create tests and document but I've got this atm.
```
<?php
function log_debug($message) {
    print("DBG: {$message}\n");
}

function append_image_src_with_text_bi_id($content, $biid) {
    $dom = new DOMDocument();
    $dom->loadHTML(htmlspecialchars_decode($content));
    foreach ($dom->getElementsByTagName('img') as $tag) {
        // Get the src attribute, if no attribute with the given qualifiedName is found an empty string is returned.
        $imagesource = $tag->getAttribute('src');

        // If it's empty then continue.
        if(empty($imagesource)) {
            continue;
        }

        // Make sure we only touch our links.
        if (!strpos($imagesource, '/artefact/file/download.php?')) {
            continue;
        }

        // If the source already contains a text parameter then skip.
        parse_str(parse_url($imagesource, PHP_URL_QUERY), $result);
        if(isset($result['text']) && !empty($result['text'])) {
            continue;
        }

        // Now that we've got an image from our site append with &text=XYZ
        log_debug("Found {$imagesource}");
        $tag->setAttribute('src', "{$imagesource}&text={$biid}");
        $dom->saveHTML();
    }
    // The DOMDocument adds some HTML tags which we don't want so get everything in the body.
    $bodynode = $dom->getElementsByTagName('body')->item(0);
    return implode(array_map([$bodynode->ownerDocument,"saveHTML"],iterator_to_array($bodynode->childNodes)));
}

$content = '<p><img width="1442" height="" style="" alt="2021-12-03_11-12-44-screenshot.png" src="http://mahara.localhost/artefact/file/download.php?text=7&amp;embedded=1&amp;description=7"></p>';
$biid = 12346;

if ($content !== $newcontent = append_image_src_with_text_bi_id($content, $biid)) {
    log_debug("Changed to {$newcontent}");
} else {
    log_debug("Nothing changed");
}
```