embeddedimage.php 12.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
<?php
/**
 *
 * @package    mahara
 * @subpackage core
 * @author     Mike Kelly UAL <m.f.kelly@arts.ac.uk>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 *
 */

defined('INTERNAL') || die();

class EmbeddedImage {

    function __construct() {
    }

    /**
     * Format HTML content in a WYSIWYG text box to correctly serve an embedded image
     * which was added via the TinyMCE imagebrowser plugin.
     * Add a database reference to the embedded image if required, to set viewing permissions for it
     *
     * @param string $fieldvalue The HTML source of the text body added to the TinyMCE text editor
     * @param string $resourcetype The type of resource which the TinyMCE editor is used in, e.g. 'forum', 'topic', 'post' for forum text boxes
     * @param int $resourceid The id of the resourcetype
     * @param int $groupid The id of the group the resource is in if applicable
     * @return string The updated $fieldvalue
     */
30
    public static function prepare_embedded_images($fieldvalue, $resourcetype, $resourceid, $groupid = NULL) {
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

        if (empty($fieldvalue) || empty($resourcetype) || empty($resourceid)) {
            return $fieldvalue;
        }

        global $USER;
        $dom = new DOMDocument();
        $dom->encoding = 'utf-8';
        $oldval = libxml_use_internal_errors(true);
        $success = $dom->loadHTML(utf8_decode($fieldvalue));
        libxml_use_internal_errors($oldval);
        if ($success) {
            $publicimages = array();
            $xpath = new DOMXPath($dom);
            $srcstart = get_config('wwwroot') . 'artefact/file/download.php?';
            $query = '//img[starts-with(@src,"' . $srcstart . '")]';
            $images = $xpath->query($query);
            if (!$images->length) {
                self::remove_embedded_images($resourcetype, $resourceid);
                return $fieldvalue;
            }
            foreach ($images as $image) {
                // is this user allowed to publish this image?
                $imgsrc = $image->getAttribute('src');
                $searchpattern = '`file=(\d+)`';
                $foundmatch = preg_match_all($searchpattern, $imgsrc, $matches);
                if ($foundmatch) {
                    foreach ($matches[1] as $imgid) {
                        $file = artefact_instance_from_id($imgid);
60 61 62 63
                        if (!($file instanceof ArtefactTypeImage)
                            || !$USER->can_publish_artefact($file)
                           ) {
                            return $fieldvalue;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
                        }
                        else {
                            $publicimages[] = $imgid;
                            $imgispublic = get_field('artefact_file_embedded', 'id', 'fileid', $imgid, 'resourcetype', $resourcetype, 'resourceid', $resourceid);
                            // add to embedded_images table for public access, specifiying context
                            if (!$imgispublic) {
                                insert_record('artefact_file_embedded', (object) array('fileid' => $imgid, 'resourcetype' => $resourcetype, 'resourceid' => $resourceid));
                            }
                        }
                    }
                }
                // rewrite to include group value and resource value
                // if user has group access, he or she will have access to view forum-based content
                $imgnode = $dom->createElement("img");
                $imgnode->setAttribute('width', $image->getAttribute('width'));
                $imgnode->setAttribute('height', $image->getAttribute('height'));
                $imgnode->setAttribute('style', $image->getAttribute('style'));
81
                $imgnode->setAttribute('alt', $image->getAttribute('alt'));
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

                if (!empty($groupid)) {
                    $searchpattern = '`group=(\d+)`';
                    $foundmatch = preg_match_all($searchpattern, $imgsrc, $matches);
                    if (!$foundmatch) {
                        $imgsrc = $imgsrc . '&group=' . $groupid;
                        $imgnode->setAttribute('src', $imgsrc);
                    }
                    else {
                        // check that the group value hasn't been spoofed
                        foreach ($matches[1] as $index => $grpid) {
                            if ($matches[1][$index] != $groupid) {
                                $imgsrc = str_replace('group=' . $matches[1][$index], 'group=' . $groupid, $imgsrc);
                            }
                        }
                        $imgnode->setAttribute('src', $imgsrc);
                    }
                }
                $searchpattern = '`' . $resourcetype . '=(\d+)`';
                $foundmatch = preg_match_all($searchpattern, $imgsrc, $matches);
                if (!$foundmatch) {
                    $imgnode->setAttribute('src', $imgsrc . '&' . $resourcetype . '=' . $resourceid);
                }
                else {
                    // check that the resourceid hasn't been spoofed
                    foreach ($matches[1] as $index => $rsrcid) {
                        if ($matches[1][$index] != $resourceid) {
                            $imgsrc = str_replace($resourcetype . '=' . $matches[1][$index], $resourcetype . '=' . $resourceid, $imgsrc);
                        }
                    }
                    $imgnode->setAttribute('src', $imgsrc);
                }
                $image->parentNode->replaceChild($imgnode, $image);
            }
            self::remove_embedded_images($resourcetype, $resourceid, $publicimages);

            // we only want the fragments inside the body tag created by new DOMDocument
            $childnodes = $dom->getElementsByTagName('body')->item(0)->childNodes;
120
            $dummydom = new DOMDocument();
121
            foreach ($childnodes as $child) {
122
                $dummydom->appendChild($dummydom->importNode($child, true));
123
            }
124
            $fieldvalue = html_entity_decode($dummydom->saveHTML(), ENT_QUOTES, 'UTF-8');
125 126 127 128 129 130 131 132 133 134 135 136 137
            return $fieldvalue;
        }
    }

    /**
     * Remove database references to an embedded image
     * which was removed from a TinyMCE WYSIWYG text editor.
     * If parent resource has children, e.g. a forum with topics, delete refs. to embedded images in child resources
     *
     * @param string $resourcetype The type of resource which the TinyMCE editor is used in, e.g. 'forum', 'topic', 'post' for forum text boxes
     * @param int $resourceid The id of the resourcetype
     * @return void
     */
138
    public static function delete_embedded_images($resourcetype, $resourceid) {
139 140 141 142 143

        self::remove_embedded_images($resourcetype, $resourceid);

        if ($resourcetype == 'forum') {
            // we deleted embedded forum image above, now delete any embedded child topic and post images for that forum
144 145 146 147 148
            if ($topicids = get_records_array('interaction_forum_topic', 'forum', $resourceid, 'id DESC', 'id')) {
                foreach ($topicids as $id) {
                    // note recursion to remove posts associated with topic
                    self::delete_embedded_images('topic', $id->id);
                }
149 150 151 152
            }
        }
        else if ($resourcetype == 'topic') {
            // we deleted embedded topic image above, now delete any embedded child post images for that topic
153 154 155
            if ($postids = get_records_array('interaction_forum_post', 'topic', $resourceid, 'id DESC', 'id')) {
                foreach ($postids as $id) {
                    self::remove_embedded_images('post', $id->id);
156
                }
157 158 159 160
            }
        }
    }

161
    public static function can_see_embedded_image($fileid, $resourcetype, $resourceid) {
162 163 164 165
        $imgispublic = get_field('artefact_file_embedded', 'id', 'fileid', $fileid, 'resourcetype', $resourcetype, 'resourceid', $resourceid);
        return $imgispublic !== false;
    }

166
    static function remove_embedded_images($resourcetype, $resourceid, $publicimages = NULL) {
167 168 169 170 171 172
        $existingpublicimages = get_records_select_array('artefact_file_embedded', "resourcetype = ? AND resourceid = ?", array($resourcetype, $resourceid));
        if (!$existingpublicimages) {
            return;
        }
        foreach ($existingpublicimages as $img) {
            if (empty($publicimages) || !in_array($img->fileid, $publicimages)) {
173
                delete_records('artefact_file_embedded', 'fileid', $img->fileid, 'resourceid', $img->resourceid);
174 175 176
            }
        }
    }
177 178 179 180 181 182 183 184 185
/**
 * Rewrites all possible embedded image urls when import a html string
 *
 * @param string $text the html string
 * @param array $artefactids artefact ID mapping, see more PluginImportLeap::$artefactids
 * @param string $resourcetype
 * @param string $resourceid
 * @return mixed
 */
186
    public static function rewrite_embedded_image_urls_from_import($text, array $artefactids, $resourcetype=null, $resourceid=null) {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
        $resourcestr = (!empty($resourcetype) && !empty($resourceid)) ?
                          "&$resourcetype=$resourceid"
                        : '';
        // Find all possible embedded image artefact ids
        // We support 2 formats of embedded image urls
        // 1. <img ... src=".../artefact/file/download.php?file=...">
        //      generated by TinyMCE embedded image plugin
        // 2. <img ... rel="leap2:has_part" href="(portfolio:artefact[\d]+)"...>
        //      generated by export_leap_rewrite_links()
        if (!empty($text) && strpos($text, '<img') !== false) {
            $ids = array();
            $regexp = array();
            $replacetext = array();
            $matches = array();
            if (preg_match_all(
                    '#<img([^>]+)src=("|\\")'
                    . preg_quote(
                        get_config('wwwroot')
                        . 'artefact/file/download.php?file='
                    )
                    . '([\d]+)'
                    . '(&|&amp;)embedded=1([^"]*)"#',
                    $text,
                    $matches)
                ) {
                foreach ($matches[3] as $id) {
                    if (!empty($artefactids["portfolio:artefact$id"])) {
                        // Replace the old image id by the new one
                        $regexp[] = '#<img([^>]+)src=("|\\")'
                            . preg_quote(
                                get_config('wwwroot')
                                . 'artefact/file/download.php?file=' . $id
                            )
                            . '(&|&amp;)embedded=1#';
                        $replacetext[] = '<img$1src="' . get_config('wwwroot')
                            . 'artefact/file/download.php?file='
                            . $artefactids["portfolio:artefact$id"][0] . '&embedded=1'
                            . $resourcestr;
                        $ids[] = $id;
                    }
                }
            }
            $matches = array();
            if (preg_match_all(
                    '#<(img[^>]+)rel="leap2:has_part"'
                    . ' href="portfolio:artefact([\d]+)"([^>]*)>#',
                    $text,
                    $matches)
                ) {
                foreach ($matches[2] as $id) {
                    if (!empty($artefactids["portfolio:artefact$id"])) {
                        // Replace the old entry id to the new one
                        $regexp[] = '#<img([^>]+)rel="leap2:has_part"'
                            . ' href="portfolio:artefact' . $id . '"#';
                        $replacetext[] = '<img$1src="' . get_config('wwwroot')
                            . 'artefact/file/download.php?file='
                            . $artefactids["portfolio:artefact$id"][0] . '&embedded=1'
                            . $resourcestr
                            . '"';
                        $ids[] = $id;
                    }
                }
            }
            if (!empty($ids)) {
                $text = preg_replace($regexp, $replacetext, $text);
                // Update the table 'artefact_file_embedded'
                if (!empty($resourcetype) && !empty($resourceid)) {
                    foreach ($ids as $id) {
                        insert_record('artefact_file_embedded', (object) array(
                        'fileid' => $artefactids["portfolio:artefact$id"][0],
                        'resourcetype' => $resourcetype,
                        'resourceid' => $resourceid
                        ));
                    }
                }
            }
        }
        return $text;

    }
267
}