Example #1
0
 /**
  * Close the Moodle Workbook.
  */
 public function close()
 {
     global $CFG;
     require_once $CFG->libdir . '/filelib.php';
     $writer = new MoodleODSWriter($this->worksheets);
     $contents = $writer->get_file_content();
     send_file($contents, $this->filename, 0, 0, true, true, $writer->get_ods_mimetype());
 }
Example #2
0
 /**
  * Send role export xml file to browser.
  *
  * @param int $roleid
  * @return void does not return, send the file to output
  */
 public static function send_export_xml($roleid)
 {
     global $CFG, $DB;
     require_once $CFG->libdir . '/filelib.php';
     $role = $DB->get_record('role', array('id' => $roleid), '*', MUST_EXIST);
     if ($role->shortname) {
         $filename = $role->shortname . '.xml';
     } else {
         $filename = 'role.xml';
     }
     $xml = self::get_export_xml($roleid);
     send_file($xml, $filename, 0, false, true, true);
     die;
 }
Example #3
0
function get_thumb($C)
{
    $C = basename($C);
    $G = IDIR . $C;
    $H = null;
    if (_CACHE) {
        $H = CDIR . $C;
        if (file_exists($H)) {
            send_file($H, 'image/jpeg');
            return;
        }
    }
    list($A, $B) = getimagesize($G);
    if ($A > $B) {
        $T = round(($A - $B) / 2);
        $R = 0;
        $A = $B;
    } else {
        $T = 0;
        $R = round(($B - $A) / 2);
        $B = $A;
    }
    $K = imagecreatetruecolor(TS, TS);
    imageinterlace($K, true);
    $Q = @imagecreatefromstring(file_get_contents($G));
    if (!$Q) {
        header("HTTP/1.0 400 Image unreadable, unsupported type.");
        exit;
    }
    imagecopyresampled($K, $Q, 0, 0, $T, $R, TS, TS, $A, $B);
    if (_CACHE) {
        imagejpeg($K, $H, QUALITY);
        send_file($H, 'image/jpeg');
    } else {
        header('Content-Type: image/jpeg');
        imagejpeg($K, null, QUALITY);
    }
    imagedestroy($K);
    imagedestroy($Q);
}
Example #4
0
/**
 * Serves the book attachments. Implements needed access control ;-)
 *
 * @param stdClass $course course object
 * @param cm_info $cm course module object
 * @param context $context context object
 * @param string $filearea file area
 * @param array $args extra arguments
 * @param bool $forcedownload whether or not force download
 * @param array $options additional options affecting the file serving
 * @return bool false if file not found, does not return if found - just send the file
 */
function book_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $CFG, $DB;
    if ($context->contextlevel != CONTEXT_MODULE) {
        return false;
    }
    require_course_login($course, true, $cm);
    if ($filearea !== 'chapter') {
        return false;
    }
    if (!has_capability('mod/book:read', $context)) {
        return false;
    }
    $chid = (int) array_shift($args);
    if (!($book = $DB->get_record('book', array('id' => $cm->instance)))) {
        return false;
    }
    if (!($chapter = $DB->get_record('book_chapters', array('id' => $chid, 'bookid' => $book->id)))) {
        return false;
    }
    if ($chapter->hidden and !has_capability('mod/book:viewhiddenchapters', $context)) {
        return false;
    }
    // Download the contents of a chapter as an html file.
    if ($args[0] == 'index.html') {
        $filename = "index.html";
        // We need to rewrite the pluginfile URLs so the media filters can work.
        $content = file_rewrite_pluginfile_urls($chapter->content, 'webservice/pluginfile.php', $context->id, 'mod_book', 'chapter', $chapter->id);
        $formatoptions = new stdClass();
        $formatoptions->noclean = true;
        $formatoptions->overflowdiv = true;
        $formatoptions->context = $context;
        $content = format_text($content, $chapter->contentformat, $formatoptions);
        // Remove @@PLUGINFILE@@/.
        $options = array('reverse' => true);
        $content = file_rewrite_pluginfile_urls($content, 'webservice/pluginfile.php', $context->id, 'mod_book', 'chapter', $chapter->id, $options);
        $content = str_replace('@@PLUGINFILE@@/', '', $content);
        $titles = "";
        // Format the chapter titles.
        if (!$book->customtitles) {
            require_once __DIR__ . '/locallib.php';
            $chapters = book_preload_chapters($book);
            if (!$chapter->subchapter) {
                $currtitle = book_get_chapter_title($chapter->id, $chapters, $book, $context);
                // Note that we can't use the $OUTPUT->heading() in WS_SERVER mode.
                $titles = "<h3>{$currtitle}</h3>";
            } else {
                $currtitle = book_get_chapter_title($chapters[$chapter->id]->parent, $chapters, $book, $context);
                $currsubtitle = book_get_chapter_title($chapter->id, $chapters, $book, $context);
                // Note that we can't use the $OUTPUT->heading() in WS_SERVER mode.
                $titles = "<h3>{$currtitle}</h3>";
                $titles .= "<h4>{$currsubtitle}</h4>";
            }
        }
        $content = $titles . $content;
        send_file($content, $filename, 0, 0, true, true);
    } else {
        $fs = get_file_storage();
        $relativepath = implode('/', $args);
        $fullpath = "/{$context->id}/mod_book/chapter/{$chid}/{$relativepath}";
        if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
            return false;
        }
        // Nasty hack because we do not have file revisions in book yet.
        $lifetime = $CFG->filelifetime;
        if ($lifetime > 60 * 10) {
            $lifetime = 60 * 10;
        }
        // Finally send the file.
        send_stored_file($file, $lifetime, 0, $forcedownload, $options);
    }
}
Example #5
0
/**
 * Called by pluginfile.php to serve files related to the 'question' core
 * component and for files belonging to qtypes.
 *
 * For files that relate to questions in a question_attempt, then we delegate to
 * a function in the component that owns the attempt (for example in the quiz,
 * or in core question preview) to get necessary inforation.
 *
 * (Note that, at the moment, all question file areas relate to questions in
 * attempts, so the If at the start of the last paragraph is always true.)
 *
 * Does not return, either calls send_file_not_found(); or serves the file.
 *
 * @param object $course course settings object
 * @param object $context context object
 * @param string $component the name of the component we are serving files for.
 * @param string $filearea the name of the file area.
 * @param array $args the remaining bits of the file path.
 * @param bool $forcedownload whether the user must be forced to download the file.
 */
function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload)
{
    global $DB, $CFG;
    list($context, $course, $cm) = get_context_info_array($context->id);
    require_login($course, false, $cm);
    if ($filearea === 'export') {
        require_once $CFG->dirroot . '/question/editlib.php';
        $contexts = new question_edit_contexts($context);
        // check export capability
        $contexts->require_one_edit_tab_cap('export');
        $category_id = (int) array_shift($args);
        $format = array_shift($args);
        $cattofile = array_shift($args);
        $contexttofile = array_shift($args);
        $filename = array_shift($args);
        // load parent class for import/export
        require_once $CFG->dirroot . '/question/format.php';
        require_once $CFG->dirroot . '/question/editlib.php';
        require_once $CFG->dirroot . '/question/format/' . $format . '/format.php';
        $classname = 'qformat_' . $format;
        if (!class_exists($classname)) {
            send_file_not_found();
        }
        $qformat = new $classname();
        if (!($category = $DB->get_record('question_categories', array('id' => $category_id)))) {
            send_file_not_found();
        }
        $qformat->setCategory($category);
        $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
        $qformat->setCourse($course);
        if ($cattofile == 'withcategories') {
            $qformat->setCattofile(true);
        } else {
            $qformat->setCattofile(false);
        }
        if ($contexttofile == 'withcontexts') {
            $qformat->setContexttofile(true);
        } else {
            $qformat->setContexttofile(false);
        }
        if (!$qformat->exportpreprocess()) {
            send_file_not_found();
            print_error('exporterror', 'question', $thispageurl->out());
        }
        // export data to moodle file pool
        if (!($content = $qformat->exportprocess(true))) {
            send_file_not_found();
        }
        //DEBUG
        //echo '<textarea cols=90 rows=20>';
        //echo $content;
        //echo '</textarea>';
        //die;
        send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
    }
    $attemptid = (int) array_shift($args);
    $questionid = (int) array_shift($args);
    if ($attemptid === 0) {
        // preview
        require_once $CFG->dirroot . '/question/previewlib.php';
        return question_preview_question_pluginfile($course, $context, $component, $filearea, $attemptid, $questionid, $args, $forcedownload);
    } else {
        $module = $DB->get_field('question_attempts', 'modulename', array('id' => $attemptid));
        $dir = get_component_directory($module);
        if (!file_exists("{$dir}/lib.php")) {
            send_file_not_found();
        }
        include_once "{$dir}/lib.php";
        $filefunction = $module . '_question_pluginfile';
        if (!function_exists($filefunction)) {
            send_file_not_found();
        }
        $filefunction($course, $context, $component, $filearea, $attemptid, $questionid, $args, $forcedownload);
        send_file_not_found();
    }
}
Example #6
0
 /**
  * Displays a thumbnail for current user's dropbox file
  *
  * @param string $string
  */
 public function send_thumbnail($source)
 {
     global $CFG;
     $saveas = $this->prepare_file('');
     try {
         $access_key = get_user_preferences($this->setting . '_access_key', '');
         $access_secret = get_user_preferences($this->setting . '_access_secret', '');
         $this->dropbox->set_access_token($access_key, $access_secret);
         $this->dropbox->get_thumbnail($source, $saveas, $CFG->repositorysyncimagetimeout);
         $content = file_get_contents($saveas);
         unlink($saveas);
         // set 30 days lifetime for the image. If the image is changed in dropbox it will have
         // different revision number and URL will be different. It is completely safe
         // to cache thumbnail in the browser for a long time
         send_file($content, basename($source), 30 * 24 * 60 * 60, 0, true);
     } catch (Exception $e) {
     }
 }
Example #7
0
 /**
  *  Gets a file relative to this file in the repository and sends it to the browser.
  *
  * @param stored_file $mainfile The main file we are trying to access relative files for.
  * @param string $relativepath the relative path to the file we are trying to access.
  */
 public function send_relative_file(stored_file $mainfile, $relativepath)
 {
     global $CFG;
     // Check if this repository is allowed to use relative linking.
     $allowlinks = $this->supports_relative_file();
     if (!empty($allowlinks)) {
         // Get path to the mainfile.
         $mainfilepath = $mainfile->get_source();
         // Strip out filename from the path.
         $filename = $mainfile->get_filename();
         $basepath = strstr($mainfilepath, $filename, true);
         $fullrelativefilepath = realpath($this->get_rootpath() . $basepath . $relativepath);
         // Sanity check to make sure this path is inside this repository and the file exists.
         if (strpos($fullrelativefilepath, realpath($this->get_rootpath())) === 0 && file_exists($fullrelativefilepath)) {
             send_file($fullrelativefilepath, basename($relativepath), null, 0);
         }
     }
     send_file_not_found();
 }
Example #8
0
/**
 * This function delegates file serving to individual plugins
 *
 * @param string $relativepath
 * @param bool $forcedownload
 * @param null|string $preview the preview mode, defaults to serving the original file
 * @todo MDL-31088 file serving improments
 */
function file_pluginfile($relativepath, $forcedownload, $preview = null)
{
    global $DB, $CFG, $USER;
    // relative path must start with '/'
    if (!$relativepath) {
        print_error('invalidargorconf');
    } else {
        if ($relativepath[0] != '/') {
            print_error('pathdoesnotstartslash');
        }
    }
    // extract relative path components
    $args = explode('/', ltrim($relativepath, '/'));
    if (count($args) < 3) {
        // always at least context, component and filearea
        print_error('invalidarguments');
    }
    $contextid = (int) array_shift($args);
    $component = clean_param(array_shift($args), PARAM_COMPONENT);
    $filearea = clean_param(array_shift($args), PARAM_AREA);
    list($context, $course, $cm) = get_context_info_array($contextid);
    $fs = get_file_storage();
    // ========================================================================================================================
    if ($component === 'blog') {
        // Blog file serving
        if ($context->contextlevel != CONTEXT_SYSTEM) {
            send_file_not_found();
        }
        if ($filearea !== 'attachment' and $filearea !== 'post') {
            send_file_not_found();
        }
        if (empty($CFG->enableblogs)) {
            print_error('siteblogdisable', 'blog');
        }
        $entryid = (int) array_shift($args);
        if (!($entry = $DB->get_record('post', array('module' => 'blog', 'id' => $entryid)))) {
            send_file_not_found();
        }
        if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
            require_login();
            if (isguestuser()) {
                print_error('noguest');
            }
            if ($CFG->bloglevel == BLOG_USER_LEVEL) {
                if ($USER->id != $entry->userid) {
                    send_file_not_found();
                }
            }
        }
        if ($entry->publishstate === 'public') {
            if ($CFG->forcelogin) {
                require_login();
            }
        } else {
            if ($entry->publishstate === 'site') {
                require_login();
                //ok
            } else {
                if ($entry->publishstate === 'draft') {
                    require_login();
                    if ($USER->id != $entry->userid) {
                        send_file_not_found();
                    }
                }
            }
        }
        $filename = array_pop($args);
        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
        if (!($file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename)) or $file->is_directory()) {
            send_file_not_found();
        }
        send_stored_file($file, 10 * 60, 0, true, array('preview' => $preview));
        // download MUST be forced - security!
        // ========================================================================================================================
    } else {
        if ($component === 'grade') {
            if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
                // Global gradebook files
                if ($CFG->forcelogin) {
                    require_login();
                }
                $fullpath = "/{$context->id}/{$component}/{$filearea}/" . implode('/', $args);
                if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                    send_file_not_found();
                }
                \core\session\manager::write_close();
                // Unlock session during file serving.
                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
            } else {
                if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
                    //TODO: nobody implemented this yet in grade edit form!!
                    send_file_not_found();
                    if ($CFG->forcelogin || $course->id != SITEID) {
                        require_login($course);
                    }
                    $fullpath = "/{$context->id}/{$component}/{$filearea}/" . implode('/', $args);
                    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                        send_file_not_found();
                    }
                    \core\session\manager::write_close();
                    // Unlock session during file serving.
                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                } else {
                    send_file_not_found();
                }
            }
            // ========================================================================================================================
        } else {
            if ($component === 'tag') {
                if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
                    // All tag descriptions are going to be public but we still need to respect forcelogin
                    if ($CFG->forcelogin) {
                        require_login();
                    }
                    $fullpath = "/{$context->id}/tag/description/" . implode('/', $args);
                    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                        send_file_not_found();
                    }
                    \core\session\manager::write_close();
                    // Unlock session during file serving.
                    send_stored_file($file, 60 * 60, 0, true, array('preview' => $preview));
                } else {
                    send_file_not_found();
                }
                // ========================================================================================================================
            } else {
                if ($component === 'badges') {
                    require_once $CFG->libdir . '/badgeslib.php';
                    $badgeid = (int) array_shift($args);
                    $badge = new badge($badgeid);
                    $filename = array_pop($args);
                    if ($filearea === 'badgeimage') {
                        if ($filename !== 'f1' && $filename !== 'f2') {
                            send_file_not_found();
                        }
                        if (!($file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename . '.png'))) {
                            send_file_not_found();
                        }
                        \core\session\manager::write_close();
                        send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                    } else {
                        if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
                            if (!($file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename . '.png'))) {
                                send_file_not_found();
                            }
                            \core\session\manager::write_close();
                            send_stored_file($file, 60 * 60, 0, true, array('preview' => $preview));
                        }
                    }
                    // ========================================================================================================================
                } else {
                    if ($component === 'calendar') {
                        if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
                            // All events here are public the one requirement is that we respect forcelogin
                            if ($CFG->forcelogin) {
                                require_login();
                            }
                            // Get the event if from the args array
                            $eventid = array_shift($args);
                            // Load the event from the database
                            if (!($event = $DB->get_record('event', array('id' => (int) $eventid, 'eventtype' => 'site')))) {
                                send_file_not_found();
                            }
                            // Get the file and serve if successful
                            $filename = array_pop($args);
                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                            if (!($file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename)) or $file->is_directory()) {
                                send_file_not_found();
                            }
                            \core\session\manager::write_close();
                            // Unlock session during file serving.
                            send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                        } else {
                            if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
                                // Must be logged in, if they are not then they obviously can't be this user
                                require_login();
                                // Don't want guests here, potentially saves a DB call
                                if (isguestuser()) {
                                    send_file_not_found();
                                }
                                // Get the event if from the args array
                                $eventid = array_shift($args);
                                // Load the event from the database - user id must match
                                if (!($event = $DB->get_record('event', array('id' => (int) $eventid, 'userid' => $USER->id, 'eventtype' => 'user')))) {
                                    send_file_not_found();
                                }
                                // Get the file and serve if successful
                                $filename = array_pop($args);
                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                if (!($file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename)) or $file->is_directory()) {
                                    send_file_not_found();
                                }
                                \core\session\manager::write_close();
                                // Unlock session during file serving.
                                send_stored_file($file, 0, 0, true, array('preview' => $preview));
                            } else {
                                if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
                                    // Respect forcelogin and require login unless this is the site.... it probably
                                    // should NEVER be the site
                                    if ($CFG->forcelogin || $course->id != SITEID) {
                                        require_login($course);
                                    }
                                    // Must be able to at least view the course. This does not apply to the front page.
                                    if ($course->id != SITEID && !is_enrolled($context) && !is_viewing($context)) {
                                        //TODO: hmm, do we really want to block guests here?
                                        send_file_not_found();
                                    }
                                    // Get the event id
                                    $eventid = array_shift($args);
                                    // Load the event from the database we need to check whether it is
                                    // a) valid course event
                                    // b) a group event
                                    // Group events use the course context (there is no group context)
                                    if (!($event = $DB->get_record('event', array('id' => (int) $eventid, 'courseid' => $course->id)))) {
                                        send_file_not_found();
                                    }
                                    // If its a group event require either membership of view all groups capability
                                    if ($event->eventtype === 'group') {
                                        if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
                                            send_file_not_found();
                                        }
                                    } else {
                                        if ($event->eventtype === 'course' || $event->eventtype === 'site') {
                                            // Ok. Please note that the event type 'site' still uses a course context.
                                        } else {
                                            // Some other type.
                                            send_file_not_found();
                                        }
                                    }
                                    // If we get this far we can serve the file
                                    $filename = array_pop($args);
                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                    if (!($file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename)) or $file->is_directory()) {
                                        send_file_not_found();
                                    }
                                    \core\session\manager::write_close();
                                    // Unlock session during file serving.
                                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                } else {
                                    send_file_not_found();
                                }
                            }
                        }
                        // ========================================================================================================================
                    } else {
                        if ($component === 'user') {
                            if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
                                if (count($args) == 1) {
                                    $themename = theme_config::DEFAULT_THEME;
                                    $filename = array_shift($args);
                                } else {
                                    $themename = array_shift($args);
                                    $filename = array_shift($args);
                                }
                                // fix file name automatically
                                if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
                                    $filename = 'f1';
                                }
                                if ((!empty($CFG->forcelogin) and !isloggedin()) || !empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser())) {
                                    // protect images if login required and not logged in;
                                    // also if login is required for profile images and is not logged in or guest
                                    // do not use require_login() because it is expensive and not suitable here anyway
                                    $theme = theme_config::load($themename);
                                    redirect($theme->pix_url('u/' . $filename, 'moodle'));
                                    // intentionally not cached
                                }
                                if (!($file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename . '.png'))) {
                                    if (!($file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename . '.jpg'))) {
                                        if ($filename === 'f3') {
                                            // f3 512x512px was introduced in 2.3, there might be only the smaller version.
                                            if (!($file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png'))) {
                                                $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
                                            }
                                        }
                                    }
                                }
                                if (!$file) {
                                    // bad reference - try to prevent future retries as hard as possible!
                                    if ($user = $DB->get_record('user', array('id' => $context->instanceid), 'id, picture')) {
                                        if ($user->picture > 0) {
                                            $DB->set_field('user', 'picture', 0, array('id' => $user->id));
                                        }
                                    }
                                    // no redirect here because it is not cached
                                    $theme = theme_config::load($themename);
                                    $imagefile = $theme->resolve_image_location('u/' . $filename, 'moodle', null);
                                    send_file($imagefile, basename($imagefile), 60 * 60 * 24 * 14);
                                }
                                $options = array('preview' => $preview);
                                if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
                                    // Profile images should be cache-able by both browsers and proxies according
                                    // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
                                    $options['cacheability'] = 'public';
                                }
                                send_stored_file($file, 60 * 60 * 24 * 365, 0, false, $options);
                                // enable long caching, there are many images on each page
                            } else {
                                if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
                                    require_login();
                                    if (isguestuser()) {
                                        send_file_not_found();
                                    }
                                    if ($USER->id !== $context->instanceid) {
                                        send_file_not_found();
                                    }
                                    $filename = array_pop($args);
                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                    if (!($file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename)) or $file->is_directory()) {
                                        send_file_not_found();
                                    }
                                    \core\session\manager::write_close();
                                    // Unlock session during file serving.
                                    send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                    // must force download - security!
                                } else {
                                    if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
                                        if ($CFG->forcelogin) {
                                            require_login();
                                        }
                                        $userid = $context->instanceid;
                                        if ($USER->id == $userid) {
                                            // always can access own
                                        } else {
                                            if (!empty($CFG->forceloginforprofiles)) {
                                                require_login();
                                                if (isguestuser()) {
                                                    send_file_not_found();
                                                }
                                                // we allow access to site profile of all course contacts (usually teachers)
                                                if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
                                                    send_file_not_found();
                                                }
                                                $canview = false;
                                                if (has_capability('moodle/user:viewdetails', $context)) {
                                                    $canview = true;
                                                } else {
                                                    $courses = enrol_get_my_courses();
                                                }
                                                while (!$canview && count($courses) > 0) {
                                                    $course = array_shift($courses);
                                                    if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
                                                        $canview = true;
                                                    }
                                                }
                                            }
                                        }
                                        $filename = array_pop($args);
                                        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                        if (!($file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename)) or $file->is_directory()) {
                                            send_file_not_found();
                                        }
                                        \core\session\manager::write_close();
                                        // Unlock session during file serving.
                                        send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                        // must force download - security!
                                    } else {
                                        if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
                                            $userid = (int) array_shift($args);
                                            $usercontext = context_user::instance($userid);
                                            if ($CFG->forcelogin) {
                                                require_login();
                                            }
                                            if (!empty($CFG->forceloginforprofiles)) {
                                                require_login();
                                                if (isguestuser()) {
                                                    print_error('noguest');
                                                }
                                                //TODO: review this logic of user profile access prevention
                                                if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
                                                    print_error('usernotavailable');
                                                }
                                                if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
                                                    print_error('cannotviewprofile');
                                                }
                                                if (!is_enrolled($context, $userid)) {
                                                    print_error('notenrolledprofile');
                                                }
                                                if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                                                    print_error('groupnotamember');
                                                }
                                            }
                                            $filename = array_pop($args);
                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                            if (!($file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename)) or $file->is_directory()) {
                                                send_file_not_found();
                                            }
                                            \core\session\manager::write_close();
                                            // Unlock session during file serving.
                                            send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                            // must force download - security!
                                        } else {
                                            if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
                                                require_login();
                                                if (isguestuser()) {
                                                    send_file_not_found();
                                                }
                                                $userid = $context->instanceid;
                                                if ($USER->id != $userid) {
                                                    send_file_not_found();
                                                }
                                                $filename = array_pop($args);
                                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                if (!($file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename)) or $file->is_directory()) {
                                                    send_file_not_found();
                                                }
                                                \core\session\manager::write_close();
                                                // Unlock session during file serving.
                                                send_stored_file($file, 0, 0, true, array('preview' => $preview));
                                                // must force download - security!
                                            } else {
                                                send_file_not_found();
                                            }
                                        }
                                    }
                                }
                            }
                            // ========================================================================================================================
                        } else {
                            if ($component === 'coursecat') {
                                if ($context->contextlevel != CONTEXT_COURSECAT) {
                                    send_file_not_found();
                                }
                                if ($filearea === 'description') {
                                    if ($CFG->forcelogin) {
                                        // no login necessary - unless login forced everywhere
                                        require_login();
                                    }
                                    $filename = array_pop($args);
                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                    if (!($file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename)) or $file->is_directory()) {
                                        send_file_not_found();
                                    }
                                    \core\session\manager::write_close();
                                    // Unlock session during file serving.
                                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                } else {
                                    send_file_not_found();
                                }
                                // ========================================================================================================================
                            } else {
                                if ($component === 'course') {
                                    if ($context->contextlevel != CONTEXT_COURSE) {
                                        send_file_not_found();
                                    }
                                    if ($filearea === 'summary' || $filearea === 'overviewfiles') {
                                        if ($CFG->forcelogin) {
                                            require_login();
                                        }
                                        $filename = array_pop($args);
                                        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                        if (!($file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename)) or $file->is_directory()) {
                                            send_file_not_found();
                                        }
                                        \core\session\manager::write_close();
                                        // Unlock session during file serving.
                                        send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                    } else {
                                        if ($filearea === 'section') {
                                            if ($CFG->forcelogin) {
                                                require_login($course);
                                            } else {
                                                if ($course->id != SITEID) {
                                                    require_login($course);
                                                }
                                            }
                                            $sectionid = (int) array_shift($args);
                                            if (!($section = $DB->get_record('course_sections', array('id' => $sectionid, 'course' => $course->id)))) {
                                                send_file_not_found();
                                            }
                                            $filename = array_pop($args);
                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                            if (!($file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename)) or $file->is_directory()) {
                                                send_file_not_found();
                                            }
                                            \core\session\manager::write_close();
                                            // Unlock session during file serving.
                                            send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                        } else {
                                            send_file_not_found();
                                        }
                                    }
                                } else {
                                    if ($component === 'cohort') {
                                        $cohortid = (int) array_shift($args);
                                        $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
                                        $cohortcontext = context::instance_by_id($cohort->contextid);
                                        // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
                                        if ($context->id != $cohort->contextid && ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
                                            send_file_not_found();
                                        }
                                        // User is able to access cohort if they have view cap on cohort level or
                                        // the cohort is visible and they have view cap on course level.
                                        $canview = has_capability('moodle/cohort:view', $cohortcontext) || $cohort->visible && has_capability('moodle/cohort:view', $context);
                                        if ($filearea === 'description' && $canview) {
                                            $filename = array_pop($args);
                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                            if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename)) && !$file->is_directory()) {
                                                \core\session\manager::write_close();
                                                // Unlock session during file serving.
                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                            }
                                        }
                                        send_file_not_found();
                                    } else {
                                        if ($component === 'group') {
                                            if ($context->contextlevel != CONTEXT_COURSE) {
                                                send_file_not_found();
                                            }
                                            require_course_login($course, true, null, false);
                                            $groupid = (int) array_shift($args);
                                            $group = $DB->get_record('groups', array('id' => $groupid, 'courseid' => $course->id), '*', MUST_EXIST);
                                            if ($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
                                                // do not allow access to separate group info if not member or teacher
                                                send_file_not_found();
                                            }
                                            if ($filearea === 'description') {
                                                require_login($course);
                                                $filename = array_pop($args);
                                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                if (!($file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename)) or $file->is_directory()) {
                                                    send_file_not_found();
                                                }
                                                \core\session\manager::write_close();
                                                // Unlock session during file serving.
                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                            } else {
                                                if ($filearea === 'icon') {
                                                    $filename = array_pop($args);
                                                    if ($filename !== 'f1' and $filename !== 'f2') {
                                                        send_file_not_found();
                                                    }
                                                    if (!($file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename . '.png'))) {
                                                        if (!($file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename . '.jpg'))) {
                                                            send_file_not_found();
                                                        }
                                                    }
                                                    \core\session\manager::write_close();
                                                    // Unlock session during file serving.
                                                    send_stored_file($file, 60 * 60, 0, false, array('preview' => $preview));
                                                } else {
                                                    send_file_not_found();
                                                }
                                            }
                                        } else {
                                            if ($component === 'grouping') {
                                                if ($context->contextlevel != CONTEXT_COURSE) {
                                                    send_file_not_found();
                                                }
                                                require_login($course);
                                                $groupingid = (int) array_shift($args);
                                                // note: everybody has access to grouping desc images for now
                                                if ($filearea === 'description') {
                                                    $filename = array_pop($args);
                                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                    if (!($file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename)) or $file->is_directory()) {
                                                        send_file_not_found();
                                                    }
                                                    \core\session\manager::write_close();
                                                    // Unlock session during file serving.
                                                    send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                } else {
                                                    send_file_not_found();
                                                }
                                                // ========================================================================================================================
                                            } else {
                                                if ($component === 'backup') {
                                                    if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
                                                        require_login($course);
                                                        require_capability('moodle/backup:downloadfile', $context);
                                                        $filename = array_pop($args);
                                                        $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                        if (!($file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename)) or $file->is_directory()) {
                                                            send_file_not_found();
                                                        }
                                                        \core\session\manager::write_close();
                                                        // Unlock session during file serving.
                                                        send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
                                                    } else {
                                                        if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
                                                            require_login($course);
                                                            require_capability('moodle/backup:downloadfile', $context);
                                                            $sectionid = (int) array_shift($args);
                                                            $filename = array_pop($args);
                                                            $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                            if (!($file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename)) or $file->is_directory()) {
                                                                send_file_not_found();
                                                            }
                                                            \core\session\manager::write_close();
                                                            send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                        } else {
                                                            if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
                                                                require_login($course, false, $cm);
                                                                require_capability('moodle/backup:downloadfile', $context);
                                                                $filename = array_pop($args);
                                                                $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                                if (!($file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename)) or $file->is_directory()) {
                                                                    send_file_not_found();
                                                                }
                                                                \core\session\manager::write_close();
                                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                            } else {
                                                                if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
                                                                    // Backup files that were generated by the automated backup systems.
                                                                    require_login($course);
                                                                    require_capability('moodle/site:config', $context);
                                                                    $filename = array_pop($args);
                                                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                                    if (!($file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename)) or $file->is_directory()) {
                                                                        send_file_not_found();
                                                                    }
                                                                    \core\session\manager::write_close();
                                                                    // Unlock session during file serving.
                                                                    send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
                                                                } else {
                                                                    send_file_not_found();
                                                                }
                                                            }
                                                        }
                                                    }
                                                    // ========================================================================================================================
                                                } else {
                                                    if ($component === 'question') {
                                                        require_once $CFG->libdir . '/questionlib.php';
                                                        question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
                                                        send_file_not_found();
                                                        // ========================================================================================================================
                                                    } else {
                                                        if ($component === 'grading') {
                                                            if ($filearea === 'description') {
                                                                // files embedded into the form definition description
                                                                if ($context->contextlevel == CONTEXT_SYSTEM) {
                                                                    require_login();
                                                                } else {
                                                                    if ($context->contextlevel >= CONTEXT_COURSE) {
                                                                        require_login($course, false, $cm);
                                                                    } else {
                                                                        send_file_not_found();
                                                                    }
                                                                }
                                                                $formid = (int) array_shift($args);
                                                                $sql = "SELECT ga.id\n                FROM {grading_areas} ga\n                JOIN {grading_definitions} gd ON (gd.areaid = ga.id)\n                WHERE gd.id = ? AND ga.contextid = ?";
                                                                $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
                                                                if (!$areaid) {
                                                                    send_file_not_found();
                                                                }
                                                                $fullpath = "/{$context->id}/{$component}/{$filearea}/{$formid}/" . implode('/', $args);
                                                                if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
                                                                    send_file_not_found();
                                                                }
                                                                \core\session\manager::write_close();
                                                                // Unlock session during file serving.
                                                                send_stored_file($file, 60 * 60, 0, $forcedownload, array('preview' => $preview));
                                                            }
                                                            // ========================================================================================================================
                                                        } else {
                                                            if (strpos($component, 'mod_') === 0) {
                                                                $modname = substr($component, 4);
                                                                if (!file_exists("{$CFG->dirroot}/mod/{$modname}/lib.php")) {
                                                                    send_file_not_found();
                                                                }
                                                                require_once "{$CFG->dirroot}/mod/{$modname}/lib.php";
                                                                if ($context->contextlevel == CONTEXT_MODULE) {
                                                                    if ($cm->modname !== $modname) {
                                                                        // somebody tries to gain illegal access, cm type must match the component!
                                                                        send_file_not_found();
                                                                    }
                                                                }
                                                                if ($filearea === 'intro') {
                                                                    if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
                                                                        send_file_not_found();
                                                                    }
                                                                    require_course_login($course, true, $cm);
                                                                    // all users may access it
                                                                    $filename = array_pop($args);
                                                                    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
                                                                    if (!($file = $fs->get_file($context->id, 'mod_' . $modname, 'intro', 0, $filepath, $filename)) or $file->is_directory()) {
                                                                        send_file_not_found();
                                                                    }
                                                                    // finally send the file
                                                                    send_stored_file($file, null, 0, false, array('preview' => $preview));
                                                                }
                                                                $filefunction = $component . '_pluginfile';
                                                                $filefunctionold = $modname . '_pluginfile';
                                                                if (function_exists($filefunction)) {
                                                                    // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                    $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                } else {
                                                                    if (function_exists($filefunctionold)) {
                                                                        // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                        $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                    }
                                                                }
                                                                send_file_not_found();
                                                                // ========================================================================================================================
                                                            } else {
                                                                if (strpos($component, 'block_') === 0) {
                                                                    $blockname = substr($component, 6);
                                                                    // note: no more class methods in blocks please, that is ....
                                                                    if (!file_exists("{$CFG->dirroot}/blocks/{$blockname}/lib.php")) {
                                                                        send_file_not_found();
                                                                    }
                                                                    require_once "{$CFG->dirroot}/blocks/{$blockname}/lib.php";
                                                                    if ($context->contextlevel == CONTEXT_BLOCK) {
                                                                        $birecord = $DB->get_record('block_instances', array('id' => $context->instanceid), '*', MUST_EXIST);
                                                                        if ($birecord->blockname !== $blockname) {
                                                                            // somebody tries to gain illegal access, cm type must match the component!
                                                                            send_file_not_found();
                                                                        }
                                                                        if ($context->get_course_context(false)) {
                                                                            // If block is in course context, then check if user has capability to access course.
                                                                            require_course_login($course);
                                                                        } else {
                                                                            if ($CFG->forcelogin) {
                                                                                // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
                                                                                require_login();
                                                                            }
                                                                        }
                                                                        $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
                                                                        // User can't access file, if block is hidden or doesn't have block:view capability
                                                                        if ($bprecord && !$bprecord->visible || !has_capability('moodle/block:view', $context)) {
                                                                            send_file_not_found();
                                                                        }
                                                                    } else {
                                                                        $birecord = null;
                                                                    }
                                                                    $filefunction = $component . '_pluginfile';
                                                                    if (function_exists($filefunction)) {
                                                                        // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                        $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                    }
                                                                    send_file_not_found();
                                                                    // ========================================================================================================================
                                                                } else {
                                                                    if (strpos($component, '_') === false) {
                                                                        // all core subsystems have to be specified above, no more guessing here!
                                                                        send_file_not_found();
                                                                    } else {
                                                                        // try to serve general plugin file in arbitrary context
                                                                        $dir = core_component::get_component_directory($component);
                                                                        if (!file_exists("{$dir}/lib.php")) {
                                                                            send_file_not_found();
                                                                        }
                                                                        include_once "{$dir}/lib.php";
                                                                        $filefunction = $component . '_pluginfile';
                                                                        if (function_exists($filefunction)) {
                                                                            // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
                                                                            $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
                                                                        }
                                                                        send_file_not_found();
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
    // force download of all attachments
}
// security: some protection of hidden resource files
// warning: it may break backwards compatibility
if (!empty($CFG->preventaccesstohiddenfiles) and count($args) >= 2 and !(strtolower($args[1]) == 'moddata' and strtolower($args[2]) != 'resource') and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
    $rargs = $args;
    array_shift($rargs);
    $reference = implode('/', $rargs);
    $sql = "SELECT COUNT(r.id) " . "FROM {$CFG->prefix}resource r, " . "{$CFG->prefix}course_modules cm, " . "{$CFG->prefix}modules m " . "WHERE r.course    = '{$course->id}' " . "AND m.name      = 'resource' " . "AND cm.module   = m.id " . "AND cm.instance = r.id " . "AND cm.visible  = 0 " . "AND r.type      = 'file' " . "AND r.reference = '{$reference}'";
    if (count_records_sql($sql)) {
        error('Access not allowed');
    }
}
// check that file exists
if (!file_exists($pathname)) {
    not_found($course->id);
}
// ========================================
// finally send the file
// ========================================
session_write_close();
// unlock session during fileserving
$filename = $args[count($args) - 1];
send_file($pathname, $filename, $lifetime, $CFG->filteruploadedfiles, false, $forcedownload);
function not_found($courseid)
{
    global $CFG;
    header('HTTP/1.0 404 not found');
    print_error('filenotfound', 'error', $CFG->wwwroot . '/course/view.php?id=' . $courseid);
    //this is not displayed on IIS??
}
Example #10
0
<?php

/*
 * This file is called by the offline Moodle SERVER and sends the existing
 * incremental or Full backup if no incremental is available to the client.
 * 
 */
require '../config.php';
require_once "{$CFG->dirroot}/backup/backup_sch_incremental.php";
require_once "{$CFG->dirroot}/backup/incremental_backuplib.php";
require_once "{$CFG->dirroot}/backup/backuplib.php";
require_once "{$CFG->dirroot}/backup/lib.php";
require_once "{$CFG->dirroot}/lib/filelib.php";
$currenthash = required_param('hash');
// hash
$action = required_param('action');
// what to do?
$file = get_incremental($currenthash);
if ($file) {
    if ($action == 'curldownload') {
        readfile_chunked($file->path . $file->name);
    } elseif ($action == 'download') {
        send_file($file->path, $file->name, 864, 0, true, true);
    } elseif ($action == 'check') {
        echo $file->name;
    } else {
        echo 'no action specified';
    }
} else {
    echo 'ERROR!!! No file returned';
}
Example #11
0
/**
 * Sends an error formatted as an rss file and then exits
 *
 * @package core_rss
 * @category rss
 *
 * @param string $error the error type, default is rsserror
 * @param string $filename the name of the file to create (NOT USED)
 * @param int $lifetime UNSURE (NOT USED)
 * @uses exit
 */
function rss_error($error = 'rsserror', $filename = 'rss.xml', $lifetime = 0)
{
    send_file(rss_geterrorxmlfile($error), $filename, $lifetime, false, true);
    exit;
}
Example #12
0
 /**
  * Repository method to serve the referenced file
  *
  * @see send_stored_file
  *
  * @param stored_file $storedfile the file that contains the reference
  * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
  * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  * @param array $options additional options affecting the file serving
  */
 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
     $reference = $storedfile->get_reference();
     if ($reference{0} == '/') {
         $file = $this->root_path.substr($reference, 1, strlen($reference)-1);
     } else {
         $file = $this->root_path.$reference;
     }
     if (is_readable($file)) {
         $filename = $storedfile->get_filename();
         if ($options && isset($options['filename'])) {
             $filename = $options['filename'];
         }
         $dontdie = ($options && isset($options['dontdie']));
         send_file($file, $filename, $lifetime , $filter, false, $forcedownload, '', $dontdie);
     } else {
         send_file_not_found();
     }
 }
Example #13
0
function tex2image($texexp, $md5, $return = false)
{
    global $CFG;
    if (!$texexp) {
        echo 'No tex expresion specified';
        return;
    }
    $texexp = '\\Large ' . $texexp;
    $image = $md5 . ".gif";
    $filetype = 'image/gif';
    if (!file_exists("{$CFG->dataroot}/filter/algebra")) {
        make_upload_directory("filter/algebra");
    }
    $pathname = "{$CFG->dataroot}/filter/algebra/{$image}";
    if (file_exists($pathname)) {
        unlink($pathname);
    }
    $commandpath = filter_tex_get_executable(true);
    $cmd = filter_tex_get_cmd($pathname, $texexp);
    system($cmd, $status);
    if ($return) {
        return $image;
    }
    if (file_exists($pathname)) {
        send_file($pathname, $image);
    } else {
        $ecmd = "{$cmd} 2>&1";
        echo `{$ecmd}` . "<br />\n";
        echo "The shell command<br />{$cmd}<br />returned status = {$status}<br />\n";
        if ($status == 4) {
            echo "Status corresponds to illegal instruction<br />\n";
        } else {
            if ($status == 11) {
                echo "Status corresponds to bus error<br />\n";
            } else {
                if ($status == 22) {
                    echo "Status corresponds to abnormal termination<br />\n";
                }
            }
        }
        if (file_exists($commandpath)) {
            echo "File size of mimetex executable  {$commandpath} is " . filesize($commandpath) . "<br />";
            echo "The file permissions are: " . decoct(fileperms($commandpath)) . "<br />";
            if (function_exists("md5_file")) {
                echo "The md5 checksum of the file is " . md5_file($commandpath) . "<br />";
            } else {
                $handle = fopen($commandpath, "rb");
                $contents = fread($handle, 16384);
                fclose($handle);
                echo "The md5 checksum of the first 16384 bytes is " . md5($contents) . "<br />";
            }
        } else {
            echo "mimetex executable {$commandpath} not found!<br />";
        }
        echo "Image not found!";
    }
}
Example #14
0
        $background = $CFG->filter_tex_latexbackground;
        $texexp = html_entity_decode($texcache->rawtext);
        $latex_path = $latex->render($texexp, $md5, 12, $density, $background);
        if ($latex_path) {
            copy($latex_path, $pathname);
            $latex->clean_up($md5);
        } else {
            // failing that, use mimetex
            $texexp = $texcache->rawtext;
            $texexp = str_replace('&lt;', '<', $texexp);
            $texexp = str_replace('&gt;', '>', $texexp);
            $texexp = preg_replace('!\\r\\n?!', ' ', $texexp);
            $texexp = '\\Large ' . $texexp;
            $cmd = tex_filter_get_cmd($pathname, $texexp);
            system($cmd, $status);
        }
    }
}
if (file_exists($pathname)) {
    send_file($pathname, $image);
} else {
    if (debugging()) {
        echo "The shell command<br />{$cmd}<br />returned status = {$status}<br />\n";
        echo "Image not found!<br />";
        echo "Please try the <a href=\"{$CFG->wwwroot}/filter/tex/texdebug.php\">debugging script</a>";
    } else {
        echo "Image not found!<br />";
        echo "Please try the <a href=\"{$CFG->wwwroot}/filter/tex/texdebug.php\">debugging script</a><br />";
        echo "Please turn on debug mode in site configuration to see more info here.";
    }
}
Example #15
0
require_once 'KLogger.php';
$log = new KLogger("log.txt", KLogger::DEBUG);
if (empty($_GET['fileid'])) {
    return false;
} else {
    $fileid = $_GET['fileid'];
}
$log->LogInfo("Download: {$fileid}");
// log file
$client_no = rand();
$logfile = uniqid(rand(), true) . '.log';
$outfile = uniqid(rand(), true) . '.out';
system("cd ../bin; ./CLIENT_p -i {$client_no} -a download -f {$fileid} -t {$outfile} > {$logfile} 2>&1");
$log->LogInfo("Downloaded from NCDS FileID: {$fileid}");
send_file("../bin/{$outfile}", $fileid);
unlink("../bin/{$outfile}");
unlink("../bin/{$logfile}");
$log->LogInfo("Sent to Client FileID: {$fileid}");
function send_file($file, $fileid)
{
    if (empty($_GET['filename'])) {
        $filename = $fileid;
    } else {
        $filename = urldecode($_GET['filename']);
    }
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment; filename={$filename}");
        header('Content-Transfer-Encoding: binary');
Example #16
0
        $file_extension = $regs[2];
        $file['file_name'] = $file_name . ($size ? "_" . $size : "") . "." . $file_extension;
        $file['file_path'] = is_local_file($image_row['image_media_file']) ? dirname($image_row['image_media_file']) . "/" . $file['file_name'] : MEDIA_PATH . "/" . $image_row['cat_id'] . "/" . $file['file_name'];
    }
    if ($user_info['user_level'] != ADMIN) {
        $sql = "UPDATE " . IMAGES_TABLE . "\n            SET image_downloads = image_downloads + 1\n            WHERE image_id = {$image_id}";
        $site_db->query($sql);
    }
    if (!empty($file['file_path'])) {
        @set_time_limit(120);
        if ($remote_url) {
            redirect($file['file_path']);
        }
        if ($action == "zip" && !preg_match("/\\.zip\$/i", $file['file_name']) && function_exists("gzcompress") && function_exists("crc32")) {
            include ROOT_PATH . "includes/zip.php";
            $zipfile = new zipfile();
            $zipfile->add_file(file_get_contents($file['file_path']), $file['file_name']);
            $zipfile->send(get_file_name($file['file_name']) . ".zip");
        } else {
            send_file($file['file_name'], $file['file_path']);
        }
        exit;
    } else {
        echo $lang['download_error'] . "\n<!-- EMPTY FILE PATH //-->";
        exit;
    }
} else {
    echo $lang['download_error'] . "\n<!-- NO ACTION SPECIFIED //-->";
    exit;
}
exit;
Example #17
0
if (!empty($CFG->forcelogin) and !isloggedin()) {
    // protect images if login required and not logged in;
    // do not use require_login() because it is expensive and not suitable here anyway
    redirect('img/error.png');
}
// disable moodle specific debug messages
disable_debugging();
$relativepath = get_file_argument('download.php');
$args = explode('/', trim($relativepath, '/'));
if (count($args) == 2) {
    $pathname = $CFG->dataroot . '/user/d0' . $relativepath;
    $lifetime = 0;
    /// Verify role assignment of the student in the specified course
    $pos = strrpos($args[1], '.pdf');
    $coursename = substr($args[1], 0, $pos);
    $user = get_record('user', 'id', $args[0]);
    if ($user === false) {
        redirect('img/error.png');
    }
    $course = get_record('course', 'fullname', $coursename);
    if ($course === false) {
        redirect('img/error.png');
    }
    $validdip = get_record('diplome_diploma', 'userid', $user->id, 'courseid', $course->id);
    $validra = get_valid_roleassign((int) $args[0], $course->id);
    if ($validra !== false && $validdip != false && file_exists($pathname) && !is_dir($pathname)) {
        send_file($pathname, $user->lastname . '_' . $user->firstname . '_' . $args[1], $lifetime);
    }
}
/// When path does not corespond -> use default instead
redirect('img/error.png');
         $booktext .= '<div class="chapter">';
         // Check if the chapter title is duplicated inside the content, and include it if not.
         if (!$chapter->subchapter and !strpos($chapter->content, "<h1")) {
             $booktext .= "<h1>" . $chapter->title . "</h1>\n";
         } else {
             if ($chapter->subchapter and !strpos($chapter->content, "<h2")) {
                 $booktext .= "<h2>" . $chapter->title . "</h2>\n";
             }
         }
         $booktext .= $chapter->content;
         $booktext .= booktool_wordimport_base64_images($context->id, 'chapter', $chapter->id);
         $booktext .= "</div>\n";
     }
     $booktext = booktool_wordimport_export($booktext);
     $filename = clean_filename($book->name) . '.doc';
     send_file($booktext, $filename, 10, 0, true, array('filename' => $filename));
     die;
 } else {
     if ($data = $mform->get_data()) {
         // A Word file has been uploaded, so process it.
         echo $OUTPUT->header();
         echo $OUTPUT->heading($book->name);
         echo $OUTPUT->heading(get_string('importchapters', 'booktool_wordimport'), 3);
         // Should the Word file split into subchapters on 'Heading 2' styles?
         $splitonsubheadings = property_exists($data, 'splitonsubheadings');
         // Get the uploaded Word file and save it to the file system.
         $fs = get_file_storage();
         $draftid = file_get_submitted_draft_itemid('importfile');
         if (!($files = $fs->get_area_files(context_user::instance($USER->id)->id, 'user', 'draft', $draftid, 'id DESC', false))) {
             redirect($PAGE->url);
         }
/**
 * Called by pluginfile.php to serve files related to the 'question' core
 * component and for files belonging to qtypes.
 *
 * For files that relate to questions in a question_attempt, then we delegate to
 * a function in the component that owns the attempt (for example in the quiz,
 * or in core question preview) to get necessary inforation.
 *
 * (Note that, at the moment, all question file areas relate to questions in
 * attempts, so the If at the start of the last paragraph is always true.)
 *
 * Does not return, either calls send_file_not_found(); or serves the file.
 *
 * @package  core_question
 * @category files
 * @param stdClass $course course settings object
 * @param stdClass $context context object
 * @param string $component the name of the component we are serving files for.
 * @param string $filearea the name of the file area.
 * @param array $args the remaining bits of the file path.
 * @param bool $forcedownload whether the user must be forced to download the file.
 * @param array $options additional options affecting the file serving
 */
function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options = array())
{
    global $DB, $CFG;
    // Special case, sending a question bank export.
    if ($filearea === 'export') {
        list($context, $course, $cm) = get_context_info_array($context->id);
        require_login($course, false, $cm);
        require_once $CFG->dirroot . '/question/editlib.php';
        $contexts = new question_edit_contexts($context);
        // check export capability
        $contexts->require_one_edit_tab_cap('export');
        $category_id = (int) array_shift($args);
        $format = array_shift($args);
        $cattofile = array_shift($args);
        $contexttofile = array_shift($args);
        $filename = array_shift($args);
        // load parent class for import/export
        require_once $CFG->dirroot . '/question/format.php';
        require_once $CFG->dirroot . '/question/editlib.php';
        require_once $CFG->dirroot . '/question/format/' . $format . '/format.php';
        $classname = 'qformat_' . $format;
        if (!class_exists($classname)) {
            send_file_not_found();
        }
        $qformat = new $classname();
        if (!($category = $DB->get_record('question_categories', array('id' => $category_id)))) {
            send_file_not_found();
        }
        $qformat->setCategory($category);
        $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
        $qformat->setCourse($course);
        if ($cattofile == 'withcategories') {
            $qformat->setCattofile(true);
        } else {
            $qformat->setCattofile(false);
        }
        if ($contexttofile == 'withcontexts') {
            $qformat->setContexttofile(true);
        } else {
            $qformat->setContexttofile(false);
        }
        if (!$qformat->exportpreprocess()) {
            send_file_not_found();
            print_error('exporterror', 'question', $thispageurl->out());
        }
        // export data to moodle file pool
        if (!($content = $qformat->exportprocess(true))) {
            send_file_not_found();
        }
        send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
    }
    // Normal case, a file belonging to a question.
    $qubaidorpreview = array_shift($args);
    // Two sub-cases: 1. A question being previewed outside an attempt/usage.
    if ($qubaidorpreview === 'preview') {
        $previewcontextid = (int) array_shift($args);
        $previewcomponent = array_shift($args);
        $questionid = (int) array_shift($args);
        $previewcontext = context_helper::instance_by_id($previewcontextid);
        $result = component_callback($previewcomponent, 'question_preview_pluginfile', array($previewcontext, $questionid, $context, $component, $filearea, $args, $forcedownload, $options), 'newcallbackmissing');
        if ($result === 'newcallbackmissing' && ($filearea = 'questiontext')) {
            // Fall back to the legacy callback for backwards compatibility.
            debugging("Component {$previewcomponent} does not define the expected " . "{$previewcomponent}_question_preview_pluginfile callback. Falling back to the deprecated " . "{$previewcomponent}_questiontext_preview_pluginfile callback.", DEBUG_DEVELOPER);
            component_callback($previewcomponent, 'questiontext_preview_pluginfile', array($previewcontext, $questionid, $args, $forcedownload, $options));
        }
        send_file_not_found();
    }
    // 2. A question being attempted in the normal way.
    $qubaid = (int) $qubaidorpreview;
    $slot = (int) array_shift($args);
    $module = $DB->get_field('question_usages', 'component', array('id' => $qubaid));
    if ($module === 'core_question_preview') {
        require_once $CFG->dirroot . '/question/previewlib.php';
        return question_preview_question_pluginfile($course, $context, $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
    } else {
        $dir = core_component::get_component_directory($module);
        if (!file_exists("{$dir}/lib.php")) {
            send_file_not_found();
        }
        include_once "{$dir}/lib.php";
        $filefunction = $module . '_question_pluginfile';
        if (function_exists($filefunction)) {
            $filefunction($course, $context, $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
        }
        // Okay, we're here so lets check for function without 'mod_'.
        if (strpos($module, 'mod_') === 0) {
            $filefunctionold = substr($module, 4) . '_question_pluginfile';
            if (function_exists($filefunctionold)) {
                $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
            }
        }
        send_file_not_found();
    }
}
Example #20
0
function poodllpluginfile($contextid, $component, $filearea, $itemid, $filepath, $filename)
{
    $fs = get_file_storage();
    $br = get_file_browser();
    $f = $fs->get_file($contextid, $component, $filearea, $itemid, $filepath, $filename);
    //if no file we just quit.
    if (!$f) {
        return;
    }
    //get permission info for this file: but it doesn't work oh no.....another moodle bug?
    /*
    	$thecontext = get_context_instance_by_id($contextid);
    	$fileinfo = $br->get_file_info($thecontext, $component,$filearea, $itemid, $filepath, $filename);	
    
    	//if we don't have permission to read, exit
    	if(!$fileinfo || !$fileinfo->is_readable()){echo "crap"; return;}
    */
    //send_stored_file also works: but we are using send file, for no reason really
    //send_stored_file($f, 0, 0, true); // download MUST be forced - security!
    $fcontent = $f->get_content();
    send_file($fcontent, $filename, 0, 0, true, true, "video/x-flv");
    return;
}
Example #21
0
}
$contextid = (int) array_shift($args);
$component = clean_param(array_shift($args), PARAM_SAFEDIR);
$filearea = clean_param(array_shift($args), PARAM_SAFEDIR);
list($context, $course, $cm) = get_context_info_array($contextid);
$fs = get_file_storage();
// If the file is a Flash file and that the user flash player is outdated return a flash upgrader MDL-20841
$mimetype = mimeinfo('type', $args[count($args) - 1]);
if (!empty($CFG->excludeoldflashclients) && $mimetype == 'application/x-shockwave-flash' && !empty($SESSION->flashversion)) {
    $userplayerversion = explode('.', $SESSION->flashversion);
    $requiredplayerversion = explode('.', $CFG->excludeoldflashclients);
    if ($userplayerversion[0] < $requiredplayerversion[0] || $userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] < $requiredplayerversion[1] || $userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] == $requiredplayerversion[1] && $userplayerversion[2] < $requiredplayerversion[2]) {
        $path = $CFG->dirroot . "/lib/flashdetect/flashupgrade.swf";
        // Alternate content asking user to upgrade Flash
        $filename = "flashupgrade.swf";
        send_file($path, $filename, O, 0, false, false, 'application/x-shockwave-flash');
        // Do not cache
    }
}
// ========================================================================================================================
if ($component === 'blog') {
    // Blog file serving
    if ($context->contextlevel != CONTEXT_SYSTEM) {
        send_file_not_found();
    }
    if ($filearea !== 'attachment' and $filearea !== 'post') {
        send_file_not_found();
    }
    if (empty($CFG->bloglevel)) {
        print_error('siteblogdisable', 'blog');
    }
function TexOutput($expression, $graphic = false)
{
    global $CFG;
    $output = '';
    $latex = new latex();
    // first check if it is likely to work at all
    $output .= "<h3>Checking executables</h3>\n";
    $executables_exist = true;
    if (is_file($CFG->filter_tex_pathlatex)) {
        $output .= "latex executable ({$CFG->filter_tex_pathlatex}) is readable<br />\n";
    } else {
        $executables_exist = false;
        $output .= "<b>Error:</b> latex executable ({$CFG->filter_tex_pathlatex}) is not readable<br />\n";
    }
    if (is_file($CFG->filter_tex_pathdvips)) {
        $output .= "dvips executable ({$CFG->filter_tex_pathdvips}) is readable<br />\n";
    } else {
        $executables_exist = false;
        $output .= "<b>Error:</b> dvips executable ({$CFG->filter_tex_pathdvips}) is not readable<br />\n";
    }
    if (is_file($CFG->filter_tex_pathconvert)) {
        $output .= "convert executable ({$CFG->filter_tex_pathconvert}) is readable<br />\n";
    } else {
        $executables_exist = false;
        $output .= "<b>Error:</b> convert executable ({$CFG->filter_tex_pathconvert}) is not readable<br />\n";
    }
    // knowing that it might work..
    $md5 = md5($expression);
    $output .= "<p>base filename for expression is '{$md5}'</p>\n";
    // temporary paths
    $tex = "{$latex->temp_dir}/{$md5}.tex";
    $dvi = "{$latex->temp_dir}/{$md5}.dvi";
    $ps = "{$latex->temp_dir}/{$md5}.ps";
    $img = "{$latex->temp_dir}/{$md5}.{$CFG->filter_tex_convertformat}";
    // put the expression as a file into the temp area
    $expression = html_entity_decode($expression);
    $output .= "<p>Processing TeX expression:</p><pre>{$expression}</pre>\n";
    $doc = $latex->construct_latex_document($expression);
    $fh = fopen($tex, 'w');
    fputs($fh, $doc);
    fclose($fh);
    // cd to temp dir
    chdir($latex->temp_dir);
    // step 1: latex command
    $cmd = "{$CFG->filter_tex_pathlatex} --interaction=nonstopmode {$tex}";
    $output .= execute($cmd);
    // step 2: dvips command
    $cmd = "{$CFG->filter_tex_pathdvips} -E {$dvi} -o {$ps}";
    $output .= execute($cmd);
    // step 3: convert command
    $cmd = "{$CFG->filter_tex_pathconvert} -density 240 -trim {$ps} {$img} ";
    $output .= execute($cmd);
    if (!$graphic) {
        echo $output;
    } else {
        if (file_exists($img)) {
            send_file($img, "{$md5}.{$CFG->filter_tex_convertformat}");
        } else {
            echo "Error creating image, see command execution output for more details.";
        }
    }
}
Example #23
0
<?php

// $Id: exportfile.php,v 1.11 2008/06/08 10:43:39 skodak Exp $
require_once "../../config.php";
require_once "lib.php";
// disable moodle specific debug messages
disable_debugging();
$id = required_param('id', PARAM_INT);
// Course Module ID
$l = optional_param('l', '', PARAM_ALPHANUM);
$cat = optional_param('cat', 0, PARAM_ALPHANUM);
if (!($cm = get_coursemodule_from_id('glossary', $id))) {
    print_error('invalidcoursemodule');
}
if (!($course = $DB->get_record("course", array("id" => $cm->course)))) {
    print_error('coursemisconf');
}
if (!($glossary = $DB->get_record("glossary", array("id" => $cm->instance)))) {
    print_error('invalidid', 'glossary');
}
require_login($course->id, false, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/glossary:export', $context);
$filename = clean_filename(strip_tags(format_string($glossary->name, true)) . '.xml');
$content = glossary_generate_export_file($glossary, $l, $cat);
send_file($content, $filename, 0, 0, true, true);
Example #24
0
    }
    echo html_writer::tag('div', $OUTPUT->render($button), array('style' => 'text-align:center'));
    echo $OUTPUT->footer($course);
    exit;
} else {
    // Output to pdf
    // No debugging here, sorry.
    $CFG->debugdisplay = 0;
    @ini_set('display_errors', '0');
    @ini_set('log_errors', '1');
    $filename = certificate_get_certificate_filename($certificate, $cm, $course) . '.pdf';
    require "{$CFG->dirroot}/mod/certificate/certificate_pdf_renderer.php";
    $cpr = new certificate_pdf_renderer($certificate, $course, $cm);
    $pdf = $cpr->get_pdf();
    // PDF contents are now in $file_contents as a string.
    $filecontents = $pdf->Output('', 'S');
    if ($certificate->savecert == 1) {
        certificate_save_pdf($filecontents, $certrecord->id, $filename, $context->id);
    }
    if ($certificate->delivery == 0) {
        // Open in browser.
        send_file($filecontents, $filename, 0, 0, true, false, 'application/pdf');
    } elseif ($certificate->delivery == 1) {
        // Force download.
        send_file($filecontents, $filename, 0, 0, true, true, 'application/pdf');
    } elseif ($certificate->delivery == 2) {
        certificate_email_student($course, $certificate, $certrecord, $context, $filecontents, $filename);
        // Open in browser after sending email.
        send_file($filecontents, $filename, 0, 0, true, false, 'application/pdf');
    }
}
Example #25
0
function rss_not_found()
{
    /// error, send some XML with error message
    global $lifetime, $filename;
    send_file(rss_geterrorxmlfile(), $filename, $lifetime, false, true);
}
Example #26
0
/**
 * Serves the page files.
 *
 * @package  mod_page
 * @category files
 * @param stdClass $course course object
 * @param stdClass $cm course module object
 * @param stdClass $context context object
 * @param string $filearea file area
 * @param array $args extra arguments
 * @param bool $forcedownload whether or not force download
 * @param array $options additional options affecting the file serving
 * @return bool false if file not found, does not return if found - just send the file
 */
function page_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
    global $CFG, $DB;
    require_once("$CFG->libdir/resourcelib.php");

    if ($context->contextlevel != CONTEXT_MODULE) {
        return false;
    }

    require_course_login($course, true, $cm);
    if (!has_capability('mod/page:view', $context)) {
        return false;
    }

    if ($filearea !== 'content') {
        // intro is handled automatically in pluginfile.php
        return false;
    }

    // $arg could be revision number or index.html
    $arg = array_shift($args);
    if ($arg == 'index.html' || $arg == 'index.htm') {
        // serve page content
        $filename = $arg;

        if (!$page = $DB->get_record('page', array('id'=>$cm->instance), '*', MUST_EXIST)) {
            return false;
        }

        // remove @@PLUGINFILE@@/
        $content = str_replace('@@PLUGINFILE@@/', '', $page->content);

        $formatoptions = new stdClass;
        $formatoptions->noclean = true;
        $formatoptions->overflowdiv = true;
        $formatoptions->context = $context;
        $content = format_text($content, $page->contentformat, $formatoptions);

        send_file($content, $filename, 0, 0, true, true);
    } else {
        $fs = get_file_storage();
        $relativepath = implode('/', $args);
        $fullpath = "/$context->id/mod_page/$filearea/0/$relativepath";
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            $page = $DB->get_record('page', array('id'=>$cm->instance), 'id, legacyfiles', MUST_EXIST);
            if ($page->legacyfiles != RESOURCELIB_LEGACYFILES_ACTIVE) {
                return false;
            }
            if (!$file = resourcelib_try_file_migration('/'.$relativepath, $cm->id, $cm->course, 'mod_page', 'content', 0)) {
                return false;
            }
            //file migrate - update flag
            $page->legacyfileslast = time();
            $DB->update_record('page', $page);
        }

        // finally send the file
        send_stored_file($file, 86400, 0, $forcedownload, $options);
    }
}
Example #27
0
/**
 * File serving.
 *
 * @param stdClass $course The course object.
 * @param stdClass $cm The cm object.
 * @param context $context The context object.
 * @param string $filearea The file area.
 * @param array $args List of arguments.
 * @param bool $forcedownload Whether or not to force the download of the file.
 * @param array $options Array of options.
 * @return void|false
 */
function core_admin_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $CFG;
    if (in_array($filearea, ['logo', 'logocompact'])) {
        $size = array_shift($args);
        // The path hides the size.
        $itemid = clean_param(array_shift($args), PARAM_INT);
        $filename = clean_param(array_shift($args), PARAM_FILE);
        $themerev = theme_get_revision();
        if ($themerev <= 0) {
            // Normalise to 0 as -1 doesn't place well with paths.
            $themerev = 0;
        }
        // Extract the requested width and height.
        $maxwidth = 0;
        $maxheight = 0;
        if (preg_match('/^\\d+x\\d+$/', $size)) {
            list($maxwidth, $maxheight) = explode('x', $size);
            $maxwidth = clean_param($maxwidth, PARAM_INT);
            $maxheight = clean_param($maxheight, PARAM_INT);
        }
        $lifetime = 0;
        if ($itemid > 0 && $themerev == $itemid) {
            // The itemid is $CFG->themerev, when 0 or less no caching. Also no caching when they don't match.
            $lifetime = DAYSECS * 60;
        }
        // Anyone, including guests and non-logged in users, can view the logos.
        $options = ['cacheability' => 'public'];
        // Check if we've got a cached file to return. When lifetime is 0 then we don't want to cached one.
        $candidate = $CFG->localcachedir . "/core_admin/{$themerev}/{$filearea}/{$maxwidth}x{$maxheight}/{$filename}";
        if (file_exists($candidate) && $lifetime > 0) {
            send_file($candidate, $filename, $lifetime, 0, false, false, '', false, $options);
        }
        // Find the original file.
        $fs = get_file_storage();
        $filepath = "/{$context->id}/core_admin/{$filearea}/0/{$filename}";
        if (!($file = $fs->get_file_by_hash(sha1($filepath)))) {
            send_file_not_found();
        }
        // No need for resizing, but if the file should be cached we save it so we can serve it fast next time.
        if (empty($maxwidth) && empty($maxheight)) {
            if ($lifetime) {
                file_safe_save_content($file->get_content(), $candidate);
            }
            send_stored_file($file, $lifetime, 0, false, $options);
        }
        // Proceed with the resizing.
        $filedata = $file->resize_image($maxwidth, $maxheight);
        if (!$filedata) {
            send_file_not_found();
        }
        // If we don't want to cached the file, serve now and quit.
        if (!$lifetime) {
            send_content_uncached($filedata, $filename);
        }
        // Save, serve and quit.
        file_safe_save_content($filedata, $candidate);
        send_file($candidate, $filename, $lifetime, 0, false, false, '', false, $options);
    }
    send_file_not_found();
}
Example #28
0
/**
 * Serves the glossary attachments. Implements needed access control ;-)
 *
 * @param object $course
 * @param object $cm
 * @param object $context
 * @param string $filearea
 * @param array $args
 * @param bool $forcedownload
 * @return bool false if file not found, does not return if found - justsend the file
 */
function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
    global $CFG, $DB;

    if ($context->contextlevel != CONTEXT_MODULE) {
        return false;
    }

    require_course_login($course, true, $cm);

    if ($filearea === 'attachment' or $filearea === 'entry') {
        $entryid = (int)array_shift($args);

        require_course_login($course, true, $cm);

        if (!$entry = $DB->get_record('glossary_entries', array('id'=>$entryid))) {
            return false;
        }

        if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
            return false;
        }

        if ($glossary->defaultapproval and !$entry->approved and !has_capability('mod/glossary:approve', $context)) {
            return false;
        }

        // this trickery here is because we need to support source glossary access

        if ($entry->glossaryid == $cm->instance) {
            $filecontext = $context;

        } else if ($entry->sourceglossaryid == $cm->instance) {
            if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) {
                return false;
            }
            $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id);

        } else {
            return false;
        }

        $relativepath = implode('/', $args);
        $fullpath = "/$filecontext->id/mod_glossary/$filearea/$entryid/$relativepath";

        $fs = get_file_storage();
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            return false;
        }

        // finally send the file
        send_stored_file($file, 0, 0, true); // download MUST be forced - security!

    } else if ($filearea === 'export') {
        require_login($course, false, $cm);
        require_capability('mod/glossary:export', $context);

        if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) {
            return false;
        }

        $cat = array_shift($args);
        $cat = clean_param($cat, PARAM_ALPHANUM);

        $filename = clean_filename(strip_tags(format_string($glossary->name)).'.xml');
        $content = glossary_generate_export_file($glossary, NULL, $cat);

        send_file($content, $filename, 0, 0, true, true);
    }

    return false;
}
Example #29
0
 function close()
 {
     global $CFG;
     require_once $CFG->libdir . '/filelib.php';
     $dir = 'temp/ods/' . time();
     make_upload_directory($dir);
     make_upload_directory($dir . '/META-INF');
     $dir = "{$CFG->dataroot}/{$dir}";
     $files = array();
     $handle = fopen("{$dir}/mimetype", 'w');
     fwrite($handle, get_ods_mimetype());
     $files[] = "{$dir}/mimetype";
     $handle = fopen("{$dir}/content.xml", 'w');
     fwrite($handle, get_ods_content($this->worksheets));
     $files[] = "{$dir}/content.xml";
     $handle = fopen("{$dir}/meta.xml", 'w');
     fwrite($handle, get_ods_meta());
     $files[] = "{$dir}/meta.xml";
     $handle = fopen("{$dir}/styles.xml", 'w');
     fwrite($handle, get_ods_styles());
     $files[] = "{$dir}/styles.xml";
     $handle = fopen("{$dir}/META-INF/manifest.xml", 'w');
     fwrite($handle, get_ods_manifest());
     $files[] = "{$dir}/META-INF";
     $filename = "{$dir}/result.ods";
     zip_files($files, $filename);
     $handle = fopen($filename, 'rb');
     $contents = fread($handle, filesize($filename));
     fclose($handle);
     remove_dir($dir);
     // cleanup the temp directory
     send_file($contents, $this->filename, 0, 0, true, true, 'application/vnd.oasis.opendocument.spreadsheet');
 }
Example #30
0
You can uncomment the following lines (minus the require) to use these as your defaults.
*/
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 80 * 1024 * 1024;
if (isset($_GET['type'])) {
    $type = $_GET['type'];
}
require 'api.php';
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
// Call handleUpload() with the name of the folder, relative to PHP's getcwd()
$result = $uploader->handleUpload('uploads/');
// If this is a file, let's upload it
if (file_exists($result)) {
    send_file($result, $type);
    $result = array('success' => true);
}
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
/******************************************/
/**
 * Interactions with API handled here
 *
 * @param $file_path
 */
function send_file($file_path, $type)
{
    $payload = array();
    $full_file_path = realpath($file_path);
    if (file_exists($full_file_path)) {