/** * Retrieve a file for a user of the Moodle client calling this function * The file is encoded in base64 * @global <type> $DB * @global <type> $USER * @global <type> $MNET_REMOTE_CLIENT * @param <type> $username * @param <type> $source * @return <type> */ public function retrieveFile($username, $source) { global $DB, $USER, $MNET_REMOTE_CLIENT; ///check the the user is known ///he has to be previously connected to the server site in order to be in the database //TODO: this seems weird - is it executed from cron or what? Please review $USER = $DB->get_record('user', array('username' => $username, 'mnethostid' => $MNET_REMOTE_CLIENT->id)); if (empty($USER)) { exit(mnet_server_fault(9016, get_string('usernotfound', 'repository_remotemoodle', $username))); } $file = unserialize(base64_decode($source)); $contextid = $file[0]; $filearea = $file[1]; $itemid = $file[2]; $filepath = $file[3]; $filename = $file[4]; ///check that the user has read permission on this file $browser = get_file_browser(); $fileinfo = $browser->get_file_info(get_context_instance_by_id($contextid), $filearea, $itemid, $filepath, $filename); if (empty($fileinfo)) { exit(mnet_server_fault(9016, get_string('usercannotaccess', 'repository_remotemoodle', $file))); } ///retrieve the file with file API functions and return it encoded in base64 $fs = get_file_storage(); $sf = $fs->get_file($contextid, $filearea, $itemid, $filepath, $filename); $contents = base64_encode($sf->get_content()); return array($contents, $sf->get_filename()); }
public function role_unassigned($ra) { global $DB; // note: do not test if plugin enabled, we want to keep removing previous roles // prevent circular dependencies - we can not sync meta roles recursively if ($ra->component === 'enrol_meta') { return true; } // only course level roles are interesting $parentcontext = get_context_instance_by_id($ra->contextid); if ($parentcontext->contextlevel != CONTEXT_COURSE) { return true; } // does anything want to sync with this parent? if (!($enrols = $DB->get_records('enrol', array('customint1' => $parentcontext->instanceid, 'enrol' => 'meta'), 'id ASC'))) { return true; } // note: do not check 'nosyncroleids', somebody might have just enabled it, we want to get rid of nosync roles gradually foreach ($enrols as $enrol) { // Is the user enrolled? We want to sync only really enrolled users if (!$DB->record_exists('user_enrolments', array('userid' => $ra->userid, 'enrolid' => $enrol->id))) { continue; } $context = get_context_instance(CONTEXT_COURSE, $enrol->courseid); // now make sure the user does not have the role through some other enrol plugin $params = array('contextid' => $ra->contextid, 'roleid' => $ra->roleid, 'userid' => $ra->userid); if ($DB->record_exists_select('role_assignments', "contextid = :contextid AND roleid = :roleid AND userid = :userid AND component <> 'enrol_meta'", $params)) { continue; } // unassign role, there is no other role assignment in parent course role_unassign($ra->roleid, $ra->userid, $context->id, 'enrol_meta', $enrol->id); } return true; }
/** * 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); }
/** * Add question-type specific form fields. * * @param MoodleQuickForm $mform the form being built. */ function question_dataset_dependent_items_form($submiturl, $question, $regenerate) { global $QTYPES, $SESSION, $CFG, $DB; $this->regenerate = $regenerate; $this->question = $question; $this->qtypeobj =& $QTYPES[$this->question->qtype]; // Validate the question category. if (!($category = $DB->get_record('question_categories', array('id' => $question->category)))) { print_error('categorydoesnotexist', 'question', $returnurl); } $this->category = $category; $this->categorycontext = get_context_instance_by_id($category->contextid); //get the dataset defintions for this question if (empty($question->id)) { $this->datasetdefs = $this->qtypeobj->get_dataset_definitions($question->id, $SESSION->calculated->definitionform->dataset); } else { if (empty($question->options)) { $this->get_question_options($question); } $this->datasetdefs = $this->qtypeobj->get_dataset_definitions($question->id, array()); } foreach ($this->datasetdefs as $datasetdef) { // Get maxnumber if ($this->maxnumber == -1 || $datasetdef->itemcount < $this->maxnumber) { $this->maxnumber = $datasetdef->itemcount; } } foreach ($this->datasetdefs as $defid => $datasetdef) { if (isset($datasetdef->id)) { $this->datasetdefs[$defid]->items = $this->qtypeobj->get_database_dataset_items($datasetdef->id); } } parent::moodleform($submiturl); }
function definition() { global $CFG, $DB; $mform = $this->_form; $course = $this->_customdata; $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('cohort'); $cohorts = array('' => get_string('choosedots')); list($sqlparents, $params) = $DB->get_in_or_equal(get_parent_contexts($coursecontext)); $sql = "SELECT id, name, contextid\n FROM {cohort}\n WHERE contextid {$sqlparents}\n ORDER BY name ASC"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $c) { $context = get_context_instance_by_id($c->contextid); if (!has_capability('moodle/cohort:view', $context)) { continue; } $cohorts[$c->id] = format_string($c->name); } $rs->close(); $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // descending default sortorder $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort')); $mform->addElement('select', 'cohortid', get_string('cohort', 'cohort'), $cohorts); $mform->addRule('cohortid', get_string('required'), 'required', null, 'client'); $mform->addElement('select', 'roleid', get_string('role'), $roles); $mform->addRule('roleid', get_string('required'), 'required', null, 'client'); $mform->setDefault('roleid', $enrol->get_config('roleid')); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); $this->add_action_buttons(true, get_string('addinstance', 'enrol')); $this->set_data(array('id' => $course->id)); }
/** * Callback function called from question_list() function * (which is called from showbank()) */ function module_specific_controls($totalnumber, $recurse, $category, $cmid, $cmoptions) { global $QTYPES, $OUTPUT; $out = ''; $catcontext = get_context_instance_by_id($category->contextid); if (has_capability('moodle/question:useall', $catcontext)) { if ($cmoptions->hasattempts) { $disabled = 'disabled="disabled"'; } else { $disabled = ''; } $randomusablequestions = $QTYPES['random']->get_usable_questions_from_category($category->id, $recurse, '0'); $maxrand = count($randomusablequestions); if ($maxrand > 0) { for ($i = 1; $i <= min(10, $maxrand); $i++) { $randomcount[$i] = $i; } for ($i = 20; $i <= min(100, $maxrand); $i += 10) { $randomcount[$i] = $i; } $straddtoquiz = get_string('addtoquiz', 'quiz'); $out = '<strong><label for="menurandomcount">' . get_string('addrandomfromcategory', 'quiz') . '</label></strong><br />'; $select = html_select::make($randomcount, 'randomcount', '1', false); $select->nothingvalue = ''; $select->disabled = $cmoptions->hasattempts; $out .= get_string('addrandom', 'quiz', $OUTPUT->select($select)); $out .= '<input type="hidden" name="recurse" value="' . $recurse . '" />'; $out .= '<input type="hidden" name="categoryid" value="' . $category->id . '" />'; $out .= ' <input type="submit" name="addrandom" value="' . $straddtoquiz . '" ' . $disabled . ' />'; $out .= $OUTPUT->help_icon(moodle_help_icon::make('random', get_string('random', 'quiz'), 'quiz')); } } return $out; }
/** * Handle a role assignment by creating an equivalent class enrolment or * instructor assignment (if applicable). */ static function role_assigned($data) { require_once CURMAN_DIRLOCATION . '/lib/student.class.php'; require_once CURMAN_DIRLOCATION . '/lib/instructor.class.php'; global $CURMAN; if (!($context = get_context_instance_by_id($data->contextid))) { $context = get_context_instance($data->contextid, $data->itemid); } if (!empty($context) && $context->contextlevel == context_level_base::get_custom_context_level('class', 'block_curr_admin')) { $cmuserid = cm_get_crlmuserid($data->userid); if ($data->roleid == $CURMAN->config->enrolment_role_sync_student_role) { // add enrolment record $student = new student(); $student->userid = $cmuserid; $student->classid = $context->instanceid; // NOTE: student::add checks if the student is already // enrolled, so we don't have to check here $student->add(); } if ($data->roleid == $CURMAN->config->enrolment_role_sync_instructor_role) { // add instructor record if (!instructor::user_is_instructor_of_class($cmuserid, $context->instanceid)) { $instructor = new instructor(); $instructor->userid = $cmuserid; $instructor->classid = $context->instanceid; $instructor->add(); } } } return true; }
/** * Callback function called from question_list() function (which is called from showbank()) */ function module_specific_controls($totalnumber, $recurse, $category, $cmid) { global $QTYPES; $out = ''; $catcontext = get_context_instance_by_id($category->contextid); if (has_capability('moodle/question:useall', $catcontext)) { $randomusablequestions = $QTYPES['random']->get_usable_questions_from_category($category->id, $recurse, '0'); $maxrand = count($randomusablequestions); if ($maxrand > 0) { for ($i = 1; $i <= min(10, $maxrand); $i++) { $randomcount[$i] = $i; } for ($i = 20; $i <= min(100, $maxrand); $i += 10) { $randomcount[$i] = $i; } $out .= '<br />'; $out .= get_string('addrandom', 'quiz', choose_from_menu($randomcount, 'randomcount', '1', '', '', '', true)); $out .= '<input type="hidden" name="recurse" value="' . $recurse . '" />'; $out .= '<input type="hidden" name="categoryid" value="' . $category->id . '" />'; $out .= ' <input type="submit" name="addrandom" value="' . get_string('add') . '" />'; $out .= helpbutton('random', get_string('random', 'quiz'), 'quiz', true, false, '', true); } } return $out; }
function definition() { $mform =& $this->_form; // First show fields specific to this type of block. $this->specific_definition($mform); // Then show the fields about where this block appears. $mform->addElement('header', 'whereheader', get_string('wherethisblockappears', 'block')); // If the current weight of the block is out-of-range, add that option in. $blockweight = $this->block->instance->weight; $weightoptions = array(); if ($blockweight < -block_manager::MAX_WEIGHT) { $weightoptions[$blockweight] = $blockweight; } for ($i = -block_manager::MAX_WEIGHT; $i <= block_manager::MAX_WEIGHT; $i++) { $weightoptions[$i] = $i; } if ($blockweight > block_manager::MAX_WEIGHT) { $weightoptions[$blockweight] = $blockweight; } $first = reset($weightoptions); $weightoptions[$first] = get_string('bracketfirst', 'block', $first); $last = end($weightoptions); $weightoptions[$last] = get_string('bracketlast', 'block', $last); $regionoptions = $this->page->theme->get_all_block_regions(); $parentcontext = get_context_instance_by_id($this->block->instance->parentcontextid); $mform->addElement('static', 'contextname', get_string('thisblockbelongsto', 'block'), print_context_name($parentcontext)); $mform->addElement('selectyesno', 'bui_showinsubcontexts', get_string('appearsinsubcontexts', 'block')); $pagetypeoptions = matching_page_type_patterns($this->page->pagetype); $pagetypeoptions = array_combine($pagetypeoptions, $pagetypeoptions); $mform->addElement('select', 'bui_pagetypepattern', get_string('pagetypes', 'block'), $pagetypeoptions); if ($this->page->subpage) { $subpageoptions = array('%@NULL@%' => get_string('anypagematchingtheabove', 'block'), $this->page->subpage => get_string('thisspecificpage', 'block', $this->page->subpage)); $mform->addElement('select', 'bui_subpagepattern', get_string('subpages', 'block'), $subpageoptions); } $defaultregionoptions = $regionoptions; $defaultregion = $this->block->instance->defaultregion; if (!array_key_exists($defaultregion, $defaultregionoptions)) { $defaultregionoptions[$defaultregion] = $defaultregion; } $mform->addElement('select', 'bui_defaultregion', get_string('defaultregion', 'block'), $defaultregionoptions); $mform->addElement('select', 'bui_defaultweight', get_string('defaultweight', 'block'), $weightoptions); // Where this block is positioned on this page. $mform->addElement('header', 'whereheader', get_string('onthispage', 'block')); $mform->addElement('selectyesno', 'bui_visible', get_string('visible', 'block')); $blockregion = $this->block->instance->region; if (!array_key_exists($blockregion, $regionoptions)) { $regionoptions[$blockregion] = $blockregion; } $mform->addElement('select', 'bui_region', get_string('region', 'block'), $regionoptions); $mform->addElement('select', 'bui_weight', get_string('weight', 'block'), $weightoptions); $pagefields = array('bui_visible', 'bui_region', 'bui_weight'); if (!$this->block->user_can_edit()) { $mform->hardFreezeAllVisibleExcept($pagefields); } if (!$this->page->user_can_edit_blocks()) { $mform->hardFreeze($pagefields); } $this->add_action_buttons(); }
/** * Get file listing * * @param string $encodedpath * @return mixed */ public function get_listing($encodedpath = '', $page = '') { global $CFG, $USER, $OUTPUT; $ret = array(); $ret['dynload'] = true; $ret['nosearch'] = true; $ret['nologin'] = true; $list = array(); if (!empty($encodedpath)) { $params = unserialize(base64_decode($encodedpath)); if (is_array($params)) { $component = is_null($params['component']) ? NULL : clean_param($params['component'], PARAM_COMPONENT); $filearea = is_null($params['filearea']) ? NULL : clean_param($params['filearea'], PARAM_AREA); $itemid = is_null($params['itemid']) ? NULL : clean_param($params['itemid'], PARAM_INT); $filepath = is_null($params['filepath']) ? NULL : clean_param($params['filepath'], PARAM_PATH); $filename = is_null($params['filename']) ? NULL : clean_param($params['filename'], PARAM_FILE); $context = get_context_instance_by_id(clean_param($params['contextid'], PARAM_INT)); } } else { $itemid = null; $filename = null; $filearea = null; $filepath = null; $component = null; if (!empty($this->context)) { list($context, $course, $cm) = get_context_info_array($this->context->id); if (is_object($course)) { $context = get_context_instance(CONTEXT_COURSE, $course->id); } else { $context = get_system_context(); } } else { $context = get_system_context(); } } $browser = get_file_browser(); $list = array(); if ($fileinfo = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename)) { // build file tree $element = repository_local_file::retrieve_file_info($fileinfo, $this); $nonemptychildren = $element->get_non_empty_children(); foreach ($nonemptychildren as $child) { $list[] = (array) $child->get_node(); } } else { // if file doesn't exist, build path nodes root of current context $fileinfo = $browser->get_file_info($context, null, null, null, null, null); } // build path navigation $ret['path'] = array(); $element = repository_local_file::retrieve_file_info($fileinfo, $this); for ($level = $element; $level; $level = $level->get_parent()) { if ($level == $element || !$level->can_skip()) { array_unshift($ret['path'], $level->get_node_path()); } } $ret['list'] = array_filter($list, array($this, 'filter')); return $ret; }
function qtype_ddmarker_course_context_id($catcontextid) { $context = get_context_instance_by_id($catcontextid); while ($context->contextlevel != CONTEXT_COURSE) { $context = get_context_instance_by_id(get_parent_contextid($context)); } return $context->id; }
function question_edit_form($submiturl, $question, $category, $contexts, $formeditable = true) { $this->question = $question; $this->contexts = $contexts; $this->category = $category; $this->categorycontext = get_context_instance_by_id($category->contextid); //course id or site id depending on question cat context $this->coursefilesid = get_filesdir_from_context(get_context_instance_by_id($category->contextid)); parent::moodleform($submiturl, null, 'post', '', null, $formeditable); }
/** * Add question-type specific form fields. * * @param MoodleQuickForm $mform the form being built. */ public function __construct($submiturl, $question) { global $DB; $this->question = $question; $this->qtypeobj = question_bank::get_qtype($this->question->qtype); // Validate the question category. if (!$category = $DB->get_record('question_categories', array('id' => $question->category))) { print_error('categorydoesnotexist', 'question', $returnurl); } $this->category = $category; $this->categorycontext = get_context_instance_by_id($category->contextid); parent::__construct($submiturl); }
public function __construct($submiturl, $question, $category, $contexts, $formeditable = true) { global $DB; $this->question = $question; $this->contexts = $contexts; $record = $DB->get_record('question_categories', array('id' => $question->category), 'contextid'); $this->context = get_context_instance_by_id($record->contextid); $this->editoroptions = array('subdirs' => 1, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'context' => $this->context); $this->fileoptions = array('subdirs' => 1, 'maxfiles' => -1, 'maxbytes' => -1); $this->category = $category; $this->categorycontext = get_context_instance_by_id($category->contextid); parent::__construct($submiturl, null, 'post', '', null, $formeditable); }
/** * Add question-type specific form fields. * * @param MoodleQuickForm $mform the form being built. */ function question_dataset_dependent_definitions_form($submiturl, $question) { global $QTYPES; $this->question = $question; $this->qtypeobj =& $QTYPES[$this->question->qtype]; // Validate the question category. if (!($category = get_record('question_categories', 'id', $question->category))) { print_error('categorydoesnotexist', 'question', $returnurl); } $this->category = $category; $this->categorycontext = get_context_instance_by_id($category->contextid); parent::moodleform($submiturl); }
/** * If this block belongs to a quiz context, then return that quiz's id. * Otherwise, return 0. * @return integer the quiz id. */ public function get_owning_quiz() { if (empty($this->instance->parentcontextid)) { return 0; } $parentcontext = get_context_instance_by_id($this->instance->parentcontextid); if ($parentcontext->contextlevel != CONTEXT_MODULE) { return 0; } $cm = get_coursemodule_from_id('quiz', $parentcontext->instanceid); if (!$cm) { return 0; } return $cm->instance; }
/** * 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); }
private function _setup_plugin($comment) { global $DB; $this->context = get_context_instance_by_id($comment->contextid); if ($this->context->contextlevel == CONTEXT_BLOCK) { if ($block = $DB->get_record('block_instances', array('id' => $this->context->instanceid))) { $this->plugintype = 'block'; $this->pluginname = $block->blockname; } } if ($this->context->contextlevel == CONTEXT_MODULE) { $this->plugintype = 'mod'; $this->cm = get_coursemodule_from_id('', $this->context->instanceid); $this->_setup_course($this->cm->course); $this->modinfo = get_fast_modinfo($this->course); $this->pluginname = $this->modinfo->cms[$this->cm->id]->modname; } }
/** * Callback function called from question_list() function (which is called from showbank()) */ function module_specific_controls($totalnumber, $recurse, $category, $cmid) { $catcontext = get_context_instance_by_id($category->contextid); if (has_capability('moodle/question:useall', $catcontext)) { for ($i = 1; $i <= min(10, $totalnumber); $i++) { $randomcount[$i] = $i; } for ($i = 20; $i <= min(100, $totalnumber); $i += 10) { $randomcount[$i] = $i; } $out = '<br />'; $out .= get_string('addrandom', 'quiz', choose_from_menu($randomcount, 'randomcount', '1', '', '', '', true)); $out .= '<input type="hidden" name="recurse" value="' . $recurse . '" />'; $out .= "<input type=\"hidden\" name=\"categoryid\" value=\"{$category->id}\" />"; $out .= ' <input type="submit" name="addrandom" value="' . get_string('add') . '" />'; $out .= helpbutton('random', get_string('random', 'quiz'), 'quiz', true, false, '', true); } else { $out = ''; } return $out; }
/** * Callback function called from question_list() function * (which is called from showbank()) */ function module_specific_controls($totalnumber, $recurse, $category, $cmid, $cmoptions) { global $OUTPUT; $out = ''; $catcontext = get_context_instance_by_id($category->contextid); if (has_capability('moodle/question:useall', $catcontext)) { if ($cmoptions->hasattempts) { $disabled = ' disabled="disabled"'; } else { $disabled = ''; } $randomusablequestions = question_bank::get_qtype('random')->get_available_questions_from_category( $category->id, $recurse); $maxrand = count($randomusablequestions); if ($maxrand > 0) { for ($i = 1; $i <= min(10, $maxrand); $i++) { $randomcount[$i] = $i; } for ($i = 20; $i <= min(100, $maxrand); $i += 10) { $randomcount[$i] = $i; } } else { $randomcount[0] = 0; $disabled = ' disabled="disabled"'; } $out = '<strong><label for="menurandomcount">'.get_string('addrandomfromcategory', 'quiz'). '</label></strong><br />'; $attributes = array(); $attributes['disabled'] = $disabled ? 'disabled' : null; $select = html_writer::select($randomcount, 'randomcount', '1', null, $attributes); $out .= get_string('addrandom', 'quiz', $select); $out .= '<input type="hidden" name="recurse" value="'.$recurse.'" />'; $out .= '<input type="hidden" name="categoryid" value="' . $category->id . '" />'; $out .= ' <input type="submit" name="addrandom" value="'. get_string('addtoquiz', 'quiz').'"' . $disabled . ' />'; $out .= $OUTPUT->help_icon('addarandomquestion', 'quiz'); } return $out; }
public function role_unassigned($ra) { global $DB; if (!enrol_is_enabled('category')) { return true; } // only category level roles are interesting $parentcontext = get_context_instance_by_id($ra->contextid); if ($parentcontext->contextlevel != CONTEXT_COURSECAT) { return true; } // now this is going to be a bit slow, take all enrolments in child courses and verify each separately $syscontext = get_context_instance(CONTEXT_SYSTEM); if (!($roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext))) { return true; } $plugin = enrol_get_plugin('category'); $sql = "SELECT e.*\n FROM {course} c\n JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel AND ctx.path LIKE :match)\n JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')\n JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)"; $params = array('courselevel' => CONTEXT_COURSE, 'match' => $parentcontext->path . '/%', 'userid' => $ra->userid); $rs = $DB->get_recordset_sql($sql, $params); list($roleids, $params) = $DB->get_in_or_equal(array_keys($roles), SQL_PARAMS_NAMED, 'r'); $params['userid'] = $ra->userid; foreach ($rs as $instance) { $coursecontext = get_context_instance(CONTEXT_COURSE, $instance->courseid); $contextids = get_parent_contexts($coursecontext); array_pop($contextids); // remove system context, we are interested in categories only list($contextids, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'c'); $params = array_merge($params, $contextparams); $sql = "SELECT ra.id\n FROM {role_assignments} ra\n WHERE ra.userid = :userid AND ra.contextid {$contextids} AND ra.roleid {$roleids}"; if (!$DB->record_exists_sql($sql, $params)) { // user does not have any interesting role in any parent context, let's unenrol $plugin->unenrol_user($instance, $ra->userid); } } $rs->close(); return true; }
function get_content() { global $CFG, $OUTPUT, $USER; $coursecontext = get_context_instance_by_id($this->instance->parentcontextid); if (!has_capability('moodle/community:add', $coursecontext) or $this->content !== NULL) { return $this->content; } $this->content = new stdClass(); $this->content->items = array(); $this->content->icons = array(); $this->content->footer = ''; if (!isloggedin()) { return $this->content; } $icon = html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('i/group'), 'class' => 'icon', 'alt' => "")); $addcourseurl = new moodle_url('/blocks/community/communitycourse.php', array('add' => true, 'courseid' => $this->page->course->id)); $searchlink = html_writer::tag('a', $icon . ' ' . get_string('addcourse', 'block_community'), array('href' => $addcourseurl->out(false))); $this->content->items[] = $searchlink; require_once $CFG->dirroot . '/blocks/community/locallib.php'; $communitymanager = new block_community_manager(); $courses = $communitymanager->block_community_get_courses($USER->id); if ($courses) { $this->content->items[] = html_writer::empty_tag('hr'); $this->content->icons[] = ''; $this->content->items[] = get_string('mycommunities', 'block_community'); $this->content->icons[] = ''; foreach ($courses as $course) { //delete link $deleteicon = html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/delete'), 'alt' => get_string('removecommunitycourse', 'block_community'))); $deleteurl = new moodle_url('/blocks/community/communitycourse.php', array('remove' => true, 'courseid' => $this->page->course->id, 'communityid' => $course->id, 'sesskey' => sesskey())); $deleteatag = html_writer::tag('a', $deleteicon, array('href' => $deleteurl)); $courselink = html_writer::tag('a', $course->coursename, array('href' => $course->courseurl)); $this->content->items[] = $courselink . ' ' . $deleteatag; $this->content->icons[] = ''; } } return $this->content; }
function backup_question_category_context($bf, $contextid, $course) { global $DB; $status = true; $context = get_context_instance_by_id($contextid); $status = $status && fwrite($bf, start_tag("CONTEXT", 4, true)); switch ($context->contextlevel) { case CONTEXT_MODULE: $status = $status && fwrite($bf, full_tag("LEVEL", 5, false, 'module')); $status = $status && fwrite($bf, full_tag("INSTANCE", 5, false, $context->instanceid)); break; case CONTEXT_COURSE: $status = $status && fwrite($bf, full_tag("LEVEL", 5, false, 'course')); break; case CONTEXT_COURSECAT: $thiscourse = $DB->get_record('course', array('id' => $course)); $cat = $thiscourse->category; $catno = 1; while ($context->instanceid != $cat) { $catno++; if ($cat == 0) { return false; } $cat = $DB->get_field('course_categories', 'parent', array('id' => $cat)); } $status = $status && fwrite($bf, full_tag("LEVEL", 5, false, 'coursecategory')); $status = $status && fwrite($bf, full_tag("COURSECATEGORYLEVEL", 5, false, $catno)); break; case CONTEXT_SYSTEM: $status = $status && fwrite($bf, full_tag("LEVEL", 5, false, 'system')); break; default: return false; } $status = $status && fwrite($bf, end_tag("CONTEXT", 4, true)); return $status; }
/** * Returns link to page which may be used to add new instance of enrolment plugin in course. * @param int $courseid * @return moodle_url page url */ public function get_newinstance_link($courseid) { global $DB; $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) { return NULL; } list($sqlparents, $params) = $DB->get_in_or_equal(get_parent_contexts($coursecontext)); $sql = "SELECT id, contextid\n FROM {cohort}\n WHERE contextid {$sqlparents}\n ORDER BY name ASC"; $cohorts = $DB->get_records_sql($sql, $params); $found = false; foreach ($cohorts as $c) { $context = get_context_instance_by_id($c->contextid); if (has_capability('moodle/cohort:view', $context)) { $found = true; break; } } if (!$found) { return NULL; } // multiple instances supported - multiple parent courses linked return new moodle_url('/enrol/cohort/addinstance.php', array('id' => $courseid)); }
/** * find and/or create the category described by a delimited list * e.g. $course$/tom/dick/harry or tom/dick/harry * * removes any context string no matter whether $getcontext is set * but if $getcontext is set then ignore the context and use selected category context. * * @param string catpath delimited category path * @param int courseid course to search for categories * @return mixed category object or null if fails */ protected function create_category_path($catpath) { global $DB; $catnames = $this->split_category_path($catpath); $parent = 0; $category = null; // check for context id in path, it might not be there in pre 1.9 exports $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches); if ($matchcount == 1) { $contextid = $this->translator->string_to_context($matches[1]); array_shift($catnames); } else { $contextid = false; } if ($this->contextfromfile && $contextid !== false) { $context = get_context_instance_by_id($contextid); require_capability('moodle/question:add', $context); } else { $context = get_context_instance_by_id($this->category->contextid); } // Now create any categories that need to be created. foreach ($catnames as $catname) { if ($category = $DB->get_record('question_categories', array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) { $parent = $category->id; } else { require_capability('moodle/question:managecategory', $context); // create the new category $category = new stdClass(); $category->contextid = $context->id; $category->name = $catname; $category->info = ''; $category->parent = $parent; $category->sortorder = 999; $category->stamp = make_unique_id_code(); $id = $DB->insert_record('question_categories', $category); $category->id = $id; $parent = $id; } } return $category; }
$extendperiod = optional_param('extendperiod', 0, PARAM_INT); $extendbase = optional_param('extendbase', 0, PARAM_INT); $userid = optional_param('userid', 0, PARAM_INT); // needed for user tabs $courseid = optional_param('courseid', 0, PARAM_INT); // needed for user tabs $errors = array(); $previoussearch = $searchtext != '' or $previoussearch ? 1 : 0; $baseurl = 'assign.php?contextid=' . $contextid; if (!empty($userid)) { $baseurl .= '&userid=' . $userid; } if (!empty($courseid)) { $baseurl .= '&courseid=' . $courseid; } if (!($context = get_context_instance_by_id($contextid))) { error("Context ID was incorrect (can't find it)"); } $inmeta = 0; if ($context->contextlevel == CONTEXT_COURSE) { $courseid = $context->instanceid; if ($course = get_record('course', 'id', $courseid)) { $inmeta = $course->metacourse; } else { error('Invalid course id'); } } else { if (!empty($courseid)) { // we need this for user tabs in user context if (!($course = get_record('course', 'id', $courseid))) { error('Invalid course id');
/** * add a single association for a blog entry * @param int contextid - id of context to associate with the blog entry */ public function add_association($contextid, $action = 'add') { global $DB, $USER; $assocobject = new StdClass(); $assocobject->contextid = $contextid; $assocobject->blogid = $this->id; $DB->insert_record('blog_association', $assocobject); $context = get_context_instance_by_id($contextid); $courseid = null; if ($context->contextlevel == CONTEXT_COURSE) { $courseid = $context->instanceid; add_to_log($courseid, 'blog', $action, 'index.php?userid=' . $this->userid . '&entryid=' . $this->id, $this->subject); } else { if ($context->contextlevel == CONTEXT_MODULE) { $cm = $DB->get_record('course_modules', array('id' => $context->instanceid)); $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module)); add_to_log($cm->course, 'blog', $action, 'index.php?userid=' . $this->userid . '&entryid=' . $this->id, $this->subject, $cm->id, $this->userid); } } }
function quiz_add_random_questions($quiz, $addonpage, $categoryid, $number, $includesubcategories) { global $DB; $category = $DB->get_record('question_categories', array('id' => $categoryid)); if (!$category) { print_error('invalidcategoryid', 'error'); } $catcontext = get_context_instance_by_id($category->contextid); require_capability('moodle/question:useall', $catcontext); // Find existing random questions in this category that are // not used by any quiz. if ($existingquestions = $DB->get_records_sql( "SELECT q.id, q.qtype FROM {question} q WHERE qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ? AND NOT EXISTS ( SELECT * FROM {quiz_question_instances} WHERE question = q.id) ORDER BY id", array($category->id, $includesubcategories))) { // Take as many of these as needed. while (($existingquestion = array_shift($existingquestions)) && $number > 0) { quiz_add_quiz_question($existingquestion->id, $quiz, $addonpage); $number -= 1; } } if ($number <= 0) { return; } // More random questions are needed, create them. for ($i = 0; $i < $number; $i += 1) { $form = new stdClass(); $form->questiontext = array('text' => $includesubcategories, 'format' => 0); $form->category = $category->id . ',' . $category->contextid; $form->defaultmark = 1; $form->hidden = 1; $form->stamp = make_unique_id_code(); // Set the unique code (not to be changed). $question = new stdClass(); $question->qtype = 'random'; $question = question_bank::get_qtype('random')->save_question($question, $form); if (!isset($question->id)) { print_error('cannotinsertrandomquestion', 'quiz'); } quiz_add_quiz_question($question->id, $quiz, $addonpage); } }
/** * Given a simple string, this function returns the string * processed by enabled string filters if $CFG->filterall is enabled * * This function should be used to print short strings (non html) that * need filter processing e.g. activity titles, post subjects, * glossary concepts. * * @global object * @global object * @global object * @staticvar bool $strcache * @param string $string The string to be filtered. * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713 * @param array $options options array/object or courseid * @return string */ function format_string($string, $striplinks = true, $options = NULL) { global $CFG, $COURSE, $PAGE; //We'll use a in-memory cache here to speed up repeated strings static $strcache = false; if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) { // do not filter anything during installation or before upgrade completes return $string = strip_tags($string); } if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron $strcache = array(); } if (is_numeric($options)) { // legacy courseid usage $options = array('context' => get_context_instance(CONTEXT_COURSE, $options)); } else { $options = (array) $options; // detach object, we can not modify it } if (empty($options['context'])) { // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-( $options['context'] = $PAGE->context; } else { if (is_numeric($options['context'])) { $options['context'] = get_context_instance_by_id($options['context']); } } if (!$options['context']) { // we did not find any context? weird return $string = strip_tags($string); } //Calculate md5 $md5 = md5($string . '<+>' . $striplinks . '<+>' . $options['context']->id . '<+>' . current_language()); //Fetch from cache if possible if (isset($strcache[$md5])) { return $strcache[$md5]; } // First replace all ampersands not followed by html entity code // Regular expression moved to its own method for easier unit testing $string = replace_ampersands_not_followed_by_entity($string); if (!empty($CFG->filterall)) { $string = filter_manager::instance()->filter_string($string, $options['context']); } // If the site requires it, strip ALL tags from this string if (!empty($CFG->formatstringstriptags)) { $string = strip_tags($string); } else { // Otherwise strip just links if that is required (default) if ($striplinks) { //strip links in string $string = strip_links($string); } $string = clean_text($string); } //Store to cache $strcache[$md5] = $string; return $string; }
$questionid = optional_param('questionid', 0, PARAM_INT); $confirm = optional_param('confirm', 0, PARAM_INT); // Check the user is logged in. require_login(); $context = get_context_instance(CONTEXT_SYSTEM); require_capability('moodle/question:config', $context); admin_externalpage_setup('qtypeddmarkerfromimagetarget'); // Header. $renderer = $PAGE->get_renderer('qtype_ddmarker', 'list'); echo $renderer->header(); echo $renderer->heading(get_string('imagetargetconverter', 'qtype_ddmarker'), 2); $params = array(); $from = 'FROM {question_categories} cat, {question} q'; $where = ' WHERE q.qtype = \'imagetarget\' AND q.category = cat.id '; if ($qcontextid) { $qcontext = get_context_instance_by_id($qcontextid, MUST_EXIST); $from .= ', {context} context'; $where .= 'AND cat.contextid = context.id AND (context.path LIKE :path OR context.id = :id) '; $params['path'] = $qcontext->path . '/%'; $params['id'] = $qcontext->id; } else { if ($categoryid) { //fetch all questions from this cats context $from .= ', {question_categories} cat2'; $where .= 'AND cat.contextid = cat2.contextid AND cat2.id = :categoryid '; $params['categoryid'] = $categoryid; } else { if ($questionid) { //fetch all questions from this cats context $where .= 'AND q.id = :questionid '; $params['questionid'] = $questionid;