Example #1
0
/**
 * Serves the message 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 block_jmail_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload)
{
    global $SCRIPT;
    if ($context->contextlevel != CONTEXT_BLOCK) {
        //send_file_not_found();
    }
    require_course_login($course);
    $coursecontext = block_jmail_get_context(CONTEXT_COURSE, $course->id, MUST_EXIST);
    // The mailbox constructor does the permission validation
    if (!($mailbox = new block_jmail_mailbox($course, $coursecontext, $context))) {
        return;
    }
    $messageid = (int) array_shift($args);
    $message = block_jmail_message::get_from_id($messageid);
    // We check if we are the senders or the receivers
    if (!$message) {
        send_file_not_found();
    }
    $pendingaprobal = !$message->approved and has_capability('block/jmail:approvemessages', $context);
    if (!$message->is_mine() and !$pendingaprobal) {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $relativepath = implode('/', $args);
    $fullpath = "/{$context->id}/block_jmail/{$filearea}/{$messageid}/{$relativepath}";
    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
        send_file_not_found();
    }
    $forcedownload = true;
    send_stored_file($file, 60 * 60, 0, $forcedownload);
}
Example #2
0
/**
 * Serves the dataformview_tabular template files.
 *
 * @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 dataformview_tabular_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload)
{
    if (!in_array($filearea, dataformview_tabular_tabular::get_file_areas())) {
        return false;
    }
    if ($context->contextlevel == CONTEXT_MODULE) {
        require_course_login($course, true, $cm);
        $viewid = (int) array_shift($args);
        $dataformid = $cm->instance;
        // Confirm user access.
        $params = array('dataformid' => $dataformid, 'viewid' => $viewid);
        if (!mod_dataform\access\view_access::validate($params)) {
            return false;
        }
        $relativepath = implode('/', $args);
        $fullpath = "/{$context->id}/dataformview_tabular/{$filearea}/{$viewid}/{$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!
    }
    return false;
}
Example #3
0
/**
 * Form for editing HTML block instances.
 *
 * @copyright 2010 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @package   block_html
 * @category  files
 * @param stdClass $course course object
 * @param stdClass $birecord_or_cm block instance record
 * @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
 */
function block_html_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $SCRIPT;
    if ($context->contextlevel != CONTEXT_BLOCK) {
        send_file_not_found();
    }
    require_course_login($course);
    if ($filearea !== 'content') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $filename = array_pop($args);
    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
    if (!($file = $fs->get_file($context->id, 'block_html', 'content', 0, $filepath, $filename)) or $file->is_directory()) {
        send_file_not_found();
    }
    if ($parentcontext = get_context_instance_by_id($birecord_or_cm->parentcontextid)) {
        if ($parentcontext->contextlevel == CONTEXT_USER) {
            // force download on all personal pages including /my/
            //because we do not have reliable way to find out from where this is used
            $forcedownload = true;
        }
    } else {
        // weird, there should be parent context, better force dowload then
        $forcedownload = true;
    }
    session_get_instance()->write_close();
    send_stored_file($file, 60 * 60, 0, $forcedownload, $options);
}
/**
 * Form for editing Information Spot  block instances.
 *
 * @copyright 2014 Roberto Pinna
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @package   block_informationspot
 * @category  files
 * @param stdClass $course course object
 * @param stdClass $birecord_or_cm block instance record
 * @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
 */
function block_informationspot_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $DB, $CFG, $USER;
    if ($context->contextlevel != CONTEXT_BLOCK) {
        send_file_not_found();
    }
    // If block is in course context, then check if user has capability to access course.
    if ($context->get_course_context(false)) {
        require_course_login($course);
    } else {
        if ($CFG->forcelogin) {
            require_login();
        } else {
            // Get parent context and see if user have proper permission.
            $parentcontext = $context->get_parent_context();
            if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
                // Check if category is visible and user can view this category.
                $category = $DB->get_record('course_categories', array('id' => $parentcontext->instanceid), '*', MUST_EXIST);
                if (!$category->visible) {
                    require_capability('moodle/category:viewhiddencategories', $parentcontext);
                }
            } else {
                if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) {
                    // The block is in the context of a user, it is only visible to the user who it belongs to.
                    send_file_not_found();
                }
            }
            // At this point there is no way to check SYSTEM context, so ignoring it.
        }
    }
    if ($filearea != 'image') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $imageid = array_shift($args);
    $filename = array_pop($args);
    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
    if (!($file = $fs->get_file($context->id, 'block_informationspot', $filearea, $imageid, $filepath, $filename)) or $file->is_directory()) {
        send_file_not_found();
    }
    if ($parentcontext = context::instance_by_id($birecord_or_cm->parentcontextid, IGNORE_MISSING)) {
        if ($parentcontext->contextlevel == CONTEXT_USER) {
            // force download on all personal pages including /my/
            //because we do not have reliable way to find out from where this is used
            $forcedownload = true;
        }
    } else {
        // weird, there should be parent context, better force dowload then
        $forcedownload = true;
    }
    // NOTE: it woudl be nice to have file revisions here, for now rely on standard file lifetime,
    //       do not lower it because the files are dispalyed very often.
    \core\session\manager::write_close();
    send_stored_file($file, null, 0, $forcedownload, $options);
}
Example #5
0
/**
 * Form for editing HTML block instances.
 *
 * @copyright 2010 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @package   block_html
 * @category  files
 * @param stdClass $course course object
 * @param stdClass $birecord_or_cm block instance record
 * @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
 * @todo MDL-36050 improve capability check on stick blocks, so we can check user capability before sending images.
 */
function block_html_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options = array())
{
    global $DB, $CFG;
    if ($context->contextlevel != CONTEXT_BLOCK) {
        send_file_not_found();
    }
    // If block is in course context, then check if user has capability to access course.
    if ($context->get_course_context(false)) {
        require_course_login($course);
    } else {
        if ($CFG->forcelogin) {
            require_login();
        } else {
            // Get parent context and see if user have proper permission.
            $parentcontext = $context->get_parent_context();
            if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
                // Check if category is visible and user can view this category.
                $category = $DB->get_record('course_categories', array('id' => $parentcontext->instanceid), '*', MUST_EXIST);
                if (!$category->visible) {
                    require_capability('moodle/category:viewhiddencategories', $parentcontext);
                }
            }
            // At this point there is no way to check SYSTEM or USER context, so ignoring it.
        }
    }
    if ($filearea !== 'content') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $filename = array_pop($args);
    $filepath = $args ? '/' . implode('/', $args) . '/' : '/';
    if (!($file = $fs->get_file($context->id, 'block_html', 'content', 0, $filepath, $filename)) or $file->is_directory()) {
        send_file_not_found();
    }
    if ($parentcontext = get_context_instance_by_id($birecord_or_cm->parentcontextid)) {
        if ($parentcontext->contextlevel == CONTEXT_USER) {
            // force download on all personal pages including /my/
            //because we do not have reliable way to find out from where this is used
            $forcedownload = true;
        }
    } else {
        // weird, there should be parent context, better force dowload then
        $forcedownload = true;
    }
    session_get_instance()->write_close();
    send_stored_file($file, 60 * 60, 0, $forcedownload, $options);
}
Example #6
0
function block_navbuttons_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload)
{
    if ($context->contextlevel != CONTEXT_COURSE) {
        send_file_not_found();
    }
    require_course_login($course);
    if ($filearea !== 'icons') {
        send_file_not_found();
    }
    $fs = get_file_storage();
    $filename = $args[1];
    $iconid = $args[0];
    if (!($file = $fs->get_file($context->id, 'block_navbuttons', 'icons', $iconid, '/', $filename)) or $file->is_directory()) {
        send_file_not_found();
    }
    send_stored_file($file, 60 * 60, 0, $forcedownload);
}
Example #7
0
/**
 * Serves the data 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 data_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 === 'content') {
        $contentid = (int)array_shift($args);

        if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
            return false;
        }

        if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
            return false;
        }

        if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
            return false;
        }

        if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
            return false;
        }

        if ($data->id != $cm->instance) {
            // hacker attempt - context does not match the contentid
            return false;
        }

        //check if approved
        if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
            return false;
        }

        // group access
        if ($record->groupid) {
            $groupmode = groups_get_activity_groupmode($cm, $course);
            if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                if (!groups_is_member($record->groupid)) {
                    return false;
                }
            }
        }

        $fieldobj = data_get_field($field, $data, $cm);

        $relativepath = implode('/', $args);
        $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";

        if (!$fieldobj->file_ok($relativepath)) {
            return false;
        }

        $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!
    }

    return false;
}
Example #8
0
/**
 * Serves the folder files.
 *
 * @package  mod_folder
 * @category files
 * @param stdClass $course course object
 * @param stdClass $cm course module
 * @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 folder_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 (!has_capability('mod/folder:view', $context)) {
        return false;
    }
    if ($filearea !== 'content') {
        // intro is handled automatically in pluginfile.php
        return false;
    }
    array_shift($args);
    // ignore revision - designed to prevent caching problems only
    $fs = get_file_storage();
    $relativepath = implode('/', $args);
    $fullpath = "/{$context->id}/mod_folder/content/0/{$relativepath}";
    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
        return false;
    }
    // finally send the file
    // for folder module, we force download file all the time
    send_stored_file($file, 0, 0, true, $options);
}
 /**
  * Initialise the navigation given the type and id for the branch to expand.
  *
  * @return array An array of the expandable nodes
  */
 public function initialise()
 {
     global $CFG, $DB, $SITE;
     if ($this->initialised || during_initial_install()) {
         return $this->expandable;
     }
     $this->initialised = true;
     $this->rootnodes = array();
     $this->rootnodes['site'] = $this->add_course($SITE);
     $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
     // Branchtype will be one of navigation_node::TYPE_*
     switch ($this->branchtype) {
         case self::TYPE_CATEGORY:
             $this->load_category($this->instanceid);
             break;
         case self::TYPE_COURSE:
             $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
             require_course_login($course, true, null, false, true);
             $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
             $coursenode = $this->add_course($course);
             $this->add_course_essentials($coursenode, $course);
             if ($this->format_display_course_content($course->format)) {
                 $this->load_course_sections($course, $coursenode);
             }
             break;
         case self::TYPE_SECTION:
             $sql = 'SELECT c.*, cs.section AS sectionnumber
                     FROM {course} c
                     LEFT JOIN {course_sections} cs ON cs.course = c.id
                     WHERE cs.id = ?';
             $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
             require_course_login($course, true, null, false, true);
             $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id));
             $coursenode = $this->add_course($course);
             $this->add_course_essentials($coursenode, $course);
             $sections = $this->load_course_sections($course, $coursenode);
             list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
             $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, $activities);
             break;
         case self::TYPE_ACTIVITY:
             $sql = "SELECT c.*\n                          FROM {course} c\n                          JOIN {course_modules} cm ON cm.course = c.id\n                         WHERE cm.id = :cmid";
             $params = array('cmid' => $this->instanceid);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             $modinfo = get_fast_modinfo($course);
             $cm = $modinfo->get_cm($this->instanceid);
             require_course_login($course, true, $cm, false, true);
             $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id));
             $coursenode = $this->load_course($course);
             if ($course->id == $SITE->id) {
                 $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
             } else {
                 $sections = $this->load_course_sections($course, $coursenode);
                 list($sectionarray, $activities) = $this->generate_sections_and_activities($course);
                 $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, $activities);
                 $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]);
             }
             break;
         default:
             throw new Exception('Unknown type');
             return $this->expandable;
     }
     if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
         $this->load_for_user(null, true);
     }
     $this->find_expandable($this->expandable);
     return $this->expandable;
 }
Example #10
0
 /**
  * Initialise the navigation given the type and id for the branch to expand.
  *
  * @return array An array of the expandable nodes
  */
 public function initialise()
 {
     global $DB, $SITE;
     if ($this->initialised || during_initial_install()) {
         return $this->expandable;
     }
     $this->initialised = true;
     $this->rootnodes = array();
     $this->rootnodes['site'] = $this->add_course($SITE);
     $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
     $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
     // The courses branch is always displayed, and is always expandable (although may be empty).
     // This mimicks what is done during {@link global_navigation::initialise()}.
     $this->rootnodes['courses']->isexpandable = true;
     // Branchtype will be one of navigation_node::TYPE_*
     switch ($this->branchtype) {
         case 0:
             if ($this->instanceid === 'mycourses') {
                 $this->load_courses_enrolled();
             } else {
                 if ($this->instanceid === 'courses') {
                     $this->load_courses_other();
                 }
             }
             break;
         case self::TYPE_CATEGORY:
             $this->load_category($this->instanceid);
             break;
         case self::TYPE_MY_CATEGORY:
             $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
             break;
         case self::TYPE_COURSE:
             $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
             if (!can_access_course($course, null, '', true)) {
                 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
                 // add the course node and break. This leads to an empty node.
                 $this->add_course($course);
                 break;
             }
             require_course_login($course, true, null, false, true);
             $this->page->set_context(context_course::instance($course->id));
             $coursenode = $this->add_course($course);
             $this->add_course_essentials($coursenode, $course);
             $this->load_course_sections($course, $coursenode);
             break;
         case self::TYPE_SECTION:
             $sql = 'SELECT c.*, cs.section AS sectionnumber
                     FROM {course} c
                     LEFT JOIN {course_sections} cs ON cs.course = c.id
                     WHERE cs.id = ?';
             $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
             require_course_login($course, true, null, false, true);
             $this->page->set_context(context_course::instance($course->id));
             $coursenode = $this->add_course($course);
             $this->add_course_essentials($coursenode, $course);
             $this->load_course_sections($course, $coursenode, $course->sectionnumber);
             break;
         case self::TYPE_ACTIVITY:
             $sql = "SELECT c.*\n                          FROM {course} c\n                          JOIN {course_modules} cm ON cm.course = c.id\n                         WHERE cm.id = :cmid";
             $params = array('cmid' => $this->instanceid);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             $modinfo = get_fast_modinfo($course);
             $cm = $modinfo->get_cm($this->instanceid);
             require_course_login($course, true, $cm, false, true);
             $this->page->set_context(context_module::instance($cm->id));
             $coursenode = $this->load_course($course);
             $this->load_course_sections($course, $coursenode, null, $cm);
             $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
             if ($activitynode) {
                 $modulenode = $this->load_activity($cm, $course, $activitynode);
             }
             break;
         default:
             throw new Exception('Unknown type');
             return $this->expandable;
     }
     if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
         $this->load_for_user(null, true);
     }
     $this->find_expandable($this->expandable);
     return $this->expandable;
 }
Example #11
0
        require_login($course, true);
    } else {
        require_login($course, true, $cm);
    }
} else {
    if ($course->id == SITEID) {
        require_course_login($course, true);
    } else {
        require_course_login($course, true, $cm);
    }
}

//check whether the given courseid exists
if ($courseid AND $courseid != SITEID) {
    if ($course2 = $DB->get_record('course', array('id'=>$courseid))) {
        require_course_login($course2); //this overwrites the object $course :-(
        $course = $DB->get_record("course", array("id"=>$cm->course)); // the workaround
    } else {
        print_error('invalidcourseid');
    }
}

if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
    add_to_log($course->id, 'feedback', 'view', 'view.php?id='.$cm->id, $feedback->id, $cm->id);
}

/// Print the page header
$strfeedbacks = get_string("modulenameplural", "feedback");
$strfeedback  = get_string("modulename", "feedback");

if ($course->id == SITEID) {
Example #12
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;
    }
    $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 #13
0
/**
 * Serves the resource files.
 * @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 - just send the file
 */
function resource_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
    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/resource:view', $context)) {
        return false;
    }

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

    array_shift($args); // ignore revision - designed to prevent caching problems only

    $fs = get_file_storage();
    $relativepath = implode('/', $args);
    $fullpath = rtrim("/$context->id/mod_resource/$filearea/0/$relativepath", '/');
    do {
        if (!$file = $fs->get_file_by_hash(sha1($fullpath))) {
            if ($fs->get_file_by_hash(sha1("$fullpath/."))) {
                if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.htm"))) {
                    break;
                }
                if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.html"))) {
                    break;
                }
                if ($file = $fs->get_file_by_hash(sha1("$fullpath/Default.htm"))) {
                    break;
                }
            }
            $resource = $DB->get_record('resource', array('id'=>$cm->instance), 'id, legacyfiles', MUST_EXIST);
            if ($resource->legacyfiles != RESOURCELIB_LEGACYFILES_ACTIVE) {
                return false;
            }
            if (!$file = resourcelib_try_file_migration('/'.$relativepath, $cm->id, $cm->course, 'mod_resource', 'content', 0)) {
                return false;
            }
            // file migrate - update flag
            $resource->legacyfileslast = time();
            $DB->update_record('resource', $resource);
        }
    } while (false);

    // should we apply filters?
    $mimetype = $file->get_mimetype();
    if ($mimetype === 'text/html' or $mimetype === 'text/plain') {
        $filter = $DB->get_field('resource', 'filterfiles', array('id'=>$cm->instance));
        $CFG->embeddedsoforcelinktarget = true;
    } else {
        $filter = 0;
    }

    // finally send the file
    send_stored_file($file, 86400, $filter, $forcedownload);
}
Example #14
0
require_once "{$CFG->libdir}/pdflib.php";
// Retrieve any variables that are passed
$id = required_param('id', PARAM_INT);
// Course Module ID
$action = optional_param('action', '', PARAM_ALPHA);
if (!($cm = get_coursemodule_from_id('iomadcertificate', $id))) {
    print_error('Course Module ID was incorrect');
}
if (!($course = $DB->get_record('course', array('id' => $cm->course)))) {
    print_error('course is misconfigured');
}
if (!($iomadcertificate = $DB->get_record('iomadcertificate', array('id' => $cm->instance)))) {
    print_error('course module is incorrect');
}
// Requires a course login
require_course_login($course->id, true, $cm);
// Check the capabilities
$context = context_module::instance($cm->id);
require_capability('mod/iomadcertificate:view', $context);
// Initialize $PAGE, compute blocks
$PAGE->set_url('/mod/iomadcertificate/review.php', array('id' => $cm->id));
$PAGE->set_context($context);
$PAGE->set_cm($cm);
$PAGE->set_title(format_string($iomadcertificate->name));
$PAGE->set_heading(format_string($course->fullname));
// Get previous cert record
if (!($certrecord = $DB->get_record('iomadcertificate_issues', array('userid' => $USER->id, 'iomadcertificateid' => $iomadcertificate->id)))) {
    notice(get_string('noiomadcertificatesissued', 'iomadcertificate'), "{$CFG->wwwroot}/course/view.php?id={$course->id}");
    die;
}
// Load the specific iomadcertificatetype
Example #15
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);
    }
}
 /**
  * Check that the user has permission to view this module, and check if they can edit it too.
  */
 function check_permission()
 {
     // Make sure the user is logged-in
     require_course_login($this->course, true, $this->cm);
     add_to_log($this->course->id, 'sloodle', 'view sloodle module', "view.php?id={$this->cm->id}", "{$this->sloodle->id}", $this->cm->id);
     // Check for permissions
     $this->module_context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
     $this->course_context = get_context_instance(CONTEXT_COURSE, $this->course->id);
     if (has_capability('moodle/course:manageactivities', $this->module_context)) {
         $this->canedit = true;
     }
     // If the module is hidden, then can the user still view it?
     if (empty($this->cm->visible) && !has_capability('moodle/course:viewhiddenactivities', $this->module_context)) {
         notice(get_string('activityiscurrentlyhidden'));
     }
 }
Example #17
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 #18
0
<?php

#################################################################################
## This versin is not present in any Moodle CVS and was generated from:
##    $Id: dlg_ins_dragmath.php,v 1.2.4.1 2008/05/14 16:04:28 net-buoy Exp $
## to accomodate changes made in DragMath 0.7.8.1 and relocation of DragMath
## for Moodle 2 purposes to /lib/DragMath.
## In Moodle 2 this file becomes dragmath.php and is located in
##   /lib/editor/tinymce/plugins/dragmath
## while DragMath itself is located in
##   /lib/DragMath
##
#################################################################################
require "../../../../config.php";
$id = optional_param('id', SITEID, PARAM_INT);
require_course_login($id);
$urlforcodebase = $CFG->wwwroot . '/lib/DragMath/applet/';
$drlang = str_replace('_utf8', '', current_language());
// use more standard language codes
$drlangmapping = array('cs' => 'cz', 'pt_br' => 'pt-br');
// fix non-standard lang names
if (array_key_exists($drlang, $drlangmapping)) {
    $drlang = $drlangmapping[$drlang];
}
if (!file_exists("{$CFG->dirroot}/lib/dragmath/applet/lang/{$drlang}.xml")) {
    $drlang = 'en';
}
@header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Example #19
0
/**
 * Serves the forum 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 forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
    global $CFG, $DB;

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

    require_course_login($course, true, $cm);

    $fileareas = array('attachment', 'post');
    if (!in_array($filearea, $fileareas)) {
        return false;
    }

    $postid = (int)array_shift($args);

    if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
        return false;
    }

    if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
        return false;
    }

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

    $fs = get_file_storage();
    $relativepath = implode('/', $args);
    $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
        return false;
    }

    // Make sure groups allow this user to see this file
    if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {   // Groups are being used
        if (!groups_group_exists($discussion->groupid)) { // Can't find group
            return false;                           // Be safe and don't send it to anyone
        }

        if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
            // do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
            return false;
        }
    }

    // Make sure we're allowed to see it...
    if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
        return false;
    }


    // finally send the file
    send_stored_file($file, 0, 0, true); // download MUST be forced - security!
}
Example #20
0
/**
 * Make sure user is logged in as required in this context.
 */
function require_login_in_context($contextorid = null)
{
    if (!is_object($contextorid)) {
        $context = get_context_instance_by_id($contextorid);
    } else {
        $context = $contextorid;
    }
    if ($context && $context->contextlevel == CONTEXT_COURSE) {
        require_login($context->instanceid);
    } else {
        if ($context && $context->contextlevel == CONTEXT_MODULE) {
            if ($cm = get_record('course_modules', 'id', $context->instanceid)) {
                if (!($course = get_record('course', 'id', $cm->course))) {
                    error('Incorrect course.');
                }
                require_course_login($course, true, $cm);
            } else {
                error('Incorrect course module id.');
            }
        } else {
            if ($context && $context->contextlevel == CONTEXT_SYSTEM) {
                if (!empty($CFG->forcelogin)) {
                    require_login();
                }
            } else {
                require_login();
            }
        }
    }
}
Example #21
0
/**
 * Serves the files included in feedback items like label. 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 feedback_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload)
{
    global $CFG, $DB;
    require_login($course, false, $cm);
    $itemid = (int) array_shift($args);
    require_course_login($course, true, $cm);
    if (!($item = $DB->get_record('feedback_item', array('id' => $itemid)))) {
        return false;
    }
    if (!has_capability('mod/feedback:view', $context)) {
        return false;
    }
    if ($context->contextlevel == CONTEXT_MODULE) {
        if ($filearea !== 'item') {
            return false;
        }
        if ($item->feedback == $cm->instance) {
            $filecontext = $context;
        } else {
            return false;
        }
    }
    if ($context->contextlevel == CONTEXT_COURSE) {
        if ($filearea !== 'template') {
            return false;
        }
    }
    $relativepath = implode('/', $args);
    $fullpath = "/{$context->id}/mod_feedback/{$filearea}/{$itemid}/{$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!
    return false;
}
Example #22
0
/**
 * Serves the forum attachments. Implements needed access control ;-)
 *
 * @package  mod_forum
 * @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 - justsend the file
 */
function forum_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);

    $areas = forum_get_file_areas($course, $cm, $context);

    // filearea must contain a real area
    if (!isset($areas[$filearea])) {
        return false;
    }

    $postid = (int)array_shift($args);

    if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
        return false;
    }

    if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
        return false;
    }

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

    $fs = get_file_storage();
    $relativepath = implode('/', $args);
    $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
        return false;
    }

    // Make sure groups allow this user to see this file
    if ($discussion->groupid > 0) {
        $groupmode = groups_get_activity_groupmode($cm, $course);
        if ($groupmode == SEPARATEGROUPS) {
            if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
                return false;
            }
        }
    }

    // Make sure we're allowed to see it...
    if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
        return false;
    }

    // finally send the file
    send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
}
 * */
require_once "../../config.php";
require_once "locallib.php";
require_once 'importexcel_form.php';
$id = required_param('id', PARAM_INT);
// Course Module ID
$url = new moodle_url('/mod/booking/importexcel.php', array('id' => $id));
$urlRedirect = new moodle_url('/mod/booking/view.php', array('id' => $id));
$PAGE->set_url($url);
if (!($cm = get_coursemodule_from_id('booking', $id))) {
    print_error("Course Module ID was incorrect");
}
if (!($course = $DB->get_record("course", array("id" => $cm->course)))) {
    print_error('coursemisconf');
}
require_course_login($course, false, $cm);
$groupmode = groups_get_activity_groupmode($cm);
if (!($booking = booking_get_booking($cm, ''))) {
    error("Course module is incorrect");
}
if (!($context = context_module::instance($cm->id))) {
    print_error('badcontext');
}
require_capability('mod/booking:updatebooking', $context);
$PAGE->navbar->add(get_string("importexceltitle", "booking"));
$PAGE->set_title(format_string($booking->name));
$PAGE->set_heading($course->fullname);
$PAGE->set_pagelayout('standard');
$mform = new importexcel_form($url);
//Form processing and displaying is done here
if ($mform->is_cancelled()) {
$url = new moodle_url('/calendar/managesubscriptions.php');
if ($courseid != SITEID) {
    $url->param('course', $courseid);
}
navigation_node::override_active_url(new moodle_url('/calendar/view.php', array('view' => 'month')));
$PAGE->set_url($url);
$PAGE->set_pagelayout('standard');
$PAGE->navbar->add(get_string('managesubscriptions', 'calendar'));
if ($courseid != SITEID && !empty($courseid)) {
    $course = $DB->get_record('course', array('id' => $courseid));
    $courses = array($course->id => $course);
} else {
    $course = get_site();
    $courses = calendar_get_default_courses();
}
require_course_login($course);
if (!calendar_user_can_add_event($course)) {
    print_error('errorcannotimport', 'calendar');
}
$form = new calendar_addsubscription_form(null);
$form->set_data(array('course' => $course->id));
$importresults = '';
$formdata = $form->get_data();
if (!empty($formdata)) {
    require_sesskey();
    // Must have sesskey for all actions.
    $subscriptionid = calendar_add_subscription($formdata);
    if ($formdata->importfrom == CALENDAR_IMPORT_FROM_FILE) {
        // Blank the URL if it's a file import.
        $formdata->url = '';
        $calendar = $form->get_file_content('importfile');
Example #25
0
/**
 * Serves the questionnaire 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 questionnaire_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload)
{
    global $DB;
    if ($context->contextlevel != CONTEXT_MODULE) {
        return false;
    }
    require_course_login($course, true, $cm);
    $fileareas = array('intro', 'info', 'thankbody', 'question');
    if (!in_array($filearea, $fileareas)) {
        return false;
    }
    $componentid = (int) array_shift($args);
    if ($filearea != 'question') {
        if (!($survey = $DB->get_record('questionnaire_survey', array('id' => $componentid)))) {
            return false;
        }
    } else {
        if (!($question = $DB->get_record('questionnaire_question', array('id' => $componentid)))) {
            return false;
        }
    }
    if (!($questionnaire = $DB->get_record('questionnaire', array('id' => $cm->instance)))) {
        return false;
    }
    $fs = get_file_storage();
    $relativepath = implode('/', $args);
    $fullpath = "/{$context->id}/mod_questionnaire/{$filearea}/{$componentid}/{$relativepath}";
    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!
}
Example #26
0
/**
 * Serves the files from the content file areas
 *
 * @package mod_content
 * @category files
 *
 * @param stdClass $course the course object
 * @param stdClass $cm the course module object
 * @param stdClass $context the content's context
 * @param string $filearea the name of the file area
 * @param array $args extra arguments (itemid, path)
 * @param bool $forcedownload whether or not force download
 * @param array $options additional options affecting the file serving
 */
function content_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);
    $itemid = 0;
    switch ($filearea) {
        case 'page':
        case 'bgpage':
            $pageid = (int) array_shift($args);
            $itemid = $pageid;
            if (!($page = $DB->get_record('content_pages', array('id' => $pageid)))) {
                return false;
            }
            break;
        case 'content':
            $itemid = 0;
            break;
        default:
            return false;
            break;
    }
    if (!($content = $DB->get_record('content', array('id' => $cm->instance)))) {
        return false;
    }
    $relativepath = implode('/', $args);
    $fullpath = "/{$context->id}/mod_content/{$filearea}/{$itemid}/{$relativepath}";
    $fs = get_file_storage();
    if (!($file = $fs->get_file_by_hash(sha1($fullpath))) or $file->is_directory()) {
        return false;
    }
    // Nasty hack because we do not have fSile revisions in content yet.
    $lifetime = $CFG->filelifetime;
    if ($lifetime > 60 * 10) {
        $lifetime = 60 * 10;
    }
    send_stored_file($file, 0, 0, true, $options);
    // download MUST be forced - security!
    // finally send the file
    return false;
}
Example #27
0
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * This page lists all the instances of book in a particular course
 *
 * @package    mod_book
 * @copyright  2004-2011 Petr Skoda {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require dirname(__FILE__) . '/../../config.php';
require_once dirname(__FILE__) . '/locallib.php';
$id = required_param('id', PARAM_INT);
// Course ID.
$course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST);
unset($id);
require_course_login($course, true);
$PAGE->set_pagelayout('incourse');
// Get all required strings
$strbooks = get_string('modulenameplural', 'mod_book');
$strbook = get_string('modulename', 'mod_book');
$strname = get_string('name');
$strintro = get_string('moduleintro');
$strlastmodified = get_string('lastmodified');
$PAGE->set_url('/mod/book/index.php', array('id' => $course->id));
$PAGE->set_title($course->shortname . ': ' . $strbooks);
$PAGE->set_heading($course->fullname);
$PAGE->navbar->add($strbooks);
echo $OUTPUT->header();
\mod_book\event\course_module_instance_list_viewed::create_from_course($course)->trigger();
// Get all the appropriate data
if (!($books = get_all_instances_in_course('book', $course))) {
Example #28
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();
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #29
0
        if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
            $buttontext = update_module_button($cm->id, $course->id, $strforum);
        } else {
            $cm->id = 0;
            $cm->visible = 1;
            $cm->course = $course->id;
            $buttontext = "";
        }
    } else {
        error('Must specify a course module or a forum ID');
    }
}
if (!$buttontext) {
    $buttontext = forum_search_form($course, $search);
}
require_course_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
/// Print header.
$navigation = build_navigation('', $cm);
print_header_simple(format_string($forum->name), "", $navigation, "", "", true, $buttontext, user_login_string($course) . '<hr style="width:95%">' . navmenu($course, $cm));
/// Some capability checks.
if (empty($cm->visible) and !has_capability('moodle/course:viewhiddenactivities', $context)) {
    notice(get_string("activityiscurrentlyhidden"));
}
if (!has_capability('mod/forum:viewdiscussion', $context)) {
    notice(get_string('noviewdiscussionspermission', 'forum'));
}
/// find out current groups mode
groups_print_activity_menu($cm, 'view.php?id=' . $cm->id);
$currentgroup = groups_get_activity_group($cm);
$groupmode = groups_get_activity_groupmode($cm);
Example #30
0
/**
 * Serves the facetoface and sessions details.
 *
 * @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 facetoface_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
    global $DB;

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

    require_course_login($course, true, $cm);

    if ($filearea !== 'session') {
        return false;
    }

    $sessionid = (int)array_shift($args);

    if (!$session = $DB->get_record('facetoface_sessions', array('id' => $sessionid))) {
        return false;
    }

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

    $fs = get_file_storage();
    $relativepath = implode('/', $args);
    $fullpath = "/$context->id/mod_facetoface/$filearea/$sessionid/$relativepath";
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
        return false;
    }

    // finally send the file
    send_stored_file($file, 360, 0, $forcedownload, $options);
}