/**
  * course_action_section_highlight constructor.
  * @param stdClass $course
  * @param stdClass $section - Note this is the section we want to affect via the url param.
  * @param bool $onsectionpage
  */
 public function __construct($course, $section, $onsectionpage = false)
 {
     if ($onsectionpage) {
         $baseurl = course_get_url($course, $section->section);
     } else {
         $baseurl = course_get_url($course);
     }
     $baseurl->param('sesskey', sesskey());
     $coursecontext = context_course::instance($course->id);
     $isstealth = isset($course->numsections) && $section->section > $course->numsections;
     if ($course->format === 'topics') {
         if (!$isstealth && has_capability('moodle/course:setcurrentsection', $coursecontext)) {
             $url = clone $baseurl;
             $marker = optional_param('marker', '', PARAM_INT);
             $marker = $marker === '' ? $course->marker : $marker;
             // Note if the new target section is 0 then it means the requested action is to have no current section
             // highlighted.
             if ($marker == $section->section || $section->section === 0) {
                 // Show the lightbulb.
                 $this->title = get_string('markedthistopic');
                 $url->param('marker', 0);
                 $this->url = $url;
                 $this->class .= ' snap-marked';
             } else {
                 $this->title = get_string('markthistopic');
                 $url->param('marker', $section->section);
                 $this->url = $url;
                 $this->class .= ' snap-marker';
             }
         }
     }
 }
Exemple #2
0
 /**
  * Render a series of section links.
  *
  * @param stdClass $course The course we are rendering for.
  * @param array $sections An array of section objects to render.
  * @param bool|int The section to provide a jump to link for.
  * @return string The HTML to display.
  */
 public function render_section_links(stdClass $course, array $sections, $jumptosection = false)
 {
     $html = html_writer::start_tag('ol', array('class' => 'inline-list'));
     foreach ($sections as $section) {
         $attributes = array();
         if (!$section->visible) {
             $attributes['class'] = 'dimmed';
         }
         $html .= html_writer::start_tag('li');
         $sectiontext = $section->section;
         if ($section->highlight) {
             $sectiontext = html_writer::tag('strong', $sectiontext);
         }
         $html .= html_writer::link(course_get_url($course, $section->section), $sectiontext, $attributes);
         $html .= html_writer::end_tag('li') . ' ';
     }
     $html .= html_writer::end_tag('ol');
     if ($jumptosection && isset($sections[$jumptosection])) {
         if ($course->format == 'weeks') {
             $linktext = new lang_string('jumptocurrentweek', 'block_section_links');
         } else {
             if ($course->format == 'topics') {
                 $linktext = new lang_string('jumptocurrenttopic', 'block_section_links');
             }
         }
         $attributes = array();
         if (!$sections[$jumptosection]->visible) {
             $attributes['class'] = 'dimmed';
         }
         $html .= html_writer::link(course_get_url($course, $jumptosection), $linktext, $attributes);
     }
     return $html;
 }
 public function __construct($course, $section, $onsectionpage = false)
 {
     if ($onsectionpage) {
         $baseurl = course_get_url($course, $section->section);
     } else {
         $baseurl = course_get_url($course);
     }
     $baseurl->param('sesskey', sesskey());
     $coursecontext = context_course::instance($course->id);
     $isstealth = isset($course->numsections) && $section->section > $course->numsections;
     $url = clone $baseurl;
     if (!$isstealth && has_capability('moodle/course:sectionvisibility', $coursecontext)) {
         if ($section->visible) {
             // Show the hide/show eye.
             $this->title = get_string('hidefromothers', 'format_' . $course->format);
             $url->param('hide', $section->section);
             $this->url = $url;
             $this->class .= ' snap-hide';
         } else {
             $this->title = get_string('showfromothers', 'format_' . $course->format);
             $url->param('show', $section->section);
             $this->url = $url;
             $this->class .= ' snap-show';
         }
     }
 }
 /**
  * Generate the edit controls of a section
  *
  * @param stdClass $course The course entry from DB
  * @param stdClass $section The course_section entry from DB
  * @param bool $onsectionpage true if being printed on a section page
  * @return array of links with edit controls
  */
 protected function section_edit_controls($course, $section, $onsectionpage = false)
 {
     global $PAGE;
     if (!$PAGE->user_is_editing()) {
         return array();
     }
     $coursecontext = context_course::instance($course->id);
     if ($onsectionpage) {
         $url = course_get_url($course, $section->section);
     } else {
         $url = course_get_url($course);
     }
     $url->param('sesskey', sesskey());
     $controls = array();
     if (has_capability('moodle/course:setcurrentsection', $coursecontext)) {
         if ($course->marker == $section->section) {
             // Show the "light globe" on/off.
             $url->param('marker', 0);
             $controls[] = html_writer::link($url, html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/marked'), 'class' => 'icon ', 'alt' => get_string('markedthistopic'))), array('title' => get_string('markedthistopic'), 'class' => 'editing_highlight'));
         } else {
             $url->param('marker', $section->section);
             $controls[] = html_writer::link($url, html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/marker'), 'class' => 'icon', 'alt' => get_string('markthistopic'))), array('title' => get_string('markthistopic'), 'class' => 'editing_highlight'));
         }
     }
     return array_merge($controls, parent::section_edit_controls($course, $section, $onsectionpage));
 }
 public function get_nav_links($course, $sections, $sectionno)
 {
     // FIXME: This is really evil and should by using the navigation API.
     $course = \course_get_format($course)->get_course();
     $left = 'left';
     $right = 'right';
     if (\right_to_left()) {
         $temp = $left;
         $left = $right;
         $right = $temp;
     }
     $previousarrow = '<i class="fa fa-chevron-circle-' . $left . '"></i>';
     $nextarrow = '<i class="fa fa-chevron-circle-' . $right . '"></i>';
     $canviewhidden = \has_capability('moodle/course:viewhiddensections', \context_course::instance($course->id)) or !$course->hiddensections;
     $links = array('previous' => '', 'next' => '');
     $back = $sectionno - 1;
     while ($back > 0 and empty($links['previous'])) {
         if ($canviewhidden || $sections[$back]->uservisible) {
             $params = array('id' => 'previous_section');
             if (!$sections[$back]->visible) {
                 $params['class'] = 'dimmed_text';
             }
             $previouslink = \html_writer::start_tag('div', array('class' => 'nav_icon'));
             $previouslink .= $previousarrow;
             $previouslink .= \html_writer::end_tag('div');
             $previouslink .= \html_writer::start_tag('span', array('class' => 'text'));
             $previouslink .= \html_writer::start_tag('span', array('class' => 'nav_guide'));
             $previouslink .= \get_string('previoussection', 'theme_essential');
             $previouslink .= \html_writer::end_tag('span');
             $previouslink .= \html_writer::empty_tag('br');
             $previouslink .= \get_section_name($course, $sections[$back]);
             $previouslink .= \html_writer::end_tag('span');
             $links['previous'] = \html_writer::link(course_get_url($course, $back), $previouslink, $params);
         }
         $back--;
     }
     $forward = $sectionno + 1;
     while ($forward <= $course->numsections and empty($links['next'])) {
         if ($canviewhidden || $sections[$forward]->uservisible) {
             $params = array('id' => 'next_section');
             if (!$sections[$forward]->visible) {
                 $params['class'] = 'dimmed_text';
             }
             $nextlink = \html_writer::start_tag('div', array('class' => 'nav_icon'));
             $nextlink .= $nextarrow;
             $nextlink .= \html_writer::end_tag('div');
             $nextlink .= \html_writer::start_tag('span', array('class' => 'text'));
             $nextlink .= \html_writer::start_tag('span', array('class' => 'nav_guide'));
             $nextlink .= \get_string('nextsection', 'theme_essential');
             $nextlink .= \html_writer::end_tag('span');
             $nextlink .= \html_writer::empty_tag('br');
             $nextlink .= \get_section_name($course, $sections[$forward]);
             $nextlink .= \html_writer::end_tag('span');
             $links['next'] = \html_writer::link(course_get_url($course, $forward), $nextlink, $params);
         }
         $forward++;
     }
     return $links;
 }
 /**
  * Add a new section with the provided title and (optional) summary
  *
  * @return string
  */
 public function addsection_action()
 {
     global $CFG, $PAGE, $DB;
     require_once $CFG->dirroot . '/course/lib.php';
     $sectioname = required_param('newsection', PARAM_TEXT);
     $summary = optional_param('summary', '', PARAM_RAW);
     require_sesskey();
     $courseid = $PAGE->context->get_course_context()->instanceid;
     $course = course_get_format($courseid)->get_course();
     $course->numsections++;
     course_get_format($course)->update_course_format_options(array('numsections' => $course->numsections));
     course_create_sections_if_missing($course, range(0, $course->numsections));
     $modinfo = get_fast_modinfo($course);
     $section = $modinfo->get_section_info($course->numsections, MUST_EXIST);
     $DB->set_field('course_sections', 'name', $sectioname, array('id' => $section->id));
     $DB->set_field('course_sections', 'summary', $summary, array('id' => $section->id));
     $DB->set_field('course_sections', 'summaryformat', FORMAT_HTML, array('id' => $section->id));
     rebuild_course_cache($course->id);
     redirect(course_get_url($course, $section->section));
 }
    public function display_stopwatch(cm_info $cm, $stopwatch)
    {
        // TODO strings!!!!
        $timecompleted = '';
        if (($userrecord = mod_stopwatch_get_user_record($cm)) && $userrecord->duration) {
            $class = 'class="stopped"';
            $timevalue = mod_stopwatch_duration_to_string($userrecord->duration);
            $started = $userrecord->timecreated - $userrecord->duration;
            $completed = $userrecord->timecreated;
            // timecreated is when the record was created and it was created when user completed the module.
            $timestarted = $this->print_times($started, $completed);
            $stoplabel = 'Adjust';
        } else {
            $this->page->requires->js_init_call('M.mod_stopwatch.init', array($cm->id), true);
            $class = '';
            $timevalue = '';
            $timestarted = $this->print_times(time());
            $stoplabel = 'I\'m finished!';
        }
        $sesskey = sesskey();
        $action = new moodle_url('/mod/stopwatch/view.php');
        $str = <<<EOD
<form id="stopwatchform" method="POST" action="{$action}" {$class}>
    <input type="hidden" name="sesskey" value="{$sesskey}" />
    <input type="hidden" name="id" value="{$cm->id}" />
    <input type="hidden" name="cmd" value="updateduration" />
    <div class="clockface">
        <input id="clock" name="durationstr" value="{$timevalue}" class="clockdisplay" />
        <input id="reset" type="button" value="Reset" class="graybutton" />
        <div class="timestartedcompleted">{$timestarted}</div>
    </div>
    <br/>
    <input id="start" type="button" value="Start" class="greenbutton" />
    <input id="resume" type="button" value="Resume" class="bigstopwatchbutton greenbutton" />
    <input id="pause" type="button" value="Pause" class="bigstopwatchbutton yellowbutton" />
    <input id="stop" type="submit" value="{$stoplabel}" class="bigstopwatchbutton redbutton" />
EOD;
        $str .= '</form><br/>';
        $str .= $this->output->single_button(course_get_url($cm->course), get_string('back'), 'GET');
        return $str;
    }
Exemple #8
0
                        require_login($course, false, $cm);
                        $coursecontext = context_course::instance($course->id);
                        $modcontext = context_module::instance($cm->id);
                        require_capability('moodle/course:manageactivities', $modcontext);
                        $section = $DB->get_record('course_sections', array('id' => $cm->section), '*', MUST_EXIST);
                        $USER->activitycopy = $copy;
                        $USER->activitycopycourse = $cm->course;
                        $USER->activitycopyname = $cm->name;
                        $USER->activitycopysectionreturn = $sectionreturn;
                        redirect(course_get_url($course, $section->section, array('sr' => $sectionreturn)));
                    } else {
                        if (!empty($cancelcopy) and confirm_sesskey()) {
                            // value = course module
                            $courseid = $USER->activitycopycourse;
                            $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
                            $cm = get_coursemodule_from_id('', $USER->activitycopy, 0, true, IGNORE_MISSING);
                            $sectionreturn = $USER->activitycopysectionreturn;
                            unset($USER->activitycopy);
                            unset($USER->activitycopycourse);
                            unset($USER->activitycopyname);
                            unset($USER->activitycopysectionreturn);
                            redirect(course_get_url($course, $cm->sectionnum, array('sr' => $sectionreturn)));
                        } else {
                            print_error('unknowaction');
                        }
                    }
                }
            }
        }
    }
}
Exemple #9
0
    exit;
}
$scoidstr = '&amp;scoid=' . $sco->id;
$modestr = '&amp;mode=' . $mode;
$SESSION->scorm = new stdClass();
$SESSION->scorm->scoid = $sco->id;
$SESSION->scorm->scormstatus = 'Not Initialized';
$SESSION->scorm->scormmode = $mode;
$SESSION->scorm->attempt = $attempt;
// Mark module viewed.
$completion = new completion_info($course);
$completion->set_module_viewed($cm);
// Print the page header.
if (empty($scorm->popup) || $displaymode == 'popup') {
    // Redirect back to the correct section if one section per page is being used.
    $exiturl = course_get_url($course, $cm->sectionnum);
    $exitlink = html_writer::link($exiturl, $strexit, array('title' => $strexit));
    $PAGE->set_button($exitlink);
}
$PAGE->requires->data_for_js('scormplayerdata', array('launch' => false, 'currentorg' => '', 'sco' => 0, 'scorm' => 0, 'courseid' => $scorm->course, 'cwidth' => $scorm->width, 'cheight' => $scorm->height, 'popupoptions' => $scorm->options), true);
$PAGE->requires->js('/mod/scorm/request.js', true);
$PAGE->requires->js('/lib/cookies.js', true);
if (file_exists($CFG->dirroot . '/mod/scorm/datamodels/' . $scorm->version . '.js')) {
    $PAGE->requires->js('/mod/scorm/datamodels/' . $scorm->version . '.js', true);
} else {
    $PAGE->requires->js('/mod/scorm/datamodels/scorm_12.js', true);
}
echo $OUTPUT->header();
if (!empty($scorm->displayactivityname)) {
    echo $OUTPUT->heading(format_string($scorm->name));
}
Exemple #10
0
 /**
  * Prepares the templateable object to display section name
  *
  * @param \section_info|\stdClass $section
  * @param bool $linkifneeded
  * @param bool $editable
  * @param null|lang_string|string $edithint
  * @param null|lang_string|string $editlabel
  * @return \core\output\inplace_editable
  */
 public function inplace_editable_render_section_name($section, $linkifneeded = true, $editable = null, $edithint = null, $editlabel = null)
 {
     global $USER, $CFG;
     require_once $CFG->dirroot . '/course/lib.php';
     if ($editable === null) {
         $editable = !empty($USER->editing) && has_capability('moodle/course:update', context_course::instance($section->course));
     }
     $displayvalue = $title = get_section_name($section->course, $section);
     if ($linkifneeded) {
         // Display link under the section name if the course format setting is to display one section per page.
         $url = course_get_url($section->course, $section->section, array('navigation' => true));
         if ($url) {
             $displayvalue = html_writer::link($url, $title);
         }
         $itemtype = 'sectionname';
     } else {
         // If $linkifneeded==false, we never display the link (this is used when rendering the section header).
         // Itemtype 'sectionnamenl' (nl=no link) will tell the callback that link should not be rendered -
         // there is no other way callback can know where we display the section name.
         $itemtype = 'sectionnamenl';
     }
     if (empty($edithint)) {
         $edithint = new lang_string('editsectionname');
     }
     if (empty($editlabel)) {
         $editlabel = new lang_string('newsectionname', '', $title);
     }
     return new \core\output\inplace_editable('format_' . $this->format, $itemtype, $section->id, $editable, $displayvalue, $section->name, $edithint, $editlabel);
 }
// restored copy of the module
$newcmid = null;
$tasks = $rc->get_plan()->get_tasks();
foreach ($tasks as $task) {
    if (is_subclass_of($task, 'restore_activity_task')) {
        if ($task->get_old_contextid() == $cmcontext->id) {
            $newcmid = $task->get_moduleid();
            break;
        }
    }
}
// if we know the cmid of the new course module, let us move it
// right below the original one. otherwise it will stay at the
// end of the section
if ($newcmid) {
    $newcm = get_coursemodule_from_id('', $newcmid, $course->id, true, MUST_EXIST);
    moveto_module($newcm, $section, $cm);
    moveto_module($cm, $section, $newcm);
}
$rc->destroy();
if (empty($CFG->keeptempdirectoriesonbackup)) {
    fulldelete($backupbasepath);
}
echo $output->header();
if ($newcmid) {
    echo $output->confirm(get_string('duplicatesuccess', 'core', $a), new single_button(new moodle_url('/course/modedit.php', array('update' => $newcmid, 'sr' => $sectionreturn)), get_string('duplicatecontedit'), 'get'), new single_button(course_get_url($course, $cm->sectionnum, array('sr' => $sectionreturn)), get_string('duplicatecontcourse'), 'get'));
} else {
    echo $output->notification(get_string('duplicatesuccess', 'core', $a), 'notifysuccess');
    echo $output->continue_button(course_get_url($course, $cm->sectionnum, array('sr' => $sectionreturn)));
}
echo $output->footer();
Exemple #12
0
require_login($course, false, $cm);
require_capability('mod/folder:managefiles', $context);

$PAGE->set_url('/mod/folder/edit.php', array('id' => $cm->id));
$PAGE->set_title($course->shortname.': '.$folder->name);
$PAGE->set_heading($course->fullname);
$PAGE->set_activity_record($folder);

$data = new stdClass();
$data->id = $cm->id;
$options = array('subdirs'=>1, 'maxbytes'=>$CFG->maxbytes, 'maxfiles'=>-1, 'accepted_types'=>'*');
file_prepare_standard_filemanager($data, 'files', $options, $context, 'mod_folder', 'content', 0);

$mform = new mod_folder_edit_form(null, array('data'=>$data, 'options'=>$options));
if ($folder->display == FOLDER_DISPLAY_INLINE) {
    $redirecturl = course_get_url($cm->course, $cm->sectionnum);
} else {
    $redirecturl = new moodle_url('/mod/folder/view.php', array('id' => $cm->id));
}

if ($mform->is_cancelled()) {
    redirect($redirecturl);

} else if ($formdata = $mform->get_data()) {
    $formdata = file_postupdate_standard_filemanager($formdata, 'files', $options, $context, 'mod_folder', 'content', 0);
    $DB->set_field('folder', 'revision', $folder->revision+1, array('id'=>$folder->id));

    // Update the variable of the folder revision so we can pass it as an accurate snapshot later.
    $folder->revision = $folder->revision + 1;

    $params = array(
 /**
  * Generate the html for the 'Jump to' menu on a single section page.
  *
  * @param stdClass $course The course entry from DB
  * @param array $sections The course_sections entries from the DB
  * @param $displaysection the current displayed section number.
  *
  * @return string HTML to output.
  */
 protected function section_nav_selection($course, $sections, $displaysection)
 {
     global $CFG;
     $o = '';
     $sectionmenu = array();
     $sectionmenu[course_get_url($course)->out(false)] = get_string('maincoursepage');
     $modinfo = get_fast_modinfo($course);
     $section = 1;
     while ($section <= $course->numsections) {
         $thissection = $modinfo->get_section_info($section);
         $showsection = $thissection->uservisible or !$course->hiddensections;
         if ($showsection && $section != $displaysection && ($url = course_get_url($course, $section))) {
             $sectionmenu[$url->out(false)] = get_section_name($course, $section);
         }
         $section++;
     }
     $select = new url_select($sectionmenu, '', array('' => get_string('jumpto')));
     $select->class = 'jumpmenu';
     $select->formid = 'sectionmenu';
     $o .= $this->output->render($select);
     return $o;
 }
Exemple #14
0
 /**
  * Output the html for a single section page .
  *
  * @param stdClass $course The course entry from DB
  * @param array $sections (argument not used)
  * @param array $mods (argument not used)
  * @param array $modnames (argument not used)
  * @param array $modnamesused (argument not used)
  * @param int $displaysection The section number in the course which is being displayed
  */
 public function print_single_section_page($course, $sections, $mods, $modnames, $modnamesused, $displaysection)
 {
     global $PAGE;
     $modinfo = get_fast_modinfo($course);
     $course = course_get_format($course)->get_course();
     // Can we view the section in question?
     if (!($sectioninfo = $modinfo->get_section_info($displaysection))) {
         // This section doesn't exist
         print_error('unknowncoursesection', 'error', null, $course->fullname);
         return;
     }
     if (!$sectioninfo->uservisible) {
         if (!$course->hiddensections) {
             echo $this->start_section_list();
             echo $this->section_hidden($displaysection);
             echo $this->end_section_list();
         }
         // Can't view this section.
         return;
     }
     // Copy activity clipboard..
     echo $this->course_activity_clipboard($course, $displaysection);
     $thissection = $modinfo->get_section_info(0);
     if ($thissection->summary or !empty($modinfo->sections[0]) or $PAGE->user_is_editing()) {
         echo $this->start_section_list();
         echo $this->section_header($thissection, $course, true, $displaysection);
         print_section($course, $thissection, null, null, true, "100%", false, $displaysection);
         if ($PAGE->user_is_editing()) {
             print_section_add_menus($course, 0, null, false, false, $displaysection);
         }
         echo $this->section_footer();
         echo $this->end_section_list();
     }
     // Start single-section div
     echo html_writer::start_tag('div', array('class' => 'single-section'));
     // The requested section page.
     $thissection = $modinfo->get_section_info($displaysection);
     // Title with section navigation links.
     $sectionnavlinks = $this->get_nav_links($course, $modinfo->get_section_info_all(), $displaysection);
     $sectiontitle = '';
     $sectiontitle .= html_writer::start_tag('div', array('class' => 'section-navigation header headingblock'));
     $sectiontitle .= html_writer::tag('span', $sectionnavlinks['previous'], array('class' => 'mdl-left'));
     $sectiontitle .= html_writer::tag('span', $sectionnavlinks['next'], array('class' => 'mdl-right'));
     // Title attributes
     $titleattr = 'mdl-align title';
     if (!$thissection->visible) {
         $titleattr .= ' dimmed_text';
     }
     $sectiontitle .= html_writer::tag('div', get_section_name($course, $displaysection), array('class' => $titleattr));
     $sectiontitle .= html_writer::end_tag('div');
     echo $sectiontitle;
     // Now the list of sections..
     echo $this->start_section_list();
     echo $this->section_header($thissection, $course, true, $displaysection);
     // Show completion help icon.
     $completioninfo = new completion_info($course);
     echo $completioninfo->display_help_icon();
     print_section($course, $thissection, null, null, true, '100%', false, $displaysection);
     if ($PAGE->user_is_editing()) {
         print_section_add_menus($course, $displaysection, null, false, false, $displaysection);
     }
     echo $this->section_footer();
     echo $this->end_section_list();
     // Display section bottom navigation.
     $courselink = html_writer::link(course_get_url($course), get_string('returntomaincoursepage'));
     $sectionbottomnav = '';
     $sectionbottomnav .= html_writer::start_tag('div', array('class' => 'section-navigation mdl-bottom'));
     $sectionbottomnav .= html_writer::tag('span', $sectionnavlinks['previous'], array('class' => 'mdl-left'));
     $sectionbottomnav .= html_writer::tag('span', $sectionnavlinks['next'], array('class' => 'mdl-right'));
     $sectionbottomnav .= html_writer::tag('div', $courselink, array('class' => 'mdl-align'));
     $sectionbottomnav .= html_writer::end_tag('div');
     echo $sectionbottomnav;
     // close single-section div.
     echo html_writer::end_tag('div');
 }
function report_comments_getusercomments($userid, $sort = 'date')
{
    global $CFG, $DB;
    $user = $DB->get_record('user', array('id' => $userid), 'firstname, lastname');
    $url = new moodle_url('/user/view.php', array('id' => $userid));
    $fullname = html_writer::link($url, $user->firstname . ' ' . $user->lastname);
    $formatoptions = array('overflowdiv' => true);
    $strftimeformat = get_string('strftimerecentfull', 'langconfig');
    $comments = $DB->get_records('comments', array('userid' => $userid), 'timecreated DESC');
    foreach ($comments as $comment) {
        $comment->fullname = $fullname;
        $comment->time = userdate($comment->timecreated, $strftimeformat);
        $context = context::instance_by_id($comment->contextid, IGNORE_MISSING);
        if (!$context) {
            continue;
        }
        $contexturl = '';
        switch ($context->contextlevel) {
            case CONTEXT_BLOCK:
                debugging('Block: ' . $context->instanceid);
                break;
            case CONTEXT_MODULE:
                $cm = get_coursemodule_from_id('', $context->instanceid);
                $course = get_course($cm->course);
                $contexturl = course_get_url($course);
                $comment->fullname = html_writer::link($contexturl, $course->fullname);
                $base = core_component::get_component_directory('mod_' . $cm->modname);
                if (file_exists("{$base}/view.php")) {
                    $base = substr($base, strlen($CFG->dirroot));
                    $contexturl = new moodle_url("{$base}/view.php", array('id' => $cm->id));
                }
                break;
            case CONTEXT_COURSE:
                $course = get_course($context->instanceid);
                $contexturl = course_get_url($course);
                $comment->fullname = html_writer::link($contexturl, $course->fullname);
                break;
            default:
                debugging('Default context: ' . $context->instanceid);
        }
        $comment->content = html_writer::link($contexturl, format_text($comment->content, $comment->format, $formatoptions));
    }
    return $comments;
}
Exemple #16
0
$context = context_module::instance($cm->id);
require_capability('mod/imscp:view', $context);
$params = array('context' => $context, 'objectid' => $imscp->id);
$event = \mod_imscp\event\course_module_viewed::create($params);
$event->add_record_snapshot('imscp', $imscp);
$event->trigger();
// Update 'viewed' state if required by completion system.
$completion = new completion_info($course);
$completion->set_module_viewed($cm);
$PAGE->set_url('/mod/imscp/view.php', array('id' => $cm->id));
$PAGE->requires->js('/mod/imscp/dummyapi.js', true);
$PAGE->requires->string_for_js('navigation', 'imscp');
$PAGE->requires->string_for_js('toc', 'imscp');
$PAGE->requires->string_for_js('hide', 'moodle');
$PAGE->requires->string_for_js('show', 'moodle');
// TODO: find some better way to disable blocks and minimise footer - pagetype just for this does not seem like a good solution.
// $PAGE->set_pagelayout('maxcontent'); ?
$PAGE->set_title($course->shortname . ': ' . $imscp->name);
$PAGE->set_heading($course->fullname);
$PAGE->set_activity_record($imscp);
echo $OUTPUT->header();
echo $OUTPUT->heading(format_string($imscp->name));
// Verify imsmanifest was parsed properly.
if (!$imscp->structure) {
    echo $OUTPUT->notification(get_string('deploymenterror', 'imscp'), 'notifyproblem');
    echo $OUTPUT->continue_button(course_get_url($course->id, $cm->section));
    echo $OUTPUT->footer();
    die;
}
imscp_print_content($imscp, $cm, $course);
echo $OUTPUT->footer();
 /**
  * Get URL related to the action.
  *
  * @return \moodle_url|null
  */
 public function get_url()
 {
     global $CFG;
     $sectionid = null;
     if (isset($this->other['coursesectionid'])) {
         $sectionid = $this->other['coursesectionid'];
     }
     require_once $CFG->dirroot . '/course/lib.php';
     try {
         return course_get_url($this->courseid, $sectionid);
     } catch (\Exception $e) {
         return null;
     }
 }
function link_to_gdoc($name, $link, $type = null, $modtype = 'url')
{
    global $COURSE, $DB, $CFG, $USER;
    require_once "{$CFG->dirroot}/mod/{$modtype}/lib.php";
    //add
    $fromform = new stdClass();
    $newform = new stdClass();
    $mform = new MoodleQuickForm(null, 'POST', 'nothing');
    $module = $DB->get_record("modules", array('name' => $modtype));
    $course = $COURSE;
    $cw = get_course_section(0, $course->id);
    $cm = null;
    // fields for mdl_url
    $fromform->course = $course->id;
    $fromform->name = $name;
    $fromform->introformat = 0;
    $fromform->introeditor = 0;
    $fromform->externalurl = $link;
    /*    if ($type !== 'dir') {
            $fromform->display          = 6;
            $fromform->displayoptions = 'a:2:{s:10:"popupwidth";i:1024;s:11:"popupheight";i:768;}';
        } else {
    */
    $fromform->display = 0;
    $fromform->popupwidth = 1024;
    $fromform->popupheight = 768;
    $fromform->popupwidth = null;
    $fromform->popupheight = null;
    $fromform->displayoptions = 'a:1:{s:10:"printintro";i:0;}';
    //    }
    // fields for mdl_course_module
    $fromform->module = $module->id;
    $fromform->instance = '';
    $fromform->section = 0;
    // The section number itself - relative!!! (section column in course_sections)
    $fromform->idnumber = null;
    $fromform->score = 0;
    $fromform->indent = 0;
    $fromform->visible = 1;
    $fromform->visibleold = 1;
    $fromform->groupmode = $course->groupmode;
    $fromform->groupingid = 0;
    $fromform->groupmembersonly = 0;
    $fromform->completion = 0;
    $fromform->completionview = 0;
    $fromform->completionexpected = 0;
    $fromform->availablefrom = 0;
    $fromform->availableuntil = 0;
    $fromform->showavailability = 0;
    $fromform->showdescription = 0;
    $fromform->conditiongradegroup = array();
    $fromform->conditionfieldgroup = array();
    // fields for mdl_course_sections
    $fromform->summaryformat = 0;
    $fromform->modulename = clean_param($module->name, PARAM_SAFEDIR);
    // For safety
    //	$fromform->add              = 'resource';
    //	$fromform->type             = $type == 'dir' ? 'collection' : 'file';
    //	$fromform->return           = 0; //must be false if this is an add, go back to course view on cancel
    //    $fromform->coursemodule 	= '';
    //	$fromform->popup			= 'resizable=1,scrollbars=1,directories=1,location=1,menubar=1,toolbar=1,status=1,width=1024,height=768';
    //	require_login($course->id); // needed to setup proper $COURSE
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    require_capability('moodle/course:manageactivities', $context);
    if (!empty($course->groupmodeforce) or !isset($fromform->groupmode)) {
        $fromform->groupmode = 0;
        // do not set groupmode
    }
    if (!course_allowed_module($course, $fromform->modulename)) {
        print_error('moduledisable', '', '', $fromform->modulename);
    }
    // first add course_module record because we need the context
    $newcm = new stdClass();
    $newcm->course = $course->id;
    $newcm->module = $fromform->module;
    $newcm->instance = 0;
    // not known yet, will be updated later (this is similar to restore code)
    $newcm->visible = $fromform->visible;
    $newcm->groupmode = $fromform->groupmode;
    $newcm->groupingid = $fromform->groupingid;
    $newcm->groupmembersonly = $fromform->groupmembersonly;
    $completion = new completion_info($course);
    if ($completion->is_enabled()) {
        $newcm->completion = $fromform->completion;
        $newcm->completiongradeitemnumber = $fromform->completiongradeitemnumber;
        $newcm->completionview = $fromform->completionview;
        $newcm->completionexpected = $fromform->completionexpected;
    }
    if (!empty($CFG->enableavailability)) {
        $newcm->availablefrom = $fromform->availablefrom;
        $newcm->availableuntil = $fromform->availableuntil;
        $newcm->showavailability = $fromform->showavailability;
    }
    if (isset($fromform->showdescription)) {
        $newcm->showdescription = $fromform->showdescription;
    } else {
        $newcm->showdescription = 0;
    }
    if (!($fromform->coursemodule = add_course_module($newcm))) {
        print_error('cannotaddcoursemodule');
    }
    if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) {
        $draftid_editor = file_get_submitted_draft_itemid('introeditor');
        file_prepare_draft_area($draftid_editor, null, null, null, null);
        $fromform->introeditor = array('text' => '', 'format' => FORMAT_HTML, 'itemid' => $draftid_editor);
        // TODO: add better default
    }
    if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) {
        $introeditor = $fromform->introeditor;
        unset($fromform->introeditor);
        $fromform->intro = $introeditor['text'];
        $fromform->introformat = $introeditor['format'];
    }
    $addinstancefunction = $fromform->modulename . "_add_instance";
    $updateinstancefunction = $fromform->modulename . "_update_instance";
    $returnfromfunc = $addinstancefunction($fromform, $mform);
    //	$returnfromfunc = url_add_instance($fromform, $mform);
    if (!$returnfromfunc or !is_number($returnfromfunc)) {
        // undo everything we can
        $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule);
        delete_context(CONTEXT_MODULE, $fromform->coursemodule);
        $DB->delete_records('course_modules', array('id' => $fromform->coursemodule));
        if (!is_number($returnfromfunc)) {
            print_error('invalidfunction', '', course_get_url($course, $cw->section));
        } else {
            print_error('cannotaddnewmodule', '', course_get_url($course, $cw->section), $fromform->modulename);
        }
    }
    $fromform->instance = $returnfromfunc;
    $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id' => $fromform->coursemodule));
    // update embedded links and save files
    $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule);
    if (!empty($introeditor)) {
        $fromform->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, 'mod_' . $fromform->modulename, 'intro', 0, array('subdirs' => true), $introeditor['text']);
        $DB->set_field($fromform->modulename, 'intro', $fromform->intro, array('id' => $fromform->instance));
    }
    // course_modules and course_sections each contain a reference
    // to each other, so we have to update one of them twice.
    $sectionid = add_mod_to_section($fromform);
    $DB->set_field('course_modules', 'section', $sectionid, array('id' => $fromform->coursemodule));
    // make sure visibility is set correctly (in particular in calendar)
    set_coursemodule_visible($fromform->coursemodule, $fromform->visible);
    if (isset($fromform->cmidnumber)) {
        //label
        // set cm idnumber
        set_coursemodule_idnumber($fromform->coursemodule, $fromform->cmidnumber);
    }
    // Set up conditions
    if ($CFG->enableavailability) {
        condition_info::update_cm_from_form((object) array('id' => $fromform->coursemodule), $fromform, false);
    }
    $eventname = 'mod_created';
    add_to_log($course->id, "course", "add mod", "../mod/{$fromform->modulename}/view.php?id={$fromform->coursemodule}", "{$fromform->modulename} {$fromform->instance}");
    add_to_log($course->id, $fromform->modulename, "add", "view.php?id={$fromform->coursemodule}", "{$fromform->instance}", $fromform->coursemodule);
    // Trigger mod_created/mod_updated event with information about this module.
    $eventdata = new stdClass();
    $eventdata->modulename = $fromform->modulename;
    $eventdata->name = $fromform->name;
    $eventdata->cmid = $fromform->coursemodule;
    $eventdata->courseid = $course->id;
    $eventdata->userid = $USER->id;
    events_trigger($eventname, $eventdata);
    rebuild_course_cache($course->id);
    return 1;
}
/**
 * This function checks that the current user is logged in and has the
 * required privileges
 *
 * This function checks that the current user is logged in, and optionally
 * whether they are allowed to be in a particular course and view a particular
 * course module.
 * If they are not logged in, then it redirects them to the site login unless
 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
 * case they are automatically logged in as guests.
 * If $courseid is given and the user is not enrolled in that course then the
 * user is redirected to the course enrolment page.
 * If $cm is given and the course module is hidden and the user is not a teacher
 * in the course then the user is redirected to the course home page.
 *
 * When $cm parameter specified, this function sets page layout to 'module'.
 * You need to change it manually later if some other layout needed.
 *
 * @package    core_access
 * @category   access
 *
 * @param mixed $courseorid id of the course or course object
 * @param bool $autologinguest default true
 * @param object $cm course module object
 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
 *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
 *             in order to keep redirects working properly. MDL-14495
 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
 * @return mixed Void, exit, and die depending on path
 * @throws coding_exception
 * @throws require_login_exception
 * @throws moodle_exception
 */
function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false)
{
    global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
    // Must not redirect when byteserving already started.
    if (!empty($_SERVER['HTTP_RANGE'])) {
        $preventredirect = true;
    }
    if (AJAX_SCRIPT) {
        // We cannot redirect for AJAX scripts either.
        $preventredirect = true;
    }
    // Setup global $COURSE, themes, language and locale.
    if (!empty($courseorid)) {
        if (is_object($courseorid)) {
            $course = $courseorid;
        } else {
            if ($courseorid == SITEID) {
                $course = clone $SITE;
            } else {
                $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
            }
        }
        if ($cm) {
            if ($cm->course != $course->id) {
                throw new coding_exception('course and cm parameters in require_login() call do not match!!');
            }
            // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
            if (!$cm instanceof cm_info) {
                // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
                // db queries so this is not really a performance concern, however it is obviously
                // better if you use get_fast_modinfo to get the cm before calling this.
                $modinfo = get_fast_modinfo($course);
                $cm = $modinfo->get_cm($cm->id);
            }
        }
    } else {
        // Do not touch global $COURSE via $PAGE->set_course(),
        // the reasons is we need to be able to call require_login() at any time!!
        $course = $SITE;
        if ($cm) {
            throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
        }
    }
    // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
    // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
    // risk leading the user back to the AJAX request URL.
    if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
        $setwantsurltome = false;
    }
    // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
    if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
        if ($preventredirect) {
            throw new require_login_session_timeout_exception();
        } else {
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            redirect(get_login_url());
        }
    }
    // If the user is not even logged in yet then make sure they are.
    if (!isloggedin()) {
        if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
            if (!($guest = get_complete_user_data('id', $CFG->siteguest))) {
                // Misconfigured site guest, just redirect to login page.
                redirect(get_login_url());
                exit;
                // Never reached.
            }
            $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
            complete_user_login($guest);
            $USER->autologinguest = true;
            $SESSION->lang = $lang;
        } else {
            // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
            if ($preventredirect) {
                throw new require_login_exception('You are not logged in');
            }
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            $referer = get_local_referer(false);
            if (!empty($referer)) {
                $SESSION->fromurl = $referer;
            }
            // Give auth plugins an opportunity to authenticate or redirect to an external login page
            $authsequence = get_enabled_auth_plugins(true);
            // auths, in sequence
            foreach ($authsequence as $authname) {
                $authplugin = get_auth_plugin($authname);
                $authplugin->pre_loginpage_hook();
                if (isloggedin()) {
                    break;
                }
            }
            // If we're still not logged in then go to the login page
            if (!isloggedin()) {
                redirect(get_login_url());
                exit;
                // Never reached.
            }
        }
    }
    // Loginas as redirection if needed.
    if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
        if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
            if ($USER->loginascontext->instanceid != $course->id) {
                print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid);
            }
        }
    }
    // Check whether the user should be changing password (but only if it is REALLY them).
    if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
        $userauth = get_auth_plugin($USER->auth);
        if ($userauth->can_change_password() and !$preventredirect) {
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            if ($changeurl = $userauth->change_password_url()) {
                // Use plugin custom url.
                redirect($changeurl);
            } else {
                // Use moodle internal method.
                if (empty($CFG->loginhttps)) {
                    redirect($CFG->wwwroot . '/login/change_password.php');
                } else {
                    $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
                    redirect($wwwroot . '/login/change_password.php');
                }
            }
        } else {
            if ($userauth->can_change_password()) {
                throw new moodle_exception('forcepasswordchangenotice');
            } else {
                throw new moodle_exception('nopasswordchangeforced', 'auth');
            }
        }
    }
    // Check that the user account is properly set up. If we can't redirect to
    // edit their profile, perform just the lax check. It will allow them to
    // use filepicker on the profile edit page.
    if ($preventredirect) {
        $usernotfullysetup = user_not_fully_set_up($USER, false);
    } else {
        $usernotfullysetup = user_not_fully_set_up($USER, true);
    }
    if ($usernotfullysetup) {
        if ($preventredirect) {
            throw new moodle_exception('usernotfullysetup');
        }
        if ($setwantsurltome) {
            $SESSION->wantsurl = qualified_me();
        }
        redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&amp;course=' . SITEID);
    }
    // Make sure the USER has a sesskey set up. Used for CSRF protection.
    sesskey();
    // Do not bother admins with any formalities, except for activities pending deletion.
    if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
        // Set the global $COURSE.
        if ($cm) {
            $PAGE->set_cm($cm, $course);
            $PAGE->set_pagelayout('incourse');
        } else {
            if (!empty($courseorid)) {
                $PAGE->set_course($course);
            }
        }
        // Set accesstime or the user will appear offline which messes up messaging.
        user_accesstime_log($course->id);
        return;
    }
    // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
    if (!$USER->policyagreed and !is_siteadmin()) {
        if (!empty($CFG->sitepolicy) and !isguestuser()) {
            if ($preventredirect) {
                throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy);
            }
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            redirect($CFG->wwwroot . '/user/policy.php');
        } else {
            if (!empty($CFG->sitepolicyguest) and isguestuser()) {
                if ($preventredirect) {
                    throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest);
                }
                if ($setwantsurltome) {
                    $SESSION->wantsurl = qualified_me();
                }
                redirect($CFG->wwwroot . '/user/policy.php');
            }
        }
    }
    // Fetch the system context, the course context, and prefetch its child contexts.
    $sysctx = context_system::instance();
    $coursecontext = context_course::instance($course->id, MUST_EXIST);
    if ($cm) {
        $cmcontext = context_module::instance($cm->id, MUST_EXIST);
    } else {
        $cmcontext = null;
    }
    // If the site is currently under maintenance, then print a message.
    if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
        if ($preventredirect) {
            throw new require_login_exception('Maintenance in progress');
        }
        $PAGE->set_context(null);
        print_maintenance_message();
    }
    // Make sure the course itself is not hidden.
    if ($course->id == SITEID) {
        // Frontpage can not be hidden.
    } else {
        if (is_role_switched($course->id)) {
            // When switching roles ignore the hidden flag - user had to be in course to do the switch.
        } else {
            if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
                // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
                // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
                if ($preventredirect) {
                    throw new require_login_exception('Course is hidden');
                }
                $PAGE->set_context(null);
                // We need to override the navigation URL as the course won't have been added to the navigation and thus
                // the navigation will mess up when trying to find it.
                navigation_node::override_active_url(new moodle_url('/'));
                notice(get_string('coursehidden'), $CFG->wwwroot . '/');
            }
        }
    }
    // Is the user enrolled?
    if ($course->id == SITEID) {
        // Everybody is enrolled on the frontpage.
    } else {
        if (\core\session\manager::is_loggedinas()) {
            // Make sure the REAL person can access this course first.
            $realuser = \core\session\manager::get_realuser();
            if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
                if ($preventredirect) {
                    throw new require_login_exception('Invalid course login-as access');
                }
                $PAGE->set_context(null);
                echo $OUTPUT->header();
                notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/');
            }
        }
        $access = false;
        if (is_role_switched($course->id)) {
            // Ok, user had to be inside this course before the switch.
            $access = true;
        } else {
            if (is_viewing($coursecontext, $USER)) {
                // Ok, no need to mess with enrol.
                $access = true;
            } else {
                if (isset($USER->enrol['enrolled'][$course->id])) {
                    if ($USER->enrol['enrolled'][$course->id] > time()) {
                        $access = true;
                        if (isset($USER->enrol['tempguest'][$course->id])) {
                            unset($USER->enrol['tempguest'][$course->id]);
                            remove_temp_course_roles($coursecontext);
                        }
                    } else {
                        // Expired.
                        unset($USER->enrol['enrolled'][$course->id]);
                    }
                }
                if (isset($USER->enrol['tempguest'][$course->id])) {
                    if ($USER->enrol['tempguest'][$course->id] == 0) {
                        $access = true;
                    } else {
                        if ($USER->enrol['tempguest'][$course->id] > time()) {
                            $access = true;
                        } else {
                            // Expired.
                            unset($USER->enrol['tempguest'][$course->id]);
                            remove_temp_course_roles($coursecontext);
                        }
                    }
                }
                if (!$access) {
                    // Cache not ok.
                    $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
                    if ($until !== false) {
                        // Active participants may always access, a timestamp in the future, 0 (always) or false.
                        if ($until == 0) {
                            $until = ENROL_MAX_TIMESTAMP;
                        }
                        $USER->enrol['enrolled'][$course->id] = $until;
                        $access = true;
                    } else {
                        $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
                        $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
                        $enrols = enrol_get_plugins(true);
                        // First ask all enabled enrol instances in course if they want to auto enrol user.
                        foreach ($instances as $instance) {
                            if (!isset($enrols[$instance->enrol])) {
                                continue;
                            }
                            // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
                            $until = $enrols[$instance->enrol]->try_autoenrol($instance);
                            if ($until !== false) {
                                if ($until == 0) {
                                    $until = ENROL_MAX_TIMESTAMP;
                                }
                                $USER->enrol['enrolled'][$course->id] = $until;
                                $access = true;
                                break;
                            }
                        }
                        // If not enrolled yet try to gain temporary guest access.
                        if (!$access) {
                            foreach ($instances as $instance) {
                                if (!isset($enrols[$instance->enrol])) {
                                    continue;
                                }
                                // Get a duration for the guest access, a timestamp in the future or false.
                                $until = $enrols[$instance->enrol]->try_guestaccess($instance);
                                if ($until !== false and $until > time()) {
                                    $USER->enrol['tempguest'][$course->id] = $until;
                                    $access = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!$access) {
            if ($preventredirect) {
                throw new require_login_exception('Not enrolled');
            }
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            redirect($CFG->wwwroot . '/enrol/index.php?id=' . $course->id);
        }
    }
    // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
    if ($cm && $cm->deletioninprogress) {
        if ($preventredirect) {
            throw new moodle_exception('activityisscheduledfordeletion');
        }
        require_once $CFG->dirroot . '/course/lib.php';
        redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
    }
    // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
    if ($cm && !$cm->uservisible) {
        if ($preventredirect) {
            throw new require_login_exception('Activity is hidden');
        }
        if ($course->id != SITEID) {
            $url = new moodle_url('/course/view.php', array('id' => $course->id));
        } else {
            $url = new moodle_url('/');
        }
        redirect($url, get_string('activityiscurrentlyhidden'));
    }
    // Set the global $COURSE.
    if ($cm) {
        $PAGE->set_cm($cm, $course);
        $PAGE->set_pagelayout('incourse');
    } else {
        if (!empty($courseorid)) {
            $PAGE->set_course($course);
        }
    }
    // Finally access granted, update lastaccess times.
    user_accesstime_log($course->id);
}
Exemple #20
0
 * @since Moodle 2.3
 */
require_once __DIR__ . '/../config.php';
require_once $CFG->dirroot . '/course/lib.php';
$courseid = required_param('courseid', PARAM_INT);
$increase = optional_param('increase', true, PARAM_BOOL);
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
$courseformatoptions = course_get_format($course)->get_format_options();
$PAGE->set_url('/course/changenumsections.php', array('courseid' => $courseid));
// Authorisation checks.
require_login($course);
require_capability('moodle/course:update', context_course::instance($course->id));
require_sesskey();
if (isset($courseformatoptions['numsections'])) {
    if ($increase) {
        // Add an additional section.
        $courseformatoptions['numsections']++;
    } else {
        // Remove a section.
        $courseformatoptions['numsections']--;
    }
    // Don't go less than 0, intentionally redirect silently (for the case of
    // double clicks).
    if ($courseformatoptions['numsections'] >= 0) {
        update_course((object) array('id' => $course->id, 'numsections' => $courseformatoptions['numsections']));
    }
}
$url = course_get_url($course);
$url->set_anchor('changenumsections');
// Redirect to where we were..
redirect($url);
Exemple #21
0
 /**
  * Returns the control to add a (sub)section
  *
  * @param int|section_info $parentsection
  * @return null|format_flexsections_edit_control
  */
 public function get_add_section_control($parentsection)
 {
     global $PAGE;
     if (!$PAGE->user_is_editing()) {
         return null;
     }
     $parentsection = $this->get_section_number($parentsection);
     $url = course_get_url($this->courseid, $this->get_viewed_section());
     $url->param('addchildsection', $parentsection);
     if ($parentsection) {
         $text = new lang_string('addsubsection', 'format_flexsections');
     } else {
         $text = new lang_string('addsection', 'format_flexsections');
     }
     return new format_flexsections_edit_control('addsection', $url, $text);
 }
Exemple #22
0
 /**
  * Export the document data to be used as a template context.
  *
  * Adding more info than the required one as people might be interested in extending the template.
  *
  * Although content is a required field when setting up the document, it accepts '' (empty) values
  * as they may be the result of striping out HTML.
  *
  * SECURITY NOTE: It is the responsibility of the document to properly escape any text to be displayed.
  * The renderer will output the content without any further cleaning.
  *
  * @param renderer_base $output The renderer.
  * @return array
  */
 public function export_for_template(\renderer_base $output)
 {
     list($componentname, $areaname) = \core_search\manager::extract_areaid_parts($this->get('areaid'));
     $title = $this->is_set('title') ? $this->format_text($this->get('title')) : '';
     $data = ['componentname' => $componentname, 'areaname' => $areaname, 'courseurl' => course_get_url($this->get('courseid')), 'coursefullname' => format_string($this->get('coursefullname'), true, array('context' => $this->get('contextid'))), 'modified' => userdate($this->get('modified')), 'title' => $title !== '' ? $title : get_string('notitle', 'search'), 'docurl' => $this->get_doc_url(), 'content' => $this->is_set('content') ? $this->format_text($this->get('content')) : null, 'contexturl' => $this->get_context_url(), 'description1' => $this->is_set('description1') ? $this->format_text($this->get('description1')) : null, 'description2' => $this->is_set('description2') ? $this->format_text($this->get('description2')) : null];
     // Now take any attached any files.
     $files = $this->get_files();
     if (!empty($files)) {
         if (count($files) > 1) {
             $filenames = array();
             foreach ($files as $file) {
                 $filenames[] = format_string($file->get_filename(), true, array('context' => $this->get('contextid')));
             }
             $data['multiplefiles'] = true;
             $data['filenames'] = $filenames;
         } else {
             $file = reset($files);
             $data['filename'] = format_string($file->get_filename(), true, array('context' => $this->get('contextid')));
         }
     }
     if ($this->is_set('userid')) {
         $data['userurl'] = new \moodle_url('/user/view.php', array('id' => $this->get('userid'), 'course' => $this->get('courseid')));
         $data['userfullname'] = format_string($this->get('userfullname'), true, array('context' => $this->get('contextid')));
     }
     return $data;
 }
Exemple #23
0
 /**
  * Generically loads the course sections into the course's navigation.
  *
  * @param stdClass $course
  * @param navigation_node $coursenode
  * @return array An array of course section nodes
  */
 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode)
 {
     global $CFG, $DB, $USER, $SITE;
     require_once $CFG->dirroot . '/course/lib.php';
     list($sections, $activities) = $this->generate_sections_and_activities($course);
     $navigationsections = array();
     foreach ($sections as $sectionid => $section) {
         $section = clone $section;
         if ($course->id == $SITE->id) {
             $this->load_section_activities($coursenode, $section->section, $activities);
         } else {
             if (!$section->uservisible || !$this->showemptysections && !$section->hasactivites && $this->includesectionnum !== $section->section) {
                 continue;
             }
             $sectionname = get_section_name($course, $section);
             $url = course_get_url($course, $section->section, array('navigation' => true));
             $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
             $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
             $sectionnode->hidden = !$section->visible || !$section->available;
             if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
                 $this->load_section_activities($sectionnode, $section->section, $activities);
             }
             $section->sectionnode = $sectionnode;
             $navigationsections[$sectionid] = $section;
         }
     }
     return $navigationsections;
 }
Exemple #24
0
    if (has_capability('moodle/course:update', $context)) {
        if ($hide && confirm_sesskey()) {
            set_section_visible($course->id, $hide, '0');
            redirect($PAGE->url);
        }
        if ($show && confirm_sesskey()) {
            set_section_visible($course->id, $show, '1');
            redirect($PAGE->url);
        }
        if (!empty($section)) {
            if (!empty($move) and confirm_sesskey()) {
                if (move_section($course, $section, $move)) {
                    if ($course->id == SITEID) {
                        redirect($CFG->wwwroot . '/?redirect=0');
                    } else {
                        redirect(course_get_url($course));
                    }
                } else {
                    echo $OUTPUT->notification('An error occurred while moving a section');
                }
            }
        }
    }
} else {
    $USER->editing = 0;
}
$SESSION->fromdiscussion = $PAGE->url->out(false);
if ($course->id == SITEID) {
    // This course is not a real course.
    redirect($CFG->wwwroot . '/');
}
Exemple #25
0
        /*$event = \core\event\course_section_updated::create(
                  array(
                      'objectid' => $data->id,
                      'courseid' => $course->id,
                      'context' => $context,
                      'other' => array('sectionnum' => $data->section)
                  )
              );
          $event->trigger();*/
        require_once $CFG->dirroot . '/calendar/lib.php';
        /*if($existentevent = $DB->get_record('event', array('courseid' =>$course->id, 'instance' => $data->section))){
              $event->id = $existentevent->id;
              $DB->update_record('event', $event);
          }else{
              calendar_event::create($event);
          }*/
        $PAGE->navigation->clear_cache();
        redirect(course_get_url($course, $section, array('sr' => $sectionreturn)));
    }
}
// The edit form is displayed for the first time or if there was validation error on the previous step.
$sectionname = get_section_name($course, $sectionnum);
$stredit = get_string('edita', '', " {$sectionname}");
$strsummaryof = get_string('summaryof', '', " {$sectionname}");
$PAGE->set_title($stredit);
$PAGE->set_heading($course->fullname);
$PAGE->navbar->add($stredit);
echo $OUTPUT->header();
echo $OUTPUT->heading($strsummaryof);
$mform->display();
echo $OUTPUT->footer();
Exemple #26
0
 /**
  * Renders html to print list of courses tagged with particular tag
  *
  * @param int $tagid id of the tag
  * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
  *             are displayed on the page and the per-page limit may be bigger
  * @param int $fromctx context id where the link was displayed, may be used by callbacks
  *            to display items in the same context first
  * @param int $ctx context id where to search for records
  * @param bool $rec search in subcontexts as well
  * @param array $displayoptions
  * @return string empty string if no courses are marked with this tag or rendered list of courses
  */
 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null)
 {
     global $CFG;
     require_once $CFG->libdir . '/coursecatlib.php';
     if (empty($displayoptions)) {
         $displayoptions = array();
     }
     $showcategories = coursecat::count_all() > 1;
     $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
     $chelper = new coursecat_helper();
     $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
     $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT : self::COURSECAT_SHOW_COURSES_EXPANDED)->set_search_criteria($searchcriteria)->set_courses_display_options($displayoptions)->set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
     // (we set the same css class as in search results by tagid)
     if ($totalcount = coursecat::search_courses_count($searchcriteria)) {
         $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
         if ($exclusivemode) {
             return $this->coursecat_courses($chelper, $courses, $totalcount);
         } else {
             $tagfeed = new core_tag\output\tagfeed();
             $img = $this->output->pix_icon('i/course', '');
             foreach ($courses as $course) {
                 $url = course_get_url($course);
                 $imgwithlink = html_writer::link($url, $img);
                 $coursename = html_writer::link($url, $course->get_formatted_name());
                 $details = '';
                 if ($showcategories && ($cat = coursecat::get($course->category, IGNORE_MISSING))) {
                     $details = get_string('category') . ': ' . html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)), $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
                 }
                 $tagfeed->add($imgwithlink, $coursename, $details);
             }
             return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
         }
     }
     return '';
 }
 /**
  * Generate a summary of a section for display on the 'course index page'
  *
  * @param stdClass $section The course_section entry from DB
  * @param stdClass $course The course entry from DB
  * @param array    $mods (argument not used)
  * @return string HTML to output.
  */
 protected function section_summary($section, $course, $mods)
 {
     $classattr = 'section main section-summary clearfix';
     $linkclasses = '';
     // If section is hidden then display grey section link.
     if (!$section->visible) {
         $classattr .= ' hidden';
         $linkclasses .= ' dimmed_text';
     } else {
         if ($this->courseformat->is_section_current($section)) {
             $classattr .= ' current';
         }
     }
     $o = '';
     $title = $this->courseformat->get_topcoll_section_name($course, $section, false);
     $liattributes = array('id' => 'section-' . $section->section, 'class' => $classattr, 'role' => 'region', 'aria-label' => $title);
     if ($this->tcsettings['layoutcolumnorientation'] == 2) {
         // Horizontal column layout.
         $liattributes['style'] = 'width:' . $this->tccolumnwidth . '%;';
     }
     $o .= html_writer::start_tag('li', $liattributes);
     $o .= html_writer::tag('div', '', array('class' => 'left side'));
     $o .= html_writer::tag('div', '', array('class' => 'right side'));
     $o .= html_writer::start_tag('div', array('class' => 'content'));
     if ($section->uservisible) {
         $title = html_writer::tag('a', $title, array('href' => course_get_url($course, $section->section), 'class' => $linkclasses));
     }
     $o .= $this->output->heading($title, 3, 'section-title');
     $o .= html_writer::start_tag('div', array('class' => 'summarytext'));
     $o .= $this->format_summary_text($section);
     $o .= html_writer::end_tag('div');
     $o .= $this->section_activity_summary($section, $course, null);
     $context = context_course::instance($course->id);
     $o .= $this->section_availability_message($section, has_capability('moodle/course:viewhiddensections', $context));
     $o .= html_writer::end_tag('div');
     $o .= html_writer::end_tag('li');
     return $o;
 }
Exemple #28
0
 /**
  * Generate the edit control items of a section
  *
  * @param stdClass $course The course entry from DB
  * @param stdClass $section The course_section entry from DB
  * @param bool $onsectionpage true if being printed on a section page
  * @return array of edit control items
  */
 protected function section_edit_control_items($course, $section, $onsectionpage = false)
 {
     global $PAGE;
     if (!$PAGE->user_is_editing()) {
         return array();
     }
     $coursecontext = context_course::instance($course->id);
     if ($onsectionpage) {
         $url = course_get_url($course, $section->section);
     } else {
         $url = course_get_url($course);
     }
     $url->param('sesskey', sesskey());
     $isstealth = $section->section > $course->numsections;
     $controls = array();
     if (!$isstealth && $section->section && has_capability('moodle/course:setcurrentsection', $coursecontext)) {
         if ($course->marker == $section->section) {
             // Show the "light globe" on/off.
             $url->param('marker', 0);
             $markedthistopic = get_string('markedthistopic');
             $highlightoff = get_string('highlightoff');
             $controls[] = array("url" => $url, "icon" => 'i/marked', "name" => $highlightoff, 'pixattr' => array('class' => '', 'alt' => $markedthistopic), "attr" => array('class' => 'editing_highlight', 'title' => $markedthistopic));
         } else {
             $url->param('marker', $section->section);
             $markthistopic = get_string('markthistopic');
             $highlight = get_string('highlight');
             $controls[] = array("url" => $url, "icon" => 'i/marker', "name" => $highlight, 'pixattr' => array('class' => '', 'alt' => $markthistopic), "attr" => array('class' => 'editing_highlight', 'title' => $markthistopic));
         }
     }
     return array_merge($controls, parent::section_edit_control_items($course, $section, $onsectionpage));
 }
 /**
  * Generically loads the course sections into the course's navigation.
  *
  * @param stdClass $course
  * @param navigation_node $coursenode
  * @param string $courseformat The course format
  * @return array An array of course section nodes
  */
 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode, $courseformat = 'unknown')
 {
     global $CFG, $DB, $USER, $SITE;
     require_once $CFG->dirroot . '/course/lib.php';
     list($sections, $activities) = $this->generate_sections_and_activities($course);
     $namingfunction = 'callback_' . $courseformat . '_get_section_name';
     $namingfunctionexists = function_exists($namingfunction);
     $urlfunction = 'callback_' . $courseformat . '_get_section_url';
     if (function_exists($urlfunction)) {
         // This code path is deprecated but we decided not to warn developers as
         // major changes are likely to follow in 2.4. See MDL-32504.
     } else {
         $urlfunction = null;
     }
     $key = 0;
     if (defined('AJAX_SCRIPT') && AJAX_SCRIPT == '0' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
         $key = optional_param('section', $key, PARAM_INT);
     }
     $navigationsections = array();
     foreach ($sections as $sectionid => $section) {
         $section = clone $section;
         if ($course->id == $SITE->id) {
             $this->load_section_activities($coursenode, $section->section, $activities);
         } else {
             if (!$section->uservisible || !$this->showemptysections && !$section->hasactivites && $this->includesectionnum !== $section->section) {
                 continue;
             }
             if ($namingfunctionexists) {
                 $sectionname = $namingfunction($course, $section, $sections);
             } else {
                 $sectionname = get_string('section') . ' ' . $section->section;
             }
             $url = null;
             if ($urlfunction) {
                 // pre 2.3 style format url
                 $url = $urlfunction($course->id, $section->section);
             } else {
                 $url = course_get_url($course, $section->section, array('navigation' => true));
             }
             $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
             $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
             $sectionnode->hidden = !$section->visible || !$section->available;
             if ($key != '0' && $section->section != '0' && $section->section == $key && $this->page->context->contextlevel != CONTEXT_MODULE && $section->hasactivites) {
                 $sectionnode->make_active();
                 $this->load_section_activities($sectionnode, $section->section, $activities);
             }
             $section->sectionnode = $sectionnode;
             $navigationsections[$sectionid] = $section;
         }
     }
     return $navigationsections;
 }
Exemple #30
0
    $imscp = $DB->get_record('imscp', array('id' => $i), '*', MUST_EXIST);
    $cm = get_coursemodule_from_instance('imscp', $imscp->id, $imscp->course, false, MUST_EXIST);
} else {
    $cm = get_coursemodule_from_id('imscp', $id, 0, false, MUST_EXIST);
    $imscp = $DB->get_record('imscp', array('id' => $cm->instance), '*', MUST_EXIST);
}
$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
require_course_login($course, true, $cm);
$context = context_module::instance($cm->id);
require_capability('mod/imscp:view', $context);
// Completion and trigger events.
imscp_view($imscp, $course, $cm, $context);
$PAGE->set_url('/mod/imscp/view.php', array('id' => $cm->id));
$PAGE->requires->js('/mod/imscp/dummyapi.js', true);
$PAGE->requires->string_for_js('navigation', 'imscp');
$PAGE->requires->string_for_js('toc', 'imscp');
$PAGE->requires->string_for_js('hide', 'moodle');
$PAGE->requires->string_for_js('show', 'moodle');
// TODO: find some better way to disable blocks and minimise footer - pagetype just for this does not seem like a good solution.
// $PAGE->set_pagelayout('maxcontent'); ?
$PAGE->set_title($course->shortname . ': ' . $imscp->name);
$PAGE->set_heading($course->fullname);
$PAGE->set_activity_record($imscp);
// Verify imsmanifest was parsed properly.
if (!$imscp->structure) {
    redirect(course_get_url($course->id, $cm->section), get_string('deploymenterror', 'imscp'));
}
echo $OUTPUT->header();
echo $OUTPUT->heading(format_string($imscp->name));
imscp_print_content($imscp, $cm, $course);
echo $OUTPUT->footer();