public function test_get_public_config() { global $CFG, $SITE, $OUTPUT; $this->resetAfterTest(true); $result = external::get_public_config(); $result = external_api::clean_returnvalue(external::get_public_config_returns(), $result); // Test default values. $context = context_system::instance(); list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id); list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id); $expected = array('wwwroot' => $CFG->wwwroot, 'httpswwwroot' => $CFG->httpswwwroot, 'sitename' => external_format_string($SITE->fullname, $context->id, true), 'guestlogin' => $CFG->guestloginbutton, 'rememberusername' => $CFG->rememberusername, 'authloginviaemail' => $CFG->authloginviaemail, 'registerauth' => $CFG->registerauth, 'forgottenpasswordurl' => $CFG->forgottenpasswordurl, 'authinstructions' => $authinstructions, 'authnoneenabled' => (int) is_enabled_auth('none'), 'enablewebservices' => $CFG->enablewebservices, 'enablemobilewebservice' => $CFG->enablemobilewebservice, 'maintenanceenabled' => $CFG->maintenance_enabled, 'maintenancemessage' => $maintenancemessage, 'typeoflogin' => api::LOGIN_VIA_APP, 'warnings' => array()); $this->assertEquals($expected, $result); // Change some values. set_config('registerauth', 'email'); $authinstructions = 'Something with <b>html tags</b>'; set_config('auth_instructions', $authinstructions); set_config('typeoflogin', api::LOGIN_VIA_BROWSER, 'tool_mobile'); set_config('logo', 'mock.png', 'core_admin'); set_config('logocompact', 'mock.png', 'core_admin'); list($authinstructions, $notusedformat) = external_format_text($authinstructions, FORMAT_MOODLE, $context->id); $expected['registerauth'] = 'email'; $expected['authinstructions'] = $authinstructions; $expected['typeoflogin'] = api::LOGIN_VIA_BROWSER; $expected['launchurl'] = "{$CFG->wwwroot}/{$CFG->admin}/tool/mobile/launch.php"; if ($logourl = $OUTPUT->get_logo_url()) { $expected['logourl'] = $logourl->out(false); } if ($compactlogourl = $OUTPUT->get_compact_logo_url()) { $expected['compactlogourl'] = $compactlogourl->out(false); } $result = external::get_public_config(); $result = external_api::clean_returnvalue(external::get_public_config_returns(), $result); $this->assertEquals($expected, $result); }
/** * Returns a list of glossaries in a provided list of courses. * * If no list is provided all glossaries that the user can view will be returned. * * @param array $courseids the course IDs. * @return array of glossaries * @since Moodle 3.1 */ public static function get_glossaries_by_courses($courseids = array()) { $params = self::validate_parameters(self::get_glossaries_by_courses_parameters(), array('courseids' => $courseids)); $warnings = array(); $courses = array(); $courseids = $params['courseids']; if (empty($courseids)) { $courses = enrol_get_my_courses(); $courseids = array_keys($courses); } // Array to store the glossaries to return. $glossaries = array(); // Ensure there are courseids to loop through. if (!empty($courseids)) { list($courses, $warnings) = external_util::validate_courses($courseids, $courses); // Get the glossaries in these courses, this function checks users visibility permissions. $glossaries = get_all_instances_in_courses('glossary', $courses); foreach ($glossaries as $glossary) { $context = context_module::instance($glossary->coursemodule); $glossary->name = external_format_string($glossary->name, $context->id); list($glossary->intro, $glossary->introformat) = external_format_text($glossary->intro, $glossary->introformat, $context->id, 'mod_glossary', 'intro', null); } } $result = array(); $result['glossaries'] = $glossaries; $result['warnings'] = $warnings; return $result; }
/** * Returns a list of the site public settings, those not requiring authentication. * * @return array with the settings and warnings */ public static function get_site_public_settings() { global $CFG, $SITE, $PAGE; $context = context_system::instance(); // We need this to make work the format text functions. $PAGE->set_context($context); $settings = array('wwwroot' => $CFG->wwwroot, 'httpswwwroot' => $CFG->httpswwwroot, 'sitename' => external_format_string($SITE->fullname, $context->id, true), 'guestlogin' => $CFG->guestloginbutton, 'rememberusername' => $CFG->rememberusername, 'authloginviaemail' => $CFG->authloginviaemail, 'registerauth' => $CFG->registerauth, 'forgottenpasswordurl' => $CFG->forgottenpasswordurl, 'authinstructions' => format_text($CFG->auth_instructions), 'authnoneenabled' => (int) is_enabled_auth('none'), 'enablewebservices' => $CFG->enablewebservices, 'enablemobilewebservice' => $CFG->enablemobilewebservice, 'maintenanceenabled' => $CFG->maintenance_enabled, 'maintenancemessage' => format_text($CFG->maintenance_message)); return $settings; }
/** * Returns a list of surveys in a provided list of courses, * if no list is provided all surveys that the user can view will be returned. * * @param array $courseids the course ids * @return array of surveys details * @since Moodle 3.0 */ public static function get_surveys_by_courses($courseids = array()) { global $CFG, $USER, $DB; $returnedsurveys = array(); $warnings = array(); $params = self::validate_parameters(self::get_surveys_by_courses_parameters(), array('courseids' => $courseids)); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the surveys in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $surveys = get_all_instances_in_courses("survey", $courses); foreach ($surveys as $survey) { $context = context_module::instance($survey->coursemodule); // Entry to return. $surveydetails = array(); // First, we return information that any user can see in the web interface. $surveydetails['id'] = $survey->id; $surveydetails['coursemodule'] = $survey->coursemodule; $surveydetails['course'] = $survey->course; $surveydetails['name'] = external_format_string($survey->name, $context->id); if (has_capability('mod/survey:participate', $context)) { $trimmedintro = trim($survey->intro); if (empty($trimmedintro)) { $tempo = $DB->get_field("survey", "intro", array("id" => $survey->template)); $survey->intro = get_string($tempo, "survey"); } // Format intro. list($surveydetails['intro'], $surveydetails['introformat']) = external_format_text($survey->intro, $survey->introformat, $context->id, 'mod_survey', 'intro', null); $surveydetails['introfiles'] = external_util::get_area_files($context->id, 'mod_survey', 'intro', false, false); $surveydetails['template'] = $survey->template; $surveydetails['days'] = $survey->days; $surveydetails['questions'] = $survey->questions; $surveydetails['surveydone'] = survey_already_done($survey->id, $USER->id) ? 1 : 0; } if (has_capability('moodle/course:manageactivities', $context)) { $surveydetails['timecreated'] = $survey->timecreated; $surveydetails['timemodified'] = $survey->timemodified; $surveydetails['section'] = $survey->section; $surveydetails['visible'] = $survey->visible; $surveydetails['groupmode'] = $survey->groupmode; $surveydetails['groupingid'] = $survey->groupingid; } $returnedsurveys[] = $surveydetails; } } $result = array(); $result['surveys'] = $returnedsurveys; $result['warnings'] = $warnings; return $result; }
protected function get_other_values(renderer_base $output) { $cm = $this->related['cm']; $context = $cm->context; $values = array('id' => $cm->id, 'name' => external_format_string($cm->name, $context->id), 'iconurl' => $cm->get_icon_url()->out()); if ($cm->url) { $values['url'] = $cm->url->out(); } return $values; }
/** * Returns a list of wikis in a provided list of courses, * if no list is provided all wikis that the user can view will be returned. * * @param array $courseids The courses IDs. * @return array Containing a list of warnings and a list of wikis. * @since Moodle 3.1 */ public static function get_wikis_by_courses($courseids = array()) { $returnedwikis = array(); $warnings = array(); $params = self::validate_parameters(self::get_wikis_by_courses_parameters(), array('courseids' => $courseids)); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the wikis in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $wikis = get_all_instances_in_courses('wiki', $courses); foreach ($wikis as $wiki) { $context = context_module::instance($wiki->coursemodule); // Entry to return. $module = array(); // First, we return information that any user can see in (or can deduce from) the web interface. $module['id'] = $wiki->id; $module['coursemodule'] = $wiki->coursemodule; $module['course'] = $wiki->course; $module['name'] = external_format_string($wiki->name, $context->id); $viewablefields = []; if (has_capability('mod/wiki:viewpage', $context)) { list($module['intro'], $module['introformat']) = external_format_text($wiki->intro, $wiki->introformat, $context->id, 'mod_wiki', 'intro', $wiki->id); $viewablefields = array('firstpagetitle', 'wikimode', 'defaultformat', 'forceformat', 'editbegin', 'editend', 'section', 'visible', 'groupmode', 'groupingid'); } // Check additional permissions for returning optional private settings. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('timecreated', 'timemodified'); $viewablefields = array_merge($viewablefields, $additionalfields); } foreach ($viewablefields as $field) { $module[$field] = $wiki->{$field}; } // Check if user can add new pages. $module['cancreatepages'] = wiki_can_create_pages($context); $returnedwikis[] = $module; } } $result = array(); $result['wikis'] = $returnedwikis; $result['warnings'] = $warnings; return $result; }
public function test_get_site_public_settings() { global $CFG, $SITE; $this->resetAfterTest(true); $result = external::get_site_public_settings(); $result = external_api::clean_returnvalue(external::get_site_public_settings_returns(), $result); // Test default values. $context = context_system::instance(); $expected = array('wwwroot' => $CFG->wwwroot, 'httpswwwroot' => $CFG->httpswwwroot, 'sitename' => external_format_string($SITE->fullname, $context->id, true), 'guestlogin' => $CFG->guestloginbutton, 'rememberusername' => $CFG->rememberusername, 'authloginviaemail' => $CFG->authloginviaemail, 'registerauth' => $CFG->registerauth, 'forgottenpasswordurl' => $CFG->forgottenpasswordurl, 'authinstructions' => format_text($CFG->auth_instructions), 'authnoneenabled' => (int) is_enabled_auth('none'), 'enablewebservices' => $CFG->enablewebservices, 'enablemobilewebservice' => $CFG->enablemobilewebservice, 'maintenanceenabled' => $CFG->maintenance_enabled, 'maintenancemessage' => format_text($CFG->maintenance_message), 'warnings' => array()); $this->assertEquals($expected, $result); // Change a value. set_config('registerauth', 'email'); $authinstructions = 'Something with <b>html tags</b>'; set_config('auth_instructions', $authinstructions); $expected['registerauth'] = 'email'; $expected['authinstructions'] = format_text($authinstructions); $result = external::get_site_public_settings(); $result = external_api::clean_returnvalue(external::get_site_public_settings_returns(), $result); $this->assertEquals($expected, $result); }
/** * Returns a list of forums in a provided list of courses, * if no list is provided all forums that the user can view * will be returned. * * @param array $courseids the course ids * @return array the forum details * @since Moodle 2.5 */ public static function get_forums_by_courses($courseids = array()) { global $CFG; require_once $CFG->dirroot . "/mod/forum/lib.php"; $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids)); $courses = array(); if (empty($params['courseids'])) { $courses = enrol_get_my_courses(); $params['courseids'] = array_keys($courses); } // Array to store the forums to return. $arrforums = array(); $warnings = array(); // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses); // Get the forums in this course. This function checks users visibility permissions. $forums = get_all_instances_in_courses("forum", $courses); foreach ($forums as $forum) { $course = $courses[$forum->course]; $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id); $context = context_module::instance($cm->id); // Skip forums we are not allowed to see discussions. if (!has_capability('mod/forum:viewdiscussion', $context)) { continue; } $forum->name = external_format_string($forum->name, $context->id); // Format the intro before being returning using the format setting. list($forum->intro, $forum->introformat) = external_format_text($forum->intro, $forum->introformat, $context->id, 'mod_forum', 'intro', 0); $forum->introfiles = external_util::get_area_files($context->id, 'mod_forum', 'intro', false, false); // Discussions count. This function does static request cache. $forum->numdiscussions = forum_count_discussions($forum, $cm, $course); $forum->cmid = $forum->coursemodule; $forum->cancreatediscussions = forum_user_can_post_discussion($forum, null, -1, $cm, $context); // Add the forum to the array to return. $arrforums[$forum->id] = $forum; } } return $arrforums; }
/** * Returns a list of databases in a provided list of courses, * if no list is provided all databases that the user can view will be returned. * * @param array $courseids the course ids * @return array the database details * @since Moodle 2.9 */ public static function get_databases_by_courses($courseids = array()) { global $CFG; $params = self::validate_parameters(self::get_databases_by_courses_parameters(), array('courseids' => $courseids)); $warnings = array(); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Array to store the databases to return. $arrdatabases = array(); // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($dbcourses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the databases in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $databases = get_all_instances_in_courses("data", $dbcourses); foreach ($databases as $database) { $datacontext = context_module::instance($database->coursemodule); // Entry to return. $newdb = array(); // First, we return information that any user can see in the web interface. $newdb['id'] = $database->id; $newdb['coursemodule'] = $database->coursemodule; $newdb['course'] = $database->course; $newdb['name'] = external_format_string($database->name, $datacontext->id); // Format intro. list($newdb['intro'], $newdb['introformat']) = external_format_text($database->intro, $database->introformat, $datacontext->id, 'mod_data', 'intro', null); $newdb['introfiles'] = external_util::get_area_files($datacontext->id, 'mod_data', 'intro', false, false); // This information should be only available if the user can see the database entries. if (has_capability('mod/data:viewentry', $datacontext)) { $viewablefields = array('comments', 'timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto', 'requiredentries', 'requiredentriestoview'); // This is for avoid a long repetitive list and for // checking that we are retrieving all the required fields. foreach ($viewablefields as $field) { // We do not use isset because it won't work for existing null values. if (!property_exists($database, $field)) { throw new invalid_response_exception('Missing database module required field: ' . $field); } $newdb[$field] = $database->{$field}; } } // Check additional permissions for returning optional private settings. // I avoid intentionally to use can_[add|update]_moduleinfo. if (has_capability('moodle/course:manageactivities', $datacontext)) { $additionalfields = array('maxentries', 'rssarticles', 'singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter', 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate', 'asearchtemplate', 'approval', 'manageapproved', 'scale', 'assessed', 'assesstimestart', 'assesstimefinish', 'defaultsort', 'defaultsortdir', 'editany', 'notification', 'timemodified'); // This is for avoid a long repetitive list. foreach ($additionalfields as $field) { if (property_exists($database, $field)) { $newdb[$field] = $database->{$field}; } } } $arrdatabases[] = $newdb; } } $result = array(); $result['databases'] = $arrdatabases; $result['warnings'] = $warnings; return $result; }
/** * Browse a glossary entries by category. * * @param int $id The glossary ID. * @param int $categoryid The category ID. * @param int $from Start returning records from here. * @param int $limit Number of records to return. * @param array $options Array of options. * @return array Containing count, entries and warnings. * @since Moodle 3.1 * @throws moodle_exception * @throws invalid_parameter_exception */ public static function get_entries_by_category($id, $categoryid, $from, $limit, $options) { global $DB; $params = self::validate_parameters(self::get_entries_by_category_parameters(), array('id' => $id, 'categoryid' => $categoryid, 'from' => $from, 'limit' => $limit, 'options' => $options)); $id = $params['id']; $categoryid = $params['categoryid']; $from = $params['from']; $limit = $params['limit']; $options = $params['options']; $warnings = array(); // Get and validate the glossary. list($glossary, $context) = self::validate_glossary($id); // Validate the mode. $modes = self::get_browse_modes_from_display_format($glossary->displayformat); if (!in_array('cat', $modes)) { throw new invalid_parameter_exception('invalidbrowsemode'); } // Validate the category. if (in_array($categoryid, array(GLOSSARY_SHOW_ALL_CATEGORIES, GLOSSARY_SHOW_NOT_CATEGORISED))) { // All good. } else { if (!$DB->record_exists('glossary_categories', array('id' => $categoryid, 'glossaryid' => $id))) { throw new invalid_parameter_exception('invalidcategory'); } } // Fetching the entries. $entries = array(); list($records, $count) = glossary_get_entries_by_category($glossary, $context, $categoryid, $from, $limit, $options); foreach ($records as $key => $record) { self::fill_entry_details($record, $context); if ($record->categoryid === null) { $record->categoryid = GLOSSARY_SHOW_NOT_CATEGORISED; } if (isset($record->categoryname)) { $record->categoryname = external_format_string($record->categoryname, $context->id); } $entries[] = $record; } return array('count' => $count, 'entries' => $entries, 'warnings' => $warnings); }
/** * Function to export the renderer data in a format that is suitable for a * mustache template. This means raw records are generated as in to_record, * but all strings are correctly passed through external_format_text (or external_format_string). * * @param renderer_base $output Used to do a final render of any components that need to be rendered for export. * @return stdClass */ public final function export(renderer_base $output) { $data = new stdClass(); $properties = self::read_properties_definition(); $context = $this->get_context(); $values = (array) $this->data; $othervalues = $this->get_other_values($output); if (array_intersect_key($values, $othervalues)) { // Attempt to replace a standard property. throw new coding_exception('Cannot override a standard property value.'); } $values += $othervalues; $record = (object) $values; foreach ($properties as $property => $definition) { if (isset($data->{$property})) { // This happens when we have already defined the format properties. continue; } else { if (!property_exists($record, $property) && array_key_exists('default', $definition)) { // We have a default value for this property. $record->{$property} = $definition['default']; } else { if (!property_exists($record, $property) && !empty($definition['optional'])) { // Fine, this property can be omitted. continue; } else { if (!property_exists($record, $property)) { // Whoops, we got something that wasn't defined. throw new coding_exception('Unexpected property ' . $property); } } } } $data->{$property} = $record->{$property}; // If the field is PARAM_RAW and has a format field. if ($propertyformat = self::get_format_field($properties, $property)) { if (!property_exists($record, $propertyformat)) { // Whoops, we got something that wasn't defined. throw new coding_exception('Unexpected property ' . $propertyformat); } $format = $record->{$propertyformat}; list($text, $format) = external_format_text($data->{$property}, $format, $context->id, 'core_competency', '', 0); $data->{$property} = $text; $data->{$propertyformat} = $format; } else { if ($definition['type'] === PARAM_TEXT) { if (!empty($definition['multiple'])) { foreach ($data->{$property} as $key => $value) { $data->{$property}[$key] = external_format_string($value, $context->id); } } else { $data->{$property} = external_format_string($data->{$property}, $context->id); } } } } return $data; }
/** * Return information about a course module. * * @param int $cmid the course module id * @return array of warnings and the course module * @since Moodle 3.0 * @throws moodle_exception */ public static function get_course_module($cmid) { $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid)); $warnings = array(); $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST); $context = context_module::instance($cm->id); self::validate_context($context); // If the user has permissions to manage the activity, return all the information. if (has_capability('moodle/course:manageactivities', $context)) { $info = $cm; } else { // Return information is safe to show to any user. $info = new stdClass(); $info->id = $cm->id; $info->course = $cm->course; $info->module = $cm->module; $info->modname = $cm->modname; $info->instance = $cm->instance; $info->section = $cm->section; $info->sectionnum = $cm->sectionnum; $info->groupmode = $cm->groupmode; $info->groupingid = $cm->groupingid; $info->completion = $cm->completion; } // Format name. $info->name = external_format_string($cm->name, $context->id); $result = array(); $result['cm'] = $info; $result['warnings'] = $warnings; return $result; }
/** * Return information about a course module. * * @param int $cmid the course module id * @return array of warnings and the course module * @since Moodle 3.0 * @throws moodle_exception */ public static function get_course_module($cmid) { global $CFG, $DB; $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid)); $warnings = array(); $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST); $context = context_module::instance($cm->id); self::validate_context($context); // If the user has permissions to manage the activity, return all the information. if (has_capability('moodle/course:manageactivities', $context)) { require_once $CFG->dirroot . '/course/modlib.php'; require_once $CFG->libdir . '/gradelib.php'; $info = $cm; // Get the extra information: grade, advanced grading and outcomes data. $course = get_course($cm->course); list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course); // Grades. $gradeinfo = array('grade', 'gradepass', 'gradecat'); foreach ($gradeinfo as $gfield) { if (isset($extrainfo->{$gfield})) { $info->{$gfield} = $extrainfo->{$gfield}; } } if (isset($extrainfo->grade) and $extrainfo->grade < 0) { $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade))); } // Advanced grading. if (isset($extrainfo->_advancedgradingdata)) { $info->advancedgrading = array(); foreach ($extrainfo as $key => $val) { if (strpos($key, 'advancedgradingmethod_') === 0) { $info->advancedgrading[] = array('area' => str_replace('advancedgradingmethod_', '', $key), 'method' => $val); } } } // Outcomes. foreach ($extrainfo as $key => $val) { if (strpos($key, 'outcome_') === 0) { if (!isset($info->outcomes)) { $info->outcomes = array(); } $id = str_replace('outcome_', '', $key); $outcome = grade_outcome::fetch(array('id' => $id)); $scaleitems = $outcome->load_scale(); $info->outcomes[] = array('id' => $id, 'name' => external_format_string($outcome->get_name(), $context->id), 'scale' => $scaleitems->scale); } } } else { // Return information is safe to show to any user. $info = new stdClass(); $info->id = $cm->id; $info->course = $cm->course; $info->module = $cm->module; $info->modname = $cm->modname; $info->instance = $cm->instance; $info->section = $cm->section; $info->sectionnum = $cm->sectionnum; $info->groupmode = $cm->groupmode; $info->groupingid = $cm->groupingid; $info->completion = $cm->completion; } // Format name. $info->name = external_format_string($cm->name, $context->id); $result = array(); $result['cm'] = $info; $result['warnings'] = $warnings; return $result; }
/** * Returns an array of courses the user is enrolled, and for each course all of the assignments that the user can * view within that course. * * @param array $courseids An optional array of course ids. If provided only assignments within the given course * will be returned. If the user is not enrolled in or can't view a given course a warning will be generated and returned. * @param array $capabilities An array of additional capability checks you wish to be made on the course context. * @param bool $includenotenrolledcourses Wheter to return courses that the user can see even if is not enroled in. * This requires the parameter $courseids to not be empty. * @return An array of courses and warnings. * @since Moodle 2.4 */ public static function get_assignments($courseids = array(), $capabilities = array(), $includenotenrolledcourses = false) { global $USER, $DB, $CFG; $params = self::validate_parameters(self::get_assignments_parameters(), array('courseids' => $courseids, 'capabilities' => $capabilities, 'includenotenrolledcourses' => $includenotenrolledcourses)); $warnings = array(); $courses = array(); $fields = 'sortorder,shortname,fullname,timemodified'; // If the courseids list is empty, we return only the courses where the user is enrolled in. if (empty($params['courseids'])) { $courses = enrol_get_users_courses($USER->id, true, $fields); $courseids = array_keys($courses); } else { if ($includenotenrolledcourses) { // In this case, we don't have to check here for enrolmnents. Maybe the user can see the course even if is not enrolled. $courseids = $params['courseids']; } else { // We need to check for enrolments. $mycourses = enrol_get_users_courses($USER->id, true, $fields); $mycourseids = array_keys($mycourses); foreach ($params['courseids'] as $courseid) { if (!in_array($courseid, $mycourseids)) { unset($courses[$courseid]); $warnings[] = array('item' => 'course', 'itemid' => $courseid, 'warningcode' => '2', 'message' => 'User is not enrolled or does not have requested capability'); } else { $courses[$courseid] = $mycourses[$courseid]; } } $courseids = array_keys($courses); } } foreach ($courseids as $cid) { try { $context = context_course::instance($cid); self::validate_context($context); // Check if this course was already loaded (by enrol_get_users_courses). if (!isset($courses[$cid])) { $courses[$cid] = get_course($cid); } $courses[$cid]->contextid = $context->id; } catch (Exception $e) { unset($courses[$cid]); $warnings[] = array('item' => 'course', 'itemid' => $cid, 'warningcode' => '1', 'message' => 'No access rights in course context ' . $e->getMessage()); continue; } if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) { unset($courses[$cid]); } } $extrafields = 'm.id as assignmentid, ' . 'm.course, ' . 'm.nosubmissions, ' . 'm.submissiondrafts, ' . 'm.sendnotifications, ' . 'm.sendlatenotifications, ' . 'm.sendstudentnotifications, ' . 'm.duedate, ' . 'm.allowsubmissionsfromdate, ' . 'm.grade, ' . 'm.timemodified, ' . 'm.completionsubmit, ' . 'm.cutoffdate, ' . 'm.teamsubmission, ' . 'm.requireallteammemberssubmit, ' . 'm.teamsubmissiongroupingid, ' . 'm.blindmarking, ' . 'm.revealidentities, ' . 'm.attemptreopenmethod, ' . 'm.maxattempts, ' . 'm.markingworkflow, ' . 'm.markingallocation, ' . 'm.requiresubmissionstatement, ' . 'm.preventsubmissionnotingroup, ' . 'm.intro, ' . 'm.introformat'; $coursearray = array(); foreach ($courses as $id => $course) { $assignmentarray = array(); // Get a list of assignments for the course. if ($modules = get_coursemodules_in_course('assign', $courses[$id]->id, $extrafields)) { foreach ($modules as $module) { $context = context_module::instance($module->id); try { self::validate_context($context); require_capability('mod/assign:view', $context); } catch (Exception $e) { $warnings[] = array('item' => 'module', 'itemid' => $module->id, 'warningcode' => '1', 'message' => 'No access rights in module context'); continue; } $assign = new assign($context, null, null); // Get configurations for only enabled plugins. $plugins = $assign->get_submission_plugins(); $plugins = array_merge($plugins, $assign->get_feedback_plugins()); $configarray = array(); foreach ($plugins as $plugin) { if ($plugin->is_enabled() && $plugin->is_visible()) { $configrecords = $plugin->get_config_for_external(); foreach ($configrecords as $name => $value) { $configarray[] = array('plugin' => $plugin->get_type(), 'subtype' => $plugin->get_subtype(), 'name' => $name, 'value' => $value); } } } $assignment = array('id' => $module->assignmentid, 'cmid' => $module->id, 'course' => $module->course, 'name' => $module->name, 'nosubmissions' => $module->nosubmissions, 'submissiondrafts' => $module->submissiondrafts, 'sendnotifications' => $module->sendnotifications, 'sendlatenotifications' => $module->sendlatenotifications, 'sendstudentnotifications' => $module->sendstudentnotifications, 'duedate' => $module->duedate, 'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate, 'grade' => $module->grade, 'timemodified' => $module->timemodified, 'completionsubmit' => $module->completionsubmit, 'cutoffdate' => $module->cutoffdate, 'teamsubmission' => $module->teamsubmission, 'requireallteammemberssubmit' => $module->requireallteammemberssubmit, 'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid, 'blindmarking' => $module->blindmarking, 'revealidentities' => $module->revealidentities, 'attemptreopenmethod' => $module->attemptreopenmethod, 'maxattempts' => $module->maxattempts, 'markingworkflow' => $module->markingworkflow, 'markingallocation' => $module->markingallocation, 'requiresubmissionstatement' => $module->requiresubmissionstatement, 'preventsubmissionnotingroup' => $module->preventsubmissionnotingroup, 'configs' => $configarray); // Return or not intro and file attachments depending on the plugin settings. if ($assign->show_intro()) { list($assignment['intro'], $assignment['introformat']) = external_format_text($module->intro, $module->introformat, $context->id, 'mod_assign', 'intro', null); $assignment['introfiles'] = external_util::get_area_files($context->id, 'mod_assign', 'intro', false, false); $assignment['introattachments'] = external_util::get_area_files($context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0); } if ($module->requiresubmissionstatement) { // Submission statement is required, return the submission statement value. $adminconfig = get_config('assign'); list($assignment['submissionstatement'], $assignment['submissionstatementformat']) = external_format_text($adminconfig->submissionstatement, FORMAT_MOODLE, $context->id, 'mod_assign', '', 0); } $assignmentarray[] = $assignment; } } $coursearray[] = array('id' => $courses[$id]->id, 'fullname' => external_format_string($courses[$id]->fullname, $course->contextid), 'shortname' => external_format_string($courses[$id]->shortname, $course->contextid), 'timemodified' => $courses[$id]->timemodified, 'assignments' => $assignmentarray); } $result = array('courses' => $coursearray, 'warnings' => $warnings); return $result; }
/** * Get list of courses user is enrolled in (only active enrolments are returned). * Please note the current user must be able to access the course, otherwise the course is not included. * * @param int $userid * @return array of courses */ public static function get_users_courses($userid) { global $USER, $DB; // Do basic automatic PARAM checks on incoming data, using params description // If any problems are found then exceptions are thrown with helpful error messages $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid' => $userid)); $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible, summary, summaryformat, format, showgrades, lang, enablecompletion, category'); $result = array(); foreach ($courses as $course) { $context = context_course::instance($course->id, IGNORE_MISSING); try { self::validate_context($context); } catch (Exception $e) { // current user can not access this course, sorry we can not disclose who is enrolled in this course! continue; } if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) { // we need capability to view participants continue; } list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context); $enrolledsql = "SELECT COUNT('x') FROM ({$enrolledsqlselect}) enrolleduserids"; $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams); list($course->summary, $course->summaryformat) = external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', null); $course->fullname = external_format_string($course->fullname, $context->id); $course->shortname = external_format_string($course->shortname, $context->id); $result[] = array('id' => $course->id, 'shortname' => $course->shortname, 'fullname' => $course->fullname, 'idnumber' => $course->idnumber, 'visible' => $course->visible, 'enrolledusercount' => $enrolledusercount, 'summary' => $course->summary, 'summaryformat' => $course->summaryformat, 'format' => $course->format, 'showgrades' => $course->showgrades, 'lang' => $course->lang, 'enablecompletion' => $course->enablecompletion, 'category' => $course->category); } return $result; }
/** * Returns a list of books in a provided list of courses, * if no list is provided all books that the user can view will be returned. * * @param array $courseids the course ids * @return array of books details * @since Moodle 3.0 */ public static function get_books_by_courses($courseids = array()) { global $CFG; $returnedbooks = array(); $warnings = array(); $params = self::validate_parameters(self::get_books_by_courses_parameters(), array('courseids' => $courseids)); $courses = array(); if (empty($params['courseids'])) { $courses = enrol_get_my_courses(); $params['courseids'] = array_keys($courses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses); // Get the books in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $books = get_all_instances_in_courses("book", $courses); foreach ($books as $book) { $context = context_module::instance($book->coursemodule); // Entry to return. $bookdetails = array(); // First, we return information that any user can see in the web interface. $bookdetails['id'] = $book->id; $bookdetails['coursemodule'] = $book->coursemodule; $bookdetails['course'] = $book->course; $bookdetails['name'] = external_format_string($book->name, $context->id); // Format intro. list($bookdetails['intro'], $bookdetails['introformat']) = external_format_text($book->intro, $book->introformat, $context->id, 'mod_book', 'intro', null); $bookdetails['numbering'] = $book->numbering; $bookdetails['navstyle'] = $book->navstyle; $bookdetails['customtitles'] = $book->customtitles; if (has_capability('moodle/course:manageactivities', $context)) { $bookdetails['revision'] = $book->revision; $bookdetails['timecreated'] = $book->timecreated; $bookdetails['timemodified'] = $book->timemodified; $bookdetails['section'] = $book->section; $bookdetails['visible'] = $book->visible; $bookdetails['groupmode'] = $book->groupmode; $bookdetails['groupingid'] = $book->groupingid; } $returnedbooks[] = $bookdetails; } } $result = array(); $result['books'] = $returnedbooks; $result['warnings'] = $warnings; return $result; }
/** * Returns a list of scorms in a provided list of courses, * if no list is provided all scorms that the user can view will be returned. * * @param array $courseids the course ids * @return array the scorm details * @since Moodle 3.0 */ public static function get_scorms_by_courses($courseids = array()) { global $CFG; $returnedscorms = array(); $warnings = array(); $params = self::validate_parameters(self::get_scorms_by_courses_parameters(), array('courseids' => $courseids)); $courses = array(); if (empty($params['courseids'])) { $courses = enrol_get_my_courses(); $params['courseids'] = array_keys($courses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses); // Get the scorms in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $scorms = get_all_instances_in_courses("scorm", $courses); $fs = get_file_storage(); foreach ($scorms as $scorm) { $context = context_module::instance($scorm->coursemodule); // Entry to return. $module = array(); // First, we return information that any user can see in (or can deduce from) the web interface. $module['id'] = $scorm->id; $module['coursemodule'] = $scorm->coursemodule; $module['course'] = $scorm->course; $module['name'] = external_format_string($scorm->name, $context->id); list($module['intro'], $module['introformat']) = external_format_text($scorm->intro, $scorm->introformat, $context->id, 'mod_scorm', 'intro', $scorm->id); // Check if the SCORM open and return warnings if so. list($open, $openwarnings) = scorm_get_availability_status($scorm, true, $context); if (!$open) { foreach ($openwarnings as $warningkey => $warningdata) { $warnings[] = array('item' => 'scorm', 'itemid' => $scorm->id, 'warningcode' => $warningkey, 'message' => get_string($warningkey, 'scorm', $warningdata)); } } else { $module['packagesize'] = 0; // SCORM size. if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) { if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) { $module['packagesize'] = $packagefile->get_filesize(); // Download URL. $module['packageurl'] = moodle_url::make_webservice_pluginfile_url($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)->out(false); } } $module['protectpackagedownloads'] = get_config('scorm', 'protectpackagedownloads'); $viewablefields = array('version', 'maxgrade', 'grademethod', 'whatgrade', 'maxattempt', 'forcecompleted', 'forcenewattempt', 'lastattemptlock', 'displayattemptstatus', 'displaycoursestructure', 'sha1hash', 'md5hash', 'revision', 'launch', 'skipview', 'hidebrowse', 'hidetoc', 'nav', 'navpositionleft', 'navpositiontop', 'auto', 'popup', 'width', 'height', 'timeopen', 'timeclose', 'displayactivityname', 'scormtype', 'reference'); // Check additional permissions for returning optional private settings. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('updatefreq', 'options', 'completionstatusrequired', 'completionscorerequired', 'autocommit', 'timemodified', 'section', 'visible', 'groupmode', 'groupingid'); $viewablefields = array_merge($viewablefields, $additionalfields); } foreach ($viewablefields as $field) { $module[$field] = $scorm->{$field}; } } $returnedscorms[] = $module; } } $result = array(); $result['scorms'] = $returnedscorms; $result['warnings'] = $warnings; return $result; }
/** * Returns a list of forum discussions optionally sorted and paginated. * * @param int $forumid the forum instance id * @param string $sortby sort by this element (id, timemodified, timestart or timeend) * @param string $sortdirection sort direction: ASC or DESC * @param int $page page number * @param int $perpage items per page * * @return array the forum discussion details including warnings * @since Moodle 2.8 */ public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC', $page = -1, $perpage = 0) { global $CFG, $DB, $USER, $PAGE; require_once $CFG->dirroot . "/mod/forum/lib.php"; $warnings = array(); $discussions = array(); $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(), array('forumid' => $forumid, 'sortby' => $sortby, 'sortdirection' => $sortdirection, 'page' => $page, 'perpage' => $perpage)); // Compact/extract functions are not recommended. $forumid = $params['forumid']; $sortby = $params['sortby']; $sortdirection = $params['sortdirection']; $page = $params['page']; $perpage = $params['perpage']; $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend'); if (!in_array($sortby, $sortallowedvalues)) { throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' . 'allowed values are: ' . implode(',', $sortallowedvalues)); } $sortdirection = strtoupper($sortdirection); $directionallowedvalues = array('ASC', 'DESC'); if (!in_array($sortdirection, $directionallowedvalues)) { throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues)); } $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST); // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..). $modcontext = context_module::instance($cm->id); self::validate_context($modcontext); // Check they have the view forum capability. require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum'); $sort = 'd.pinned DESC, d.' . $sortby . ' ' . $sortdirection; $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage, FORUM_POSTS_ALL_USER_GROUPS); if ($alldiscussions) { $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext); // Get the unreads array, this takes a forum id and returns data for all discussions. $unreads = array(); if ($cantrack = forum_tp_can_track_forums($forum)) { if ($forumtracked = forum_tp_is_tracked($forum)) { $unreads = forum_get_discussions_unread($cm); } } // The forum function returns the replies for all the discussions in a given forum. $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage); foreach ($alldiscussions as $discussion) { // This function checks for qanda forums. // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this. $discussionrec = clone $discussion; $discussionrec->id = $discussion->discussion; if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) { $warning = array(); // Function forum_get_discussions returns forum_posts ids not forum_discussions ones. $warning['item'] = 'post'; $warning['itemid'] = $discussion->id; $warning['warningcode'] = '1'; $warning['message'] = 'You can\'t see this discussion'; $warnings[] = $warning; continue; } $discussion->numunread = 0; if ($cantrack && $forumtracked) { if (isset($unreads[$discussion->discussion])) { $discussion->numunread = (int) $unreads[$discussion->discussion]; } } $discussion->numreplies = 0; if (!empty($replies[$discussion->discussion])) { $discussion->numreplies = (int) $replies[$discussion->discussion]->replies; } $discussion->name = external_format_string($discussion->name, $modcontext->id); $discussion->subject = external_format_string($discussion->subject, $modcontext->id); // Rewrite embedded images URLs. list($discussion->message, $discussion->messageformat) = external_format_text($discussion->message, $discussion->messageformat, $modcontext->id, 'mod_forum', 'post', $discussion->id); // List attachments. if (!empty($discussion->attachment)) { $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment', $discussion->id); } $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id); if (!empty($messageinlinefiles)) { $discussion->messageinlinefiles = $messageinlinefiles; } $discussion->locked = forum_discussion_is_locked($forum, $discussion); $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext); if (forum_is_author_hidden($discussion, $forum)) { $discussion->userid = null; $discussion->userfullname = null; $discussion->userpictureurl = null; $discussion->usermodified = null; $discussion->usermodifiedfullname = null; $discussion->usermodifiedpictureurl = null; } else { $picturefields = explode(',', user_picture::fields()); // Load user objects from the results of the query. $user = new stdclass(); $user->id = $discussion->userid; $user = username_load_fields_from_object($user, $discussion, null, $picturefields); // Preserve the id, it can be modified by username_load_fields_from_object. $user->id = $discussion->userid; $discussion->userfullname = fullname($user, $canviewfullname); $userpicture = new user_picture($user); $userpicture->size = 1; // Size f1. $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false); $usermodified = new stdclass(); $usermodified->id = $discussion->usermodified; $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields); // Preserve the id (it can be overwritten due to the prefixed $picturefields). $usermodified->id = $discussion->usermodified; $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname); $userpicture = new user_picture($usermodified); $userpicture->size = 1; // Size f1. $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false); } $discussions[] = $discussion; } } $result = array(); $result['discussions'] = $discussions; $result['warnings'] = $warnings; return $result; }
/** * Returns a list of choices in a provided list of courses, * if no list is provided all choices that the user can view will be returned. * * @param array $courseids the course ids * @return array of choices details * @since Moodle 3.0 */ public static function get_choices_by_courses($courseids = array()) { global $CFG; $returnedchoices = array(); $warnings = array(); $params = self::validate_parameters(self::get_choices_by_courses_parameters(), array('courseids' => $courseids)); if (empty($params['courseids'])) { $params['courseids'] = array_keys(enrol_get_my_courses()); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids']); // Get the choices in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $choices = get_all_instances_in_courses("choice", $courses); foreach ($choices as $choice) { $context = context_module::instance($choice->coursemodule); // Entry to return. $choicedetails = array(); // First, we return information that any user can see in the web interface. $choicedetails['id'] = $choice->id; $choicedetails['coursemodule'] = $choice->coursemodule; $choicedetails['course'] = $choice->course; $choicedetails['name'] = external_format_string($choice->name, $context->id); // Format intro. list($choicedetails['intro'], $choicedetails['introformat']) = external_format_text($choice->intro, $choice->introformat, $context->id, 'mod_choice', 'intro', null); if (has_capability('mod/choice:choose', $context)) { $choicedetails['publish'] = $choice->publish; $choicedetails['showresults'] = $choice->showresults; $choicedetails['showpreview'] = $choice->showpreview; $choicedetails['timeopen'] = $choice->timeopen; $choicedetails['timeclose'] = $choice->timeclose; $choicedetails['display'] = $choice->display; $choicedetails['allowupdate'] = $choice->allowupdate; $choicedetails['allowmultiple'] = $choice->allowmultiple; $choicedetails['limitanswers'] = $choice->limitanswers; $choicedetails['showunanswered'] = $choice->showunanswered; $choicedetails['includeinactive'] = $choice->includeinactive; } if (has_capability('moodle/course:manageactivities', $context)) { $choicedetails['timemodified'] = $choice->timemodified; $choicedetails['completionsubmit'] = $choice->completionsubmit; $choicedetails['section'] = $choice->section; $choicedetails['visible'] = $choice->visible; $choicedetails['groupmode'] = $choice->groupmode; $choicedetails['groupingid'] = $choice->groupingid; } $returnedchoices[] = $choicedetails; } } $result = array(); $result['choices'] = $returnedchoices; $result['warnings'] = $warnings; return $result; }
/** * Get the signup required settings and profile fields. * * @return array settings and possible warnings * @since Moodle 3.2 * @throws moodle_exception */ public static function get_signup_settings() { global $CFG, $PAGE; $context = context_system::instance(); // We need this to make work the format text functions. $PAGE->set_context($context); self::check_signup_enabled(); $result = array(); $result['namefields'] = useredit_get_required_name_fields(); if (!empty($CFG->passwordpolicy)) { $result['passwordpolicy'] = print_password_policy(); } if (!empty($CFG->sitepolicy)) { $result['sitepolicy'] = $CFG->sitepolicy; } if (!empty($CFG->defaultcity)) { $result['defaultcity'] = $CFG->defaultcity; } if (!empty($CFG->country)) { $result['country'] = $CFG->country; } if ($fields = profile_get_signup_fields()) { $result['profilefields'] = array(); foreach ($fields as $field) { $fielddata = $field->object->get_field_config_for_external(); $fielddata['categoryname'] = external_format_string($field->categoryname, $context->id); $fielddata['name'] = external_format_string($fielddata['name'], $context->id); list($fielddata['defaultdata'], $fielddata['defaultdataformat']) = external_format_text($fielddata['defaultdata'], $fielddata['defaultdataformat'], $context->id); $result['profilefields'][] = $fielddata; } } if (signup_captcha_enabled()) { require_once $CFG->libdir . '/recaptchalib.php'; // We return the public key, maybe we want to use the javascript api to get the image. $result['recaptchapublickey'] = $CFG->recaptchapublickey; list($result['recaptchachallengehash'], $result['recaptchachallengeimage'], $result['recaptchachallengejs']) = recaptcha_get_challenge_hash_and_urls(RECAPTCHA_API_SECURE_SERVER, $CFG->recaptchapublickey); } $result['warnings'] = array(); return $result; }
public function test_external_format_string() { $settings = external_settings::get_instance(); $currentraw = $settings->get_raw(); $currentfilter = $settings->get_filter(); $settings->set_raw(true); $context = context_system::instance(); $test = '$$ \pi $$ <script>hi</script> <h3>there</h3>'; $correct = $test; $this->assertSame(external_format_string($test, $context->id), $correct); $settings->set_raw(false); $test = '$$ \pi $$<script>hi</script> <h3>there</h3>'; $correct = '$$ \pi $$hi there'; $this->assertSame(external_format_string($test, $context->id), $correct); $settings->set_raw($currentraw); $settings->set_filter($currentfilter); }
/** * Get the values associated with a scale. * * @param int $scaleid Scale ID * @return array Values for a scale. */ public static function get_scale_values($scaleid) { global $DB; $params = self::validate_parameters(self::get_scale_values_parameters(), array('scaleid' => $scaleid)); $context = context_system::instance(); self::validate_context($context); // The following section is not learning plan specific and so has not been moved to the api. // Retrieve the scale value from the database. $scale = grade_scale::fetch(array('id' => $scaleid)); $scalevalues = $scale->load_items(); foreach ($scalevalues as $key => $value) { // Add a key (make the first value 1). $scalevalues[$key] = array('id' => $key + 1, 'name' => external_format_string($value, $context->id)); } return $scalevalues; }
public function test_external_format_string() { $this->resetAfterTest(); $settings = external_settings::get_instance(); $currentraw = $settings->get_raw(); $currentfilter = $settings->get_filter(); // Enable multilang filter to on content and heading. filter_set_global_state('multilang', TEXTFILTER_ON); filter_set_applies_to_strings('multilang', 1); $filtermanager = filter_manager::instance(); $filtermanager->reset_caches(); $settings->set_raw(true); $settings->set_filter(true); $context = context_system::instance(); $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>!'; $correct = $test; $this->assertSame($correct, external_format_string($test, $context->id)); $settings->set_raw(false); $settings->set_filter(false); $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>?'; $correct = 'ENFR hi there?'; $this->assertSame($correct, external_format_string($test, $context->id)); $settings->set_filter(true); $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>@'; $correct = 'EN hi there@'; $this->assertSame($correct, external_format_string($test, $context->id)); // Filters can be opted out. $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>%'; $correct = 'ENFR hi there%'; $this->assertSame($correct, external_format_string($test, $context->id, false, ['filter' => false])); $settings->set_raw($currentraw); $settings->set_filter($currentfilter); }
/** * Returns the list of pages from a specific subwiki. * * @param int $wikiid The wiki instance ID. * @param int $groupid The group ID. If not defined, use current group. * @param int $userid The user ID. If not defined, use current user. * @param array $options Several options like sort by, sort direction, ... * @return array Containing a list of warnings and a list of pages. * @since Moodle 3.1 */ public static function get_subwiki_pages($wikiid, $groupid = -1, $userid = 0, $options = array()) { $returnedpages = array(); $warnings = array(); $params = self::validate_parameters(self::get_subwiki_pages_parameters(), array('wikiid' => $wikiid, 'groupid' => $groupid, 'userid' => $userid, 'options' => $options)); // Get wiki instance. if (!($wiki = wiki_get_wiki($params['wikiid']))) { throw new moodle_exception('incorrectwikiid', 'wiki'); } list($course, $cm) = get_course_and_cm_from_instance($wiki, 'wiki'); $context = context_module::instance($cm->id); self::validate_context($context); // Determine groupid and userid to use. list($groupid, $userid) = self::determine_group_and_user($cm, $wiki, $params['groupid'], $params['userid']); // Get subwiki and validate it. $subwiki = wiki_get_subwiki_by_group_and_user_with_validation($wiki, $groupid, $userid); if ($subwiki === false) { throw new moodle_exception('cannotviewpage', 'wiki'); } else { if ($subwiki->id != -1) { // Set sort param. $options = $params['options']; if (!empty($options['sortby'])) { if ($options['sortdirection'] != 'ASC' && $options['sortdirection'] != 'DESC') { // Invalid sort direction. Use default. $options['sortdirection'] = 'ASC'; } $sort = $options['sortby'] . ' ' . $options['sortdirection']; } $pages = wiki_get_page_list($subwiki->id, $sort); $caneditpages = wiki_user_can_edit($subwiki); $firstpage = wiki_get_first_page($subwiki->id); foreach ($pages as $page) { $retpage = array('id' => $page->id, 'subwikiid' => $page->subwikiid, 'title' => external_format_string($page->title, $context->id), 'timecreated' => $page->timecreated, 'timemodified' => $page->timemodified, 'timerendered' => $page->timerendered, 'userid' => $page->userid, 'pageviews' => $page->pageviews, 'readonly' => $page->readonly, 'caneditpage' => $caneditpages, 'firstpage' => $page->id == $firstpage->id); // Refresh page cached content if needed. if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { if ($content = wiki_refresh_cachedcontent($page)) { $page = $content['page']; } } list($cachedcontent, $contentformat) = external_format_text($page->cachedcontent, FORMAT_HTML, $context->id, 'mod_wiki', 'attachments', $subwiki->id); if ($options['includecontent']) { // Return the page content. $retpage['cachedcontent'] = $cachedcontent; $retpage['contentformat'] = $contentformat; } else { // Return the size of the content. if (function_exists('mb_strlen') && (int) ini_get('mbstring.func_overload') & 2) { $retpage['contentsize'] = mb_strlen($cachedcontent, '8bit'); } else { $retpage['contentsize'] = strlen($cachedcontent); } } $returnedpages[] = $retpage; } } } $result = array(); $result['pages'] = $returnedpages; $result['warnings'] = $warnings; return $result; }
protected function get_other_values(renderer_base $output) { $context = $this->related['cm']->context; return array('id' => $this->related['cm']->id, 'name' => external_format_string($this->related['cm']->name, $context->id), 'url' => $this->related['cm']->url->out(), 'iconurl' => $this->related['cm']->get_icon_url()->out()); }
/** * Export this data so it can be used as the context for a mustache template. * * @param renderer_base $output Used to do a final render of any components that need to be rendered for export. * @return array */ public function export_for_template(renderer_base $output) { global $CFG; require_once($CFG->libdir . '/externallib.php'); $syscontext = context_system::instance(); $context = new stdClass(); $context->text = external_format_string($this->text, $syscontext->id); $context->url = $this->url ? $this->url->out() : null; $context->title = external_format_string($this->title, $syscontext->id); $context->sort = $this->sort; $context->children = array(); if (preg_match("/^#+$/", $this->text)) { $context->divider = true; } $context->haschildren = !empty($this->children) && (count($this->children) > 0); foreach ($this->children as $child) { $child = $child->export_for_template($output); array_push($context->children, $child); } return $context; }
/** * Returns a list of chats in a provided list of courses, * if no list is provided all chats that the user can view will be returned. * * @param array $courseids the course ids * @return array of chats details * @since Moodle 3.0 */ public static function get_chats_by_courses($courseids = array()) { global $CFG; $returnedchats = array(); $warnings = array(); $params = self::validate_parameters(self::get_chats_by_courses_parameters(), array('courseids' => $courseids)); $courses = array(); if (empty($params['courseids'])) { $courses = enrol_get_my_courses(); $params['courseids'] = array_keys($courses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses); // Get the chats in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $chats = get_all_instances_in_courses("chat", $courses); foreach ($chats as $chat) { $chatcontext = context_module::instance($chat->coursemodule); // Entry to return. $chatdetails = array(); // First, we return information that any user can see in the web interface. $chatdetails['id'] = $chat->id; $chatdetails['coursemodule'] = $chat->coursemodule; $chatdetails['course'] = $chat->course; $chatdetails['name'] = external_format_string($chat->name, $chatcontext->id); // Format intro. list($chatdetails['intro'], $chatdetails['introformat']) = external_format_text($chat->intro, $chat->introformat, $chatcontext->id, 'mod_chat', 'intro', null); if (has_capability('mod/chat:chat', $chatcontext)) { $chatdetails['chatmethod'] = $CFG->chat_method; $chatdetails['keepdays'] = $chat->keepdays; $chatdetails['studentlogs'] = $chat->studentlogs; $chatdetails['chattime'] = $chat->chattime; $chatdetails['schedule'] = $chat->schedule; } if (has_capability('moodle/course:manageactivities', $chatcontext)) { $chatdetails['timemodified'] = $chat->timemodified; $chatdetails['section'] = $chat->section; $chatdetails['visible'] = $chat->visible; $chatdetails['groupmode'] = $chat->groupmode; $chatdetails['groupingid'] = $chat->groupingid; } $returnedchats[] = $chatdetails; } } $result = array(); $result['chats'] = $returnedchats; $result['warnings'] = $warnings; return $result; }
/** * Returns a list of external tools in a provided list of courses, * if no list is provided all external tools that the user can view will be returned. * * @param array $courseids the course ids * @return array the lti details * @since Moodle 3.0 */ public static function get_ltis_by_courses($courseids = array()) { global $CFG; $returnedltis = array(); $warnings = array(); $params = self::validate_parameters(self::get_ltis_by_courses_parameters(), array('courseids' => $courseids)); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the ltis in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $ltis = get_all_instances_in_courses("lti", $courses); foreach ($ltis as $lti) { $context = context_module::instance($lti->coursemodule); // Entry to return. $module = array(); // First, we return information that any user can see in (or can deduce from) the web interface. $module['id'] = $lti->id; $module['coursemodule'] = $lti->coursemodule; $module['course'] = $lti->course; $module['name'] = external_format_string($lti->name, $context->id); $viewablefields = []; if (has_capability('mod/lti:view', $context)) { list($module['intro'], $module['introformat']) = external_format_text($lti->intro, $lti->introformat, $context->id, 'mod_lti', 'intro', $lti->id); $module['introfiles'] = external_util::get_area_files($context->id, 'mod_lti', 'intro', false, false); $viewablefields = array('launchcontainer', 'showtitlelaunch', 'showdescriptionlaunch', 'icon', 'secureicon'); } // Check additional permissions for returning optional private settings. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('timecreated', 'timemodified', 'typeid', 'toolurl', 'securetoolurl', 'instructorchoicesendname', 'instructorchoicesendemailaddr', 'instructorchoiceallowroster', 'instructorchoiceallowsetting', 'instructorcustomparameters', 'instructorchoiceacceptgrades', 'grade', 'resourcekey', 'password', 'debuglaunch', 'servicesalt', 'visible', 'groupmode', 'groupingid'); $viewablefields = array_merge($viewablefields, $additionalfields); } foreach ($viewablefields as $field) { $module[$field] = $lti->{$field}; } $returnedltis[] = $module; } } $result = array(); $result['ltis'] = $returnedltis; $result['warnings'] = $warnings; return $result; }
/** * Returns a list of quizzes in a provided list of courses, * if no list is provided all quizzes that the user can view will be returned. * * @param array $courseids Array of course ids * @return array of quizzes details * @since Moodle 3.1 */ public static function get_quizzes_by_courses($courseids = array()) { global $USER; $warnings = array(); $returnedquizzes = array(); $params = array('courseids' => $courseids); $params = self::validate_parameters(self::get_quizzes_by_courses_parameters(), $params); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the quizzes in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $quizzes = get_all_instances_in_courses("quiz", $courses); foreach ($quizzes as $quiz) { $context = context_module::instance($quiz->coursemodule); // Update quiz with override information. $quiz = quiz_update_effective_access($quiz, $USER->id); // Entry to return. $quizdetails = array(); // First, we return information that any user can see in the web interface. $quizdetails['id'] = $quiz->id; $quizdetails['coursemodule'] = $quiz->coursemodule; $quizdetails['course'] = $quiz->course; $quizdetails['name'] = external_format_string($quiz->name, $context->id); if (has_capability('mod/quiz:view', $context)) { // Format intro. list($quizdetails['intro'], $quizdetails['introformat']) = external_format_text($quiz->intro, $quiz->introformat, $context->id, 'mod_quiz', 'intro', null); $viewablefields = array('timeopen', 'timeclose', 'grademethod', 'section', 'visible', 'groupmode', 'groupingid'); $timenow = time(); $quizobj = quiz::create($quiz->id, $USER->id); $accessmanager = new quiz_access_manager($quizobj, $timenow, has_capability('mod/quiz:ignoretimelimits', $context, null, false)); // Fields the user could see if have access to the quiz. if (!$accessmanager->prevent_access()) { // Some times this function returns just empty. $hasfeedback = quiz_has_feedback($quiz); $quizdetails['hasfeedback'] = !empty($hasfeedback) ? 1 : 0; $quizdetails['hasquestions'] = (int) $quizobj->has_questions(); $quizdetails['autosaveperiod'] = get_config('quiz', 'autosaveperiod'); $additionalfields = array('timelimit', 'attempts', 'attemptonlast', 'grademethod', 'decimalpoints', 'questiondecimalpoints', 'reviewattempt', 'reviewcorrectness', 'reviewmarks', 'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer', 'reviewoverallfeedback', 'questionsperpage', 'navmethod', 'sumgrades', 'grade', 'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks', 'completionattemptsexhausted', 'completionpass', 'overduehandling', 'graceperiod', 'preferredbehaviour', 'canredoquestions'); $viewablefields = array_merge($viewablefields, $additionalfields); } // Fields only for managers. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet'); $viewablefields = array_merge($viewablefields, $additionalfields); } foreach ($viewablefields as $field) { $quizdetails[$field] = $quiz->{$field}; } } $returnedquizzes[] = $quizdetails; } } $result = array(); $result['quizzes'] = $returnedquizzes; $result['warnings'] = $warnings; return $result; }
/** * Test get_courses */ public function test_get_courses() { global $DB; $this->resetAfterTest(true); $generatedcourses = array(); $coursedata['idnumber'] = 'idnumbercourse1'; // Adding tags here to check that format_string is applied. $coursedata['fullname'] = '<b>Course 1 for PHPunit test</b>'; $coursedata['shortname'] = '<b>Course 1 for PHPunit test</b>'; $coursedata['summary'] = 'Course 1 description'; $coursedata['summaryformat'] = FORMAT_MOODLE; $course1 = self::getDataGenerator()->create_course($coursedata); $generatedcourses[$course1->id] = $course1; $course2 = self::getDataGenerator()->create_course(); $generatedcourses[$course2->id] = $course2; $course3 = self::getDataGenerator()->create_course(array('format' => 'topics')); $generatedcourses[$course3->id] = $course3; // Set the required capabilities by the external function. $context = context_system::instance(); $roleid = $this->assignUserCapability('moodle/course:view', $context->id); $this->assignUserCapability('moodle/course:update', context_course::instance($course1->id)->id, $roleid); $this->assignUserCapability('moodle/course:update', context_course::instance($course2->id)->id, $roleid); $this->assignUserCapability('moodle/course:update', context_course::instance($course3->id)->id, $roleid); $courses = core_course_external::get_courses(array('ids' => array($course1->id, $course2->id))); // We need to execute the return values cleaning process to simulate the web service server. $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses); // Check we retrieve the good total number of categories. $this->assertEquals(2, count($courses)); foreach ($courses as $course) { $coursecontext = context_course::instance($course['id']); $dbcourse = $generatedcourses[$course['id']]; $this->assertEquals($course['idnumber'], $dbcourse->idnumber); $this->assertEquals($course['fullname'], external_format_string($dbcourse->fullname, $coursecontext->id)); $this->assertEquals($course['displayname'], external_format_string(get_course_display_name_for_list($dbcourse), $coursecontext->id)); // Summary was converted to the HTML format. $this->assertEquals($course['summary'], format_text($dbcourse->summary, FORMAT_MOODLE, array('para' => false))); $this->assertEquals($course['summaryformat'], FORMAT_HTML); $this->assertEquals($course['shortname'], external_format_string($dbcourse->shortname, $coursecontext->id)); $this->assertEquals($course['categoryid'], $dbcourse->category); $this->assertEquals($course['format'], $dbcourse->format); $this->assertEquals($course['showgrades'], $dbcourse->showgrades); $this->assertEquals($course['newsitems'], $dbcourse->newsitems); $this->assertEquals($course['startdate'], $dbcourse->startdate); $this->assertEquals($course['enddate'], $dbcourse->enddate); $this->assertEquals($course['numsections'], $dbcourse->numsections); $this->assertEquals($course['maxbytes'], $dbcourse->maxbytes); $this->assertEquals($course['showreports'], $dbcourse->showreports); $this->assertEquals($course['visible'], $dbcourse->visible); $this->assertEquals($course['hiddensections'], $dbcourse->hiddensections); $this->assertEquals($course['groupmode'], $dbcourse->groupmode); $this->assertEquals($course['groupmodeforce'], $dbcourse->groupmodeforce); $this->assertEquals($course['defaultgroupingid'], $dbcourse->defaultgroupingid); $this->assertEquals($course['completionnotify'], $dbcourse->completionnotify); $this->assertEquals($course['lang'], $dbcourse->lang); $this->assertEquals($course['forcetheme'], $dbcourse->theme); $this->assertEquals($course['enablecompletion'], $dbcourse->enablecompletion); if ($dbcourse->format === 'topics') { $this->assertEquals($course['courseformatoptions'], array(array('name' => 'numsections', 'value' => $dbcourse->numsections), array('name' => 'hiddensections', 'value' => $dbcourse->hiddensections), array('name' => 'coursedisplay', 'value' => $dbcourse->coursedisplay))); } } // Get all courses in the DB $courses = core_course_external::get_courses(array()); // We need to execute the return values cleaning process to simulate the web service server. $courses = external_api::clean_returnvalue(core_course_external::get_courses_returns(), $courses); $this->assertEquals($DB->count_records('course'), count($courses)); }