public function test_create_content() { global $DB; $this->resetAfterTest(); $this->setAdminUser(); $course = $this->getDataGenerator()->create_course(); $wiki = $this->getDataGenerator()->create_module('wiki', array('course' => $course)); $wikigenerator = $this->getDataGenerator()->get_plugin_generator('mod_wiki'); $page1 = $wikigenerator->create_first_page($wiki); $page2 = $wikigenerator->create_content($wiki); $page3 = $wikigenerator->create_content($wiki, array('title' => 'Custom title', 'tags' => array('Cats', 'mice'))); unset($wiki->cmid); $page4 = $wikigenerator->create_content($wiki, array('tags' => 'Cats, dogs')); $subwikis = $DB->get_records('wiki_subwikis', array('wikiid' => $wiki->id), 'id'); $this->assertEquals(1, count($subwikis)); $subwikiid = key($subwikis); $records = $DB->get_records('wiki_pages', array('subwikiid' => $subwikiid), 'id'); $this->assertEquals(4, count($records)); $this->assertEquals($page1->id, $records[$page1->id]->id); $this->assertEquals($page2->id, $records[$page2->id]->id); $this->assertEquals($page3->id, $records[$page3->id]->id); $this->assertEquals('Custom title', $records[$page3->id]->title); $this->assertEquals(array('Cats', 'mice'), array_values(core_tag_tag::get_item_tags_array('mod_wiki', 'wiki_pages', $page3->id))); $this->assertEquals(array('Cats', 'dogs'), array_values(core_tag_tag::get_item_tags_array('mod_wiki', 'wiki_pages', $page4->id))); }
/** * Private function to factor common code out of get_question_options(). * * @param object $question the question to tidy. * @param boolean $loadtags load the question tags from the tags table. Optional, default false. */ function _tidy_question($question, $loadtags = false) { global $CFG; // Load question-type specific fields. if (!question_bank::is_qtype_installed($question->qtype)) { $question->questiontext = html_writer::tag('p', get_string('warningmissingtype', 'qtype_missingtype')) . $question->questiontext; } question_bank::get_qtype($question->qtype)->get_question_options($question); // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.) $question->defaultmark += 0; $question->penalty += 0; if (isset($question->_partiallyloaded)) { unset($question->_partiallyloaded); } if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) { $question->tags = core_tag_tag::get_item_tags_array('core_question', 'question', $question->id); } }
/** * Turns question into an xml segment * @param object $question the question data. * @return string xml segment */ public function writequestion($question) { global $CFG, $OUTPUT; $invalidquestion = false; $fs = get_file_storage(); $contextid = $question->contextid; // Get files used by the questiontext. $question->questiontextfiles = $fs->get_area_files($contextid, 'question', 'questiontext', $question->id); // Get files used by the generalfeedback. $question->generalfeedbackfiles = $fs->get_area_files($contextid, 'question', 'generalfeedback', $question->id); if (!empty($question->options->answers)) { foreach ($question->options->answers as $answer) { $answer->answerfiles = $fs->get_area_files($contextid, 'question', 'answer', $answer->id); $answer->feedbackfiles = $fs->get_area_files($contextid, 'question', 'answerfeedback', $answer->id); } } $expout = ''; // Add a comment linking this to the original question id. $expout .= "<!-- question: {$question->id} -->\n"; // Check question type. $questiontype = $this->get_qtype($question->qtype); // Categories are a special case. if ($question->qtype == 'category') { $categorypath = $this->writetext($question->category); $expout .= " <question type=\"category\">\n"; $expout .= " <category>\n"; $expout .= " {$categorypath}\n"; $expout .= " </category>\n"; $expout .= " </question>\n"; return $expout; } // Now we know we are are handing a real question. // Output the generic information. $expout .= " <question type=\"{$questiontype}\">\n"; $expout .= " <name>\n"; $expout .= $this->writetext($question->name, 3); $expout .= " </name>\n"; $expout .= " <questiontext {$this->format($question->questiontextformat)}>\n"; $expout .= $this->writetext($question->questiontext, 3); $expout .= $this->write_files($question->questiontextfiles); $expout .= " </questiontext>\n"; $expout .= " <generalfeedback {$this->format($question->generalfeedbackformat)}>\n"; $expout .= $this->writetext($question->generalfeedback, 3); $expout .= $this->write_files($question->generalfeedbackfiles); $expout .= " </generalfeedback>\n"; if ($question->qtype != 'multianswer') { $expout .= " <defaultgrade>{$question->defaultmark}</defaultgrade>\n"; } $expout .= " <penalty>{$question->penalty}</penalty>\n"; $expout .= " <hidden>{$question->hidden}</hidden>\n"; // The rest of the output depends on question type. switch ($question->qtype) { case 'category': // Not a qtype really - dummy used for category switching. break; case 'truefalse': $trueanswer = $question->options->answers[$question->options->trueanswer]; $trueanswer->answer = 'true'; $expout .= $this->write_answer($trueanswer); $falseanswer = $question->options->answers[$question->options->falseanswer]; $falseanswer->answer = 'false'; $expout .= $this->write_answer($falseanswer); break; case 'multichoice': $expout .= " <single>" . $this->get_single($question->options->single) . "</single>\n"; $expout .= " <shuffleanswers>" . $this->get_single($question->options->shuffleanswers) . "</shuffleanswers>\n"; $expout .= " <answernumbering>" . $question->options->answernumbering . "</answernumbering>\n"; $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid); $expout .= $this->write_answers($question->options->answers); break; case 'shortanswer': $expout .= " <usecase>{$question->options->usecase}</usecase>\n"; $expout .= $this->write_answers($question->options->answers); break; case 'numerical': foreach ($question->options->answers as $answer) { $expout .= $this->write_answer($answer, " <tolerance>{$answer->tolerance}</tolerance>\n"); } $units = $question->options->units; if (count($units)) { $expout .= "<units>\n"; foreach ($units as $unit) { $expout .= " <unit>\n"; $expout .= " <multiplier>{$unit->multiplier}</multiplier>\n"; $expout .= " <unit_name>{$unit->unit}</unit_name>\n"; $expout .= " </unit>\n"; } $expout .= "</units>\n"; } if (isset($question->options->unitgradingtype)) { $expout .= " <unitgradingtype>" . $question->options->unitgradingtype . "</unitgradingtype>\n"; } if (isset($question->options->unitpenalty)) { $expout .= " <unitpenalty>{$question->options->unitpenalty}</unitpenalty>\n"; } if (isset($question->options->showunits)) { $expout .= " <showunits>{$question->options->showunits}</showunits>\n"; } if (isset($question->options->unitsleft)) { $expout .= " <unitsleft>{$question->options->unitsleft}</unitsleft>\n"; } if (!empty($question->options->instructionsformat)) { $files = $fs->get_area_files($contextid, 'qtype_numerical', 'instruction', $question->id); $expout .= " <instructions " . $this->format($question->options->instructionsformat) . ">\n"; $expout .= $this->writetext($question->options->instructions, 3); $expout .= $this->write_files($files); $expout .= " </instructions>\n"; } break; case 'match': $expout .= " <shuffleanswers>" . $this->get_single($question->options->shuffleanswers) . "</shuffleanswers>\n"; $expout .= $this->write_combined_feedback($question->options, $question->id, $question->contextid); foreach ($question->options->subquestions as $subquestion) { $files = $fs->get_area_files($contextid, 'qtype_match', 'subquestion', $subquestion->id); $expout .= " <subquestion " . $this->format($subquestion->questiontextformat) . ">\n"; $expout .= $this->writetext($subquestion->questiontext, 3); $expout .= $this->write_files($files); $expout .= " <answer>\n"; $expout .= $this->writetext($subquestion->answertext, 4); $expout .= " </answer>\n"; $expout .= " </subquestion>\n"; } break; case 'description': // Nothing else to do. break; case 'multianswer': foreach ($question->options->questions as $index => $subq) { $expout = str_replace('{#' . $index . '}', $subq->questiontext, $expout); } break; case 'essay': $expout .= " <responseformat>" . $question->options->responseformat . "</responseformat>\n"; $expout .= " <responserequired>" . $question->options->responserequired . "</responserequired>\n"; $expout .= " <responsefieldlines>" . $question->options->responsefieldlines . "</responsefieldlines>\n"; $expout .= " <attachments>" . $question->options->attachments . "</attachments>\n"; $expout .= " <attachmentsrequired>" . $question->options->attachmentsrequired . "</attachmentsrequired>\n"; $expout .= " <graderinfo " . $this->format($question->options->graderinfoformat) . ">\n"; $expout .= $this->writetext($question->options->graderinfo, 3); $expout .= $this->write_files($fs->get_area_files($contextid, 'qtype_essay', 'graderinfo', $question->id)); $expout .= " </graderinfo>\n"; $expout .= " <responsetemplate " . $this->format($question->options->responsetemplateformat) . ">\n"; $expout .= $this->writetext($question->options->responsetemplate, 3); $expout .= " </responsetemplate>\n"; break; case 'calculated': case 'calculatedsimple': case 'calculatedmulti': $expout .= " <synchronize>{$question->options->synchronize}</synchronize>\n"; $expout .= " <single>{$question->options->single}</single>\n"; $expout .= " <answernumbering>" . $question->options->answernumbering . "</answernumbering>\n"; $expout .= " <shuffleanswers>" . $question->options->shuffleanswers . "</shuffleanswers>\n"; $component = 'qtype_' . $question->qtype; $files = $fs->get_area_files($contextid, $component, 'correctfeedback', $question->id); $expout .= " <correctfeedback>\n"; $expout .= $this->writetext($question->options->correctfeedback, 3); $expout .= $this->write_files($files); $expout .= " </correctfeedback>\n"; $files = $fs->get_area_files($contextid, $component, 'partiallycorrectfeedback', $question->id); $expout .= " <partiallycorrectfeedback>\n"; $expout .= $this->writetext($question->options->partiallycorrectfeedback, 3); $expout .= $this->write_files($files); $expout .= " </partiallycorrectfeedback>\n"; $files = $fs->get_area_files($contextid, $component, 'incorrectfeedback', $question->id); $expout .= " <incorrectfeedback>\n"; $expout .= $this->writetext($question->options->incorrectfeedback, 3); $expout .= $this->write_files($files); $expout .= " </incorrectfeedback>\n"; foreach ($question->options->answers as $answer) { $percent = 100 * $answer->fraction; $expout .= "<answer fraction=\"{$percent}\">\n"; // The "<text/>" tags are an added feature, old files won't have them. $expout .= " <text>{$answer->answer}</text>\n"; $expout .= " <tolerance>{$answer->tolerance}</tolerance>\n"; $expout .= " <tolerancetype>{$answer->tolerancetype}</tolerancetype>\n"; $expout .= " <correctanswerformat>" . $answer->correctanswerformat . "</correctanswerformat>\n"; $expout .= " <correctanswerlength>" . $answer->correctanswerlength . "</correctanswerlength>\n"; $expout .= " <feedback {$this->format($answer->feedbackformat)}>\n"; $files = $fs->get_area_files($contextid, $component, 'instruction', $question->id); $expout .= $this->writetext($answer->feedback); $expout .= $this->write_files($answer->feedbackfiles); $expout .= " </feedback>\n"; $expout .= "</answer>\n"; } if (isset($question->options->unitgradingtype)) { $expout .= " <unitgradingtype>" . $question->options->unitgradingtype . "</unitgradingtype>\n"; } if (isset($question->options->unitpenalty)) { $expout .= " <unitpenalty>" . $question->options->unitpenalty . "</unitpenalty>\n"; } if (isset($question->options->showunits)) { $expout .= " <showunits>{$question->options->showunits}</showunits>\n"; } if (isset($question->options->unitsleft)) { $expout .= " <unitsleft>{$question->options->unitsleft}</unitsleft>\n"; } if (isset($question->options->instructionsformat)) { $files = $fs->get_area_files($contextid, $component, 'instruction', $question->id); $expout .= " <instructions " . $this->format($question->options->instructionsformat) . ">\n"; $expout .= $this->writetext($question->options->instructions, 3); $expout .= $this->write_files($files); $expout .= " </instructions>\n"; } if (isset($question->options->units)) { $units = $question->options->units; if (count($units)) { $expout .= "<units>\n"; foreach ($units as $unit) { $expout .= " <unit>\n"; $expout .= " <multiplier>{$unit->multiplier}</multiplier>\n"; $expout .= " <unit_name>{$unit->unit}</unit_name>\n"; $expout .= " </unit>\n"; } $expout .= "</units>\n"; } } // The tag $question->export_process has been set so we get all the // data items in the database from the function // qtype_calculated::get_question_options calculatedsimple defaults // to calculated. if (isset($question->options->datasets) && count($question->options->datasets)) { $expout .= "<dataset_definitions>\n"; foreach ($question->options->datasets as $def) { $expout .= "<dataset_definition>\n"; $expout .= " <status>" . $this->writetext($def->status) . "</status>\n"; $expout .= " <name>" . $this->writetext($def->name) . "</name>\n"; if ($question->qtype == 'calculated') { $expout .= " <type>calculated</type>\n"; } else { $expout .= " <type>calculatedsimple</type>\n"; } $expout .= " <distribution>" . $this->writetext($def->distribution) . "</distribution>\n"; $expout .= " <minimum>" . $this->writetext($def->minimum) . "</minimum>\n"; $expout .= " <maximum>" . $this->writetext($def->maximum) . "</maximum>\n"; $expout .= " <decimals>" . $this->writetext($def->decimals) . "</decimals>\n"; $expout .= " <itemcount>{$def->itemcount}</itemcount>\n"; if ($def->itemcount > 0) { $expout .= " <dataset_items>\n"; foreach ($def->items as $item) { $expout .= " <dataset_item>\n"; $expout .= " <number>" . $item->itemnumber . "</number>\n"; $expout .= " <value>" . $item->value . "</value>\n"; $expout .= " </dataset_item>\n"; } $expout .= " </dataset_items>\n"; $expout .= " <number_of_items>" . $def->number_of_items . "</number_of_items>\n"; } $expout .= "</dataset_definition>\n"; } $expout .= "</dataset_definitions>\n"; } break; default: // Try support by optional plugin. if (!($data = $this->try_exporting_using_qtypes($question->qtype, $question))) { $invalidquestion = true; } else { $expout .= $data; } } // Output any hints. $expout .= $this->write_hints($question); // Write the question tags. $tags = core_tag_tag::get_item_tags_array('core_question', 'question', $question->id); if (!empty($tags)) { $expout .= " <tags>\n"; foreach ($tags as $tag) { $expout .= " <tag>" . $this->writetext($tag, 0, true) . "</tag>\n"; } $expout .= " </tags>\n"; } // Close the question tag. $expout .= " </question>\n"; if ($invalidquestion) { return ''; } else { return $expout; } }
$overviewfilesoptions = course_overviewfiles_options($course); if (!empty($course)) { // Add context for editor. $editoroptions['context'] = $coursecontext; $editoroptions['subdirs'] = file_area_contains_subdirs($coursecontext, 'course', 'summary', 0); $course = file_prepare_standard_editor($course, 'summary', $editoroptions, $coursecontext, 'course', 'summary', 0); if ($overviewfilesoptions) { file_prepare_standard_filemanager($course, 'overviewfiles', $overviewfilesoptions, $coursecontext, 'course', 'overviewfiles', 0); } // Inject current aliases. $aliases = $DB->get_records('role_names', array('contextid' => $coursecontext->id)); foreach ($aliases as $alias) { $course->{'role_' . $alias->roleid} = $alias->name; } // Populate course tags. $course->tags = core_tag_tag::get_item_tags_array('core', 'course', $course->id); } else { // Editor should respect category context if course context is not set. $editoroptions['context'] = $catcontext; $editoroptions['subdirs'] = 0; $course = file_prepare_standard_editor($course, 'summary', $editoroptions, null, 'course', 'summary', null); if ($overviewfilesoptions) { file_prepare_standard_filemanager($course, 'overviewfiles', $overviewfilesoptions, null, 'course', 'overviewfiles', 0); } } // First create the form. $args = array('course' => $course, 'category' => $category, 'editoroptions' => $editoroptions, 'returnto' => $returnto, 'returnurl' => $returnurl); $editform = new course_edit_form(null, $args); if ($editform->is_cancelled()) { // The form has been cancelled, take them back to what ever the return to is. redirect($returnurl);
/** * Generate any blog RSS feed via one function * * @param stdClass $context The context of the blog for which the feed it being generated * @param array $args An array of arguements needed to build the feed (contextid, token, componentname, type, id, tagid) */ function blog_rss_get_feed($context, $args) { global $CFG, $SITE, $DB; if (empty($CFG->enableblogs)) { debugging('Blogging disabled on this site, RSS feeds are not available'); return null; } if (empty($CFG->enablerssfeeds)) { debugging('Sorry, RSS feeds are disabled on this site'); return ''; } if ($CFG->bloglevel == BLOG_SITE_LEVEL) { if (isguestuser()) { debugging(get_string('nopermissiontoshow', 'error')); return ''; } } $sitecontext = context_system::instance(); if (!has_capability('moodle/blog:view', $sitecontext)) { return null; } $type = clean_param($args[3], PARAM_ALPHA); $id = clean_param($args[4], PARAM_INT); // Could be groupid / courseid / userid depending on $type. $tagid = 0; if ($args[5] != 'rss.xml') { $tagid = clean_param($args[5], PARAM_INT); } else { $tagid = 0; } $filename = blog_rss_file_name($type, $id, $tagid); if (file_exists($filename)) { if (filemtime($filename) + 3600 > time()) { return $filename; // It's already done so we return cached version. } } $courseid = $groupid = $userid = null; switch ($type) { case 'site': break; case 'course': $courseid = $id; break; case 'group': $groupid = $id; break; case 'user': $userid = $id; break; } // Get all the entries from the database. require_once $CFG->dirroot . '/blog/locallib.php'; $blogheaders = blog_get_headers($courseid, $groupid, $userid, $tagid); $bloglisting = new blog_listing($blogheaders['filters']); $blogentries = $bloglisting->get_entries(); // Now generate an array of RSS items. if ($blogentries) { $items = array(); foreach ($blogentries as $blogentry) { $item = new stdClass(); $item->author = fullname($DB->get_record('user', array('id' => $blogentry->userid))); // TODO: this is slow. $item->title = $blogentry->subject; $item->pubdate = $blogentry->lastmodified; $item->link = $CFG->wwwroot . '/blog/index.php?entryid=' . $blogentry->id; $summary = file_rewrite_pluginfile_urls($blogentry->summary, 'pluginfile.php', $sitecontext->id, 'blog', 'post', $blogentry->id); $item->description = format_text($summary, $blogentry->format); if ($blogtags = core_tag_tag::get_item_tags_array('core', 'post', $blogentry->id)) { $item->tags = $blogtags; $item->tagscheme = $CFG->wwwroot . '/tag'; } $items[] = $item; } $articles = rss_add_items($items); // Change structure to XML. } else { $articles = ''; } // Get header and footer information. switch ($type) { case 'user': $info = fullname($DB->get_record('user', array('id' => $id), get_all_user_name_fields(true))); break; case 'course': $info = $DB->get_field('course', 'fullname', array('id' => $id)); $info = format_string($info, true, array('context' => context_course::instance($id))); break; case 'site': $info = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))); break; case 'group': $group = groups_get_group($id); $info = $group->name; // TODO: $DB->get_field('groups', 'name', array('id' => $id)). break; default: $info = ''; break; } if ($tagid) { $info .= ': ' . $DB->get_field('tags', 'text', array('id' => $tagid)); } $header = rss_standard_header(get_string($type . 'blog', 'blog', $info), $CFG->wwwroot . '/blog/index.php', get_string('intro', 'blog')); $footer = rss_standard_footer(); // Save the XML contents to file. $rssdata = $header . $articles . $footer; if (blog_rss_save_file($type, $id, $tagid, $rssdata)) { return $filename; } else { return false; // Couldn't find it or make it. } }
public function test_data_saved() { global $DB; $this->resetAfterTest(true); // Create. $mode = tool_uploadcourse_processor::MODE_CREATE_NEW; $updatemode = tool_uploadcourse_processor::UPDATE_NOTHING; $data = array('shortname' => 'c1', 'fullname' => 'Fullname', 'category' => '1', 'visible' => '0', 'startdate' => '8 June 1990', 'idnumber' => '123abc', 'summary' => 'Summary', 'format' => 'weeks', 'theme' => 'afterburner', 'lang' => 'en', 'newsitems' => '7', 'showgrades' => '0', 'showreports' => '1', 'legacyfiles' => '1', 'maxbytes' => '1234', 'groupmode' => '2', 'groupmodeforce' => '1', 'enablecompletion' => '1', 'tags' => 'Cat, Dog', 'role_teacher' => 'Knight', 'role_manager' => 'Jedi', 'enrolment_1' => 'guest', 'enrolment_2' => 'self', 'enrolment_2_roleid' => '1', 'enrolment_3' => 'manual', 'enrolment_3_disable' => '1'); $this->assertFalse($DB->record_exists('course', array('shortname' => 'c1'))); $co = new tool_uploadcourse_course($mode, $updatemode, $data); $this->assertTrue($co->prepare()); $co->proceed(); $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1'))); $course = $DB->get_record('course', array('shortname' => 'c1')); $ctx = context_course::instance($course->id); $this->assertEquals($data['fullname'], $course->fullname); $this->assertEquals($data['category'], $course->category); $this->assertEquals($data['visible'], $course->visible); $this->assertEquals(mktime(0, 0, 0, 6, 8, 1990), $course->startdate); $this->assertEquals($data['idnumber'], $course->idnumber); $this->assertEquals($data['summary'], $course->summary); $this->assertEquals($data['format'], $course->format); $this->assertEquals($data['theme'], $course->theme); $this->assertEquals($data['lang'], $course->lang); $this->assertEquals($data['newsitems'], $course->newsitems); $this->assertEquals($data['showgrades'], $course->showgrades); $this->assertEquals($data['showreports'], $course->showreports); $this->assertEquals($data['legacyfiles'], $course->legacyfiles); $this->assertEquals($data['maxbytes'], $course->maxbytes); $this->assertEquals($data['groupmode'], $course->groupmode); $this->assertEquals($data['groupmodeforce'], $course->groupmodeforce); $this->assertEquals($data['enablecompletion'], $course->enablecompletion); $this->assertEquals($data['tags'], join(', ', core_tag_tag::get_item_tags_array('core', 'course', $course->id))); // Roles. $roleids = array(); $roles = get_all_roles(); foreach ($roles as $role) { $roleids[$role->shortname] = $role->id; } $this->assertEquals('Knight', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['teacher']))); $this->assertEquals('Jedi', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['manager']))); // Enrolment methods. $enroldata = array(); $instances = enrol_get_instances($course->id, false); $this->assertCount(3, $instances); foreach ($instances as $instance) { $enroldata[$instance->enrol] = $instance; } $this->assertNotEmpty($enroldata['guest']); $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['guest']->status); $this->assertNotEmpty($enroldata['self']); $this->assertEquals($data['enrolment_2_roleid'], $enroldata['self']->roleid); $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['self']->status); $this->assertNotEmpty($enroldata['manual']); $this->assertEquals(ENROL_INSTANCE_DISABLED, $enroldata['manual']->status); // Update existing course. $cat = $this->getDataGenerator()->create_category(); $mode = tool_uploadcourse_processor::MODE_UPDATE_ONLY; $updatemode = tool_uploadcourse_processor::UPDATE_ALL_WITH_DATA_ONLY; $data = array('shortname' => 'c1', 'fullname' => 'Fullname 2', 'category' => $cat->id, 'visible' => '1', 'startdate' => '11 June 1984', 'idnumber' => 'changeidn', 'summary' => 'Summary 2', 'format' => 'topics', 'theme' => 'clean', 'lang' => '', 'newsitems' => '2', 'showgrades' => '1', 'showreports' => '0', 'legacyfiles' => '0', 'maxbytes' => '4321', 'groupmode' => '1', 'groupmodeforce' => '0', 'enablecompletion' => '0', 'role_teacher' => 'Teacher', 'role_manager' => 'Manager', 'enrolment_1' => 'guest', 'enrolment_1_disable' => '1', 'enrolment_2' => 'self', 'enrolment_2_roleid' => '2', 'enrolment_3' => 'manual', 'enrolment_3_delete' => '1'); $this->assertTrue($DB->record_exists('course', array('shortname' => 'c1'))); $co = new tool_uploadcourse_course($mode, $updatemode, $data); $this->assertTrue($co->prepare()); $co->proceed(); $course = $DB->get_record('course', array('shortname' => 'c1')); $ctx = context_course::instance($course->id); $this->assertEquals($data['fullname'], $course->fullname); $this->assertEquals($data['category'], $course->category); $this->assertEquals($data['visible'], $course->visible); $this->assertEquals(mktime(0, 0, 0, 6, 11, 1984), $course->startdate); $this->assertEquals($data['idnumber'], $course->idnumber); $this->assertEquals($data['summary'], $course->summary); $this->assertEquals($data['format'], $course->format); $this->assertEquals($data['theme'], $course->theme); $this->assertEquals($data['lang'], $course->lang); $this->assertEquals($data['newsitems'], $course->newsitems); $this->assertEquals($data['showgrades'], $course->showgrades); $this->assertEquals($data['showreports'], $course->showreports); $this->assertEquals($data['legacyfiles'], $course->legacyfiles); $this->assertEquals($data['maxbytes'], $course->maxbytes); $this->assertEquals($data['groupmode'], $course->groupmode); $this->assertEquals($data['groupmodeforce'], $course->groupmodeforce); $this->assertEquals($data['enablecompletion'], $course->enablecompletion); // Roles. $roleids = array(); $roles = get_all_roles(); foreach ($roles as $role) { $roleids[$role->shortname] = $role->id; } $this->assertEquals('Teacher', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['teacher']))); $this->assertEquals('Manager', $DB->get_field_select('role_names', 'name', 'roleid = :roleid AND contextid = :ctxid', array('ctxid' => $ctx->id, 'roleid' => $roleids['manager']))); // Enrolment methods. $enroldata = array(); $instances = enrol_get_instances($course->id, false); $this->assertCount(2, $instances); foreach ($instances as $instance) { $enroldata[$instance->enrol] = $instance; } $this->assertNotEmpty($enroldata['guest']); $this->assertEquals(ENROL_INSTANCE_DISABLED, $enroldata['guest']->status); $this->assertNotEmpty($enroldata['self']); $this->assertEquals($data['enrolment_2_roleid'], $enroldata['self']->roleid); $this->assertEquals(ENROL_INSTANCE_ENABLED, $enroldata['self']->status); }
/** * Test get_moduleinfo_data */ public function test_get_moduleinfo_data() { global $DB; $this->resetAfterTest(true); $this->setAdminUser(); $course = self::getDataGenerator()->create_course(); $assignmodule = $DB->get_record('modules', array('name' => 'assign'), '*', MUST_EXIST); $assign = self::getDataGenerator()->create_module('assign', array('course' => $course->id)); $assigncm = get_coursemodule_from_id('assign', $assign->cmid); $assigncontext = context_module::instance($assign->cmid); list($cm, $context, $module, $data, $cw) = get_moduleinfo_data($assigncm, $course); $this->assertEquals($assigncm, $cm); $this->assertEquals($assigncontext, $context); $this->assertEquals($assignmodule, $module); // Prepare expected data. $expecteddata = clone $assign; $expecteddata->coursemodule = $assigncm->id; $expecteddata->section = $cw->section; $expecteddata->visible = $assigncm->visible; $expecteddata->cmidnumber = $assigncm->idnumber; $expecteddata->groupmode = groups_get_activity_groupmode($cm); $expecteddata->groupingid = $assigncm->groupingid; $expecteddata->course = $course->id; $expecteddata->module = $module->id; $expecteddata->modulename = $module->name; $expecteddata->instance = $assigncm->instance; $expecteddata->completion = $assigncm->completion; $expecteddata->completionview = $assigncm->completionview; $expecteddata->completionexpected = $assigncm->completionexpected; $expecteddata->completionusegrade = is_null($assigncm->completiongradeitemnumber) ? 0 : 1; $expecteddata->showdescription = $assigncm->showdescription; $expecteddata->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $assigncm->id); $expecteddata->availabilityconditionsjson = null; $expecteddata->advancedgradingmethod_submissions = null; if ($items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => 'assign', 'iteminstance' => $assign->id, 'courseid' => $course->id))) { // set category if present $gradecat = false; foreach ($items as $item) { if ($gradecat === false) { $gradecat = $item->categoryid; continue; } if ($gradecat != $item->categoryid) { //mixed categories $gradecat = false; break; } } if ($gradecat !== false) { // do not set if mixed categories present $expecteddata->gradecat = $gradecat; } } $expecteddata->gradepass = '******'; // Unset untestable. unset($expecteddata->cmid); unset($data->introeditor); unset($data->_advancedgradingdata); $this->assertEquals($expecteddata, $data); // Create a viewer user. Not able to edit. $viewer = self::getDataGenerator()->create_user(); $this->getDataGenerator()->enrol_user($viewer->id, $course->id); $this->setUser($viewer); $this->expectException('required_capability_exception'); get_moduleinfo_data($assigncm, $course); }
public function test_move_tags_with_related() { global $DB; list($collid1, $collid2, $user1, $user2, $blogpost) = $this->prepare_move_tags(); // Set Tag1 to be related to Tag2 and Tag4 (in collection 1). core_tag_tag::get_by_name($collid1, 'Tag1')->set_related_tags(array('Tag2', 'Tag4')); // Set collection for 'post' tag area to be collection 2 and add some tags there. $tagareablog = $DB->get_record('tag_area', array('itemtype' => 'post', 'component' => 'core')); core_tag_area::update($tagareablog, array('tagcollid' => $collid2)); core_tag_tag::set_item_tags('core', 'post', $blogpost->id, context_system::instance(), array('TAG1', 'Tag3')); // Move 'user' area from collection 1 to collection 2, make sure tags were moved completely. $tagarea = $DB->get_record('tag_area', array('itemtype' => 'user', 'component' => 'core')); core_tag_area::update($tagarea, array('tagcollid' => $collid2)); $this->assertEquals(array('Tag1', 'Tag2', 'Tag4'), $DB->get_fieldset_select('tag', 'rawname', 'tagcollid = ? ORDER BY name', array($collid1))); $this->assertEquals(array('TAG1', 'Tag2', 'Tag3', 'Tag4', 'Tag5'), $DB->get_fieldset_select('tag', 'rawname', 'tagcollid = ? ORDER BY name', array($collid2))); $this->assertEquals(array('TAG1', 'Tag2'), array_values(core_tag_tag::get_item_tags_array('core', 'user', $user1->id))); $this->assertEquals(array('Tag2', 'Tag3'), array_values(core_tag_tag::get_item_tags_array('core', 'user', $user2->id))); $tag11 = core_tag_tag::get_by_name($collid1, 'Tag1'); $related11 = tag_get_related_tags($tag11->id, TAG_RELATED_MANUAL); $this->assertDebuggingCalled(); $related11 = array_map('core_tag_tag::make_display_name', $related11); sort($related11); // Order of related tags may be random. $this->assertEquals('Tag2, Tag4', join(', ', $related11)); $tag21 = core_tag_tag::get_by_name($collid2, 'TAG1'); $related21 = tag_get_related_tags($tag21->id, TAG_RELATED_MANUAL); $this->assertDebuggingCalled(); $related21 = array_map('core_tag_tag::make_display_name', $related21); sort($related21); // Order of related tags may be random. $this->assertEquals('Tag2, Tag4', join(', ', $related21)); }
/** * Given a record in the {blog_external} table, checks the blog's URL * for new entries not yet copied into Moodle. * Also attempts to identify and remove deleted blog entries * * @param object $externalblog * @return boolean False if the Feed is invalid */ function blog_sync_external_entries($externalblog) { global $CFG, $DB; require_once $CFG->libdir . '/simplepie/moodle_simplepie.php'; $rss = new moodle_simplepie(); $rssfile = $rss->registry->create('File', array($externalblog->url)); $filetest = $rss->registry->create('Locator', array($rssfile)); if (!$filetest->is_feed($rssfile)) { $externalblog->failedlastsync = 1; $DB->update_record('blog_external', $externalblog); return false; } else { if (!empty($externalblog->failedlastsync)) { $externalblog->failedlastsync = 0; $DB->update_record('blog_external', $externalblog); } } $rss->set_feed_url($externalblog->url); $rss->init(); if (empty($rss->data)) { return null; } // Used to identify blog posts that have been deleted from the source feed. $oldesttimestamp = null; $uniquehashes = array(); foreach ($rss->get_items() as $entry) { // If filtertags are defined, use them to filter the entries by RSS category. if (!empty($externalblog->filtertags)) { $containsfiltertag = false; $categories = $entry->get_categories(); $filtertags = explode(',', $externalblog->filtertags); $filtertags = array_map('trim', $filtertags); $filtertags = array_map('strtolower', $filtertags); if (!empty($categories)) { foreach ($categories as $category) { if (in_array(trim(strtolower($category->term)), $filtertags)) { $containsfiltertag = true; } } } if (!$containsfiltertag) { continue; } } $uniquehashes[] = $entry->get_permalink(); $newentry = new stdClass(); $newentry->userid = $externalblog->userid; $newentry->module = 'blog_external'; $newentry->content = $externalblog->id; $newentry->uniquehash = $entry->get_permalink(); $newentry->publishstate = 'site'; $newentry->format = FORMAT_HTML; // Clean subject of html, just in case. $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT); // Observe 128 max chars in DB. // TODO: +1 to raise this to 255. if (core_text::strlen($newentry->subject) > 128) { $newentry->subject = core_text::substr($newentry->subject, 0, 125) . '...'; } $newentry->summary = $entry->get_description(); // Used to decide whether to insert or update. // Uses enty permalink plus creation date if available. $existingpostconditions = array('uniquehash' => $entry->get_permalink()); // Our DB doesnt allow null creation or modified timestamps so check the external blog supplied one. $entrydate = $entry->get_date('U'); if (!empty($entrydate)) { $existingpostconditions['created'] = $entrydate; } // The post ID or false if post not found in DB. $postid = $DB->get_field('post', 'id', $existingpostconditions); $timestamp = null; if (empty($entrydate)) { $timestamp = time(); } else { $timestamp = $entrydate; } // Only set created if its a new post so we retain the original creation timestamp if the post is edited. if ($postid === false) { $newentry->created = $timestamp; } $newentry->lastmodified = $timestamp; if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) { // Found an older post. $oldesttimestamp = $timestamp; } if (core_text::strlen($newentry->uniquehash) > 255) { // The URL for this item is too long for the field. Rather than add // the entry without the link we will skip straight over it. // RSS spec says recommended length 500, we use 255. debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER); continue; } if ($postid === false) { $id = $DB->insert_record('post', $newentry); // Set tags. if ($tags = core_tag_tag::get_item_tags_array('core', 'blog_external', $externalblog->id)) { core_tag_tag::set_item_tags('core', 'post', $id, context_user::instance($externalblog->userid), $tags); } } else { $newentry->id = $postid; $DB->update_record('post', $newentry); } } // Look at the posts we have in the database to check if any of them have been deleted from the feed. // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or // may just not be returned anymore. We can't tell the difference so we leave older posts alone. $sql = "SELECT id, uniquehash\n FROM {post}\n WHERE module = 'blog_external'\n AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "\n AND created > :ts"; $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp)); $todelete = array(); foreach ($dbposts as $dbpost) { if (!in_array($dbpost->uniquehash, $uniquehashes)) { $todelete[] = $dbpost->id; } } $DB->delete_records_list('post', 'id', $todelete); $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time())); }
public function test_create() { global $DB; $this->resetAfterTest(true); $generator = $this->getDataGenerator(); $count = $DB->count_records('course_categories'); $category = $generator->create_category(); $this->assertEquals($count + 1, $DB->count_records('course_categories')); $this->assertRegExp('/^Course category \\d/', $category->name); $this->assertSame('', $category->idnumber); $this->assertRegExp('/^Test course category \\d/', $category->description); $this->assertSame(FORMAT_MOODLE, $category->descriptionformat); $count = $DB->count_records('cohort'); $cohort = $generator->create_cohort(); $this->assertEquals($count + 1, $DB->count_records('cohort')); $this->assertEquals(context_system::instance()->id, $cohort->contextid); $this->assertRegExp('/^Cohort \\d/', $cohort->name); $this->assertSame('', $cohort->idnumber); $this->assertRegExp('/^Test cohort \\d/', $cohort->description); $this->assertSame(FORMAT_MOODLE, $cohort->descriptionformat); $this->assertSame('', $cohort->component); $this->assertLessThanOrEqual(time(), $cohort->timecreated); $this->assertSame($cohort->timecreated, $cohort->timemodified); $count = $DB->count_records('course'); $course = $generator->create_course(); $this->assertEquals($count + 1, $DB->count_records('course')); $this->assertRegExp('/^Test course \\d/', $course->fullname); $this->assertRegExp('/^tc_\\d/', $course->shortname); $this->assertSame('', $course->idnumber); $this->assertSame('topics', $course->format); $this->assertEquals(0, $course->newsitems); $this->assertEquals(5, $course->numsections); $this->assertRegExp('/^Test course \\d/', $course->summary); $this->assertSame(FORMAT_MOODLE, $course->summaryformat); $section = $generator->create_course_section(array('course' => $course->id, 'section' => 3)); $this->assertEquals($course->id, $section->course); $course = $generator->create_course(array('tags' => 'Cat, Dog')); $this->assertEquals(array('Cat', 'Dog'), array_values(core_tag_tag::get_item_tags_array('core', 'course', $course->id))); $scale = $generator->create_scale(); $this->assertNotEmpty($scale); }
$tag = core_tag_tag::get($tagid, '*'); } } if (empty($tag)) { redirect(new moodle_url('/tag/search.php')); } $PAGE->set_url($tag->get_view_url()); $PAGE->set_subpage($tag->id); $PAGE->set_context($systemcontext); $PAGE->set_blocks_editing_capability('moodle/tag:editblocks'); $PAGE->set_pagelayout('standard'); $tagname = $tag->get_display_name(); $tagcollid = $tag->tagcollid; // set the relatedtags field of the $tag object that will be passed to the form $data = $tag->to_object(); $data->relatedtags = core_tag_tag::get_item_tags_array('core', 'tag', $tag->id); $options = new stdClass(); $options->smiley = false; $options->filter = false; // convert and remove any XSS $data->description = format_text($tag->description, $tag->descriptionformat, $options); $data->descriptionformat = FORMAT_HTML; $errorstring = ''; $editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $CFG->maxbytes, 'trusttext' => false, 'context' => $systemcontext, 'subdirs' => file_area_contains_subdirs($systemcontext, 'tag', 'description', $tag->id)); $data = file_prepare_standard_editor($data, 'description', $editoroptions, $systemcontext, 'tag', 'description', $data->id); $tagform = new tag_edit_form(null, array('editoroptions' => $editoroptions, 'tag' => $tag)); $data->tagtype = $data->tagtype === 'official' ? '1' : '0'; $data->returnurl = $returnurl; $tagform->set_data($data); if ($tagform->is_cancelled()) { redirect($returnurl ? new moodle_url($returnurl) : $tag->get_view_url());
/** * Get module information data required for updating the module. * * @param stdClass $cm course module object * @param stdClass $course course object * @return array required data for updating a module * @since Moodle 3.2 */ function get_moduleinfo_data($cm, $course) { global $CFG; list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm); $data->coursemodule = $cm->id; $data->section = $cw->section; // The section number itself - relative!!! (section column in course_sections) $data->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides $data->cmidnumber = $cm->idnumber; // The cm IDnumber $data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced $data->groupingid = $cm->groupingid; $data->course = $course->id; $data->module = $module->id; $data->modulename = $module->name; $data->instance = $cm->instance; $data->completion = $cm->completion; $data->completionview = $cm->completionview; $data->completionexpected = $cm->completionexpected; $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1; $data->showdescription = $cm->showdescription; $data->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $cm->id); if (!empty($CFG->enableavailability)) { $data->availabilityconditionsjson = $cm->availability; } if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) { $draftid_editor = file_get_submitted_draft_itemid('introeditor'); $currentintro = file_prepare_draft_area($draftid_editor, $context->id, 'mod_' . $data->modulename, 'intro', 0, array('subdirs' => true), $data->intro); $data->introeditor = array('text' => $currentintro, 'format' => $data->introformat, 'itemid' => $draftid_editor); } if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false) and has_capability('moodle/grade:managegradingforms', $context)) { require_once $CFG->dirroot . '/grade/grading/lib.php'; $gradingman = get_grading_manager($context, 'mod_' . $data->modulename); $data->_advancedgradingdata['methods'] = $gradingman->get_available_methods(); $areas = $gradingman->get_available_areas(); foreach ($areas as $areaname => $areatitle) { $gradingman->set_area($areaname); $method = $gradingman->get_active_method(); $data->_advancedgradingdata['areas'][$areaname] = array('title' => $areatitle, 'method' => $method); $formfield = 'advancedgradingmethod_' . $areaname; $data->{$formfield} = $method; } } if ($items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $data->modulename, 'iteminstance' => $data->instance, 'courseid' => $course->id))) { // Add existing outcomes. foreach ($items as $item) { if (!empty($item->outcomeid)) { $data->{'outcome_' . $item->outcomeid} = 1; } else { if (isset($item->gradepass)) { $decimalpoints = $item->get_decimals(); $data->gradepass = format_float($item->gradepass, $decimalpoints); } } } // set category if present $gradecat = false; foreach ($items as $item) { if ($gradecat === false) { $gradecat = $item->categoryid; continue; } if ($gradecat != $item->categoryid) { //mixed categories $gradecat = false; break; } } if ($gradecat !== false) { // do not set if mixed categories present $data->gradecat = $gradecat; } } return array($cm, $context, $module, $data, $cw); }
public function test_create_module() { global $CFG, $SITE, $DB; if (!file_exists("{$CFG->dirroot}/mod/page/")) { $this->markTestSkipped('Can not find standard Page module'); } $this->resetAfterTest(true); $generator = $this->getDataGenerator(); $page = $generator->create_module('page', array('course' => $SITE->id)); $this->assertNotEmpty($page); $cm = get_coursemodule_from_instance('page', $page->id, $SITE->id, true); $this->assertEquals(0, $cm->sectionnum); $page = $generator->create_module('page', array('course' => $SITE->id), array('section' => 3)); $this->assertNotEmpty($page); $cm = get_coursemodule_from_instance('page', $page->id, $SITE->id, true); $this->assertEquals(3, $cm->sectionnum); $page = $generator->create_module('page', array('course' => $SITE->id, 'tags' => 'Cat, Dog')); $this->assertEquals(array('Cat', 'Dog'), array_values(core_tag_tag::get_item_tags_array('core', 'course_modules', $page->cmid))); // Prepare environment to generate modules with all possible options. // Enable advanced functionality. $CFG->enablecompletion = 1; $CFG->enableavailability = 1; $CFG->enableoutcomes = 1; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->libdir . '/completionlib.php'; require_once $CFG->dirroot . '/rating/lib.php'; // Create a course with enabled completion. $course = $generator->create_course(array('enablecompletion' => true)); // Create new grading category in this course. $grade_category = new grade_category(); $grade_category->courseid = $course->id; $grade_category->fullname = 'Grade category'; $grade_category->insert(); // Create group and grouping. $group = $generator->create_group(array('courseid' => $course->id)); $grouping = $generator->create_grouping(array('courseid' => $course->id)); $generator->create_grouping_group(array('groupid' => $group->id, 'groupingid' => $grouping->id)); // Prepare arrays with properties that we can both use for creating modules and asserting the data in created modules. // General properties. $optionsgeneral = array('visible' => 0, 'section' => 3, 'cmidnumber' => 'IDNUM', 'groupmode' => SEPARATEGROUPS, 'groupingid' => $grouping->id); // In case completion is enabled on site and for course every module can have manual completion. $featurecompletionmanual = array('completion' => COMPLETION_TRACKING_MANUAL, 'completionexpected' => time() + 7 * DAYSECS); // Automatic completion is possible if module supports FEATURE_COMPLETION_TRACKS_VIEWS or FEATURE_GRADE_HAS_GRADE. // Note: completionusegrade is stored in DB and can be found in cm_info as 'completiongradeitemnumber' - either NULL or 0. // Note: module can have more autocompletion rules as defined in moodleform_mod::add_completion_rules(). $featurecompletionautomatic = array('completion' => COMPLETION_TRACKING_AUTOMATIC, 'completionview' => 1, 'completionusegrade' => 1); // Module supports FEATURE_RATE: $featurerate = array('assessed' => RATING_AGGREGATE_AVERAGE, 'scale' => 100, 'ratingtime' => 1, 'assesstimestart' => time() - DAYSECS, 'assesstimefinish' => time() + DAYSECS); // Module supports FEATURE_GRADE_HAS_GRADE: $featuregrade = array('grade' => 10, 'gradecat' => $grade_category->id); // Now let's create several modules with different options. $m1 = $generator->create_module('assign', array('course' => $course->id) + $optionsgeneral); $m2 = $generator->create_module('data', array('course' => $course->id) + $featurecompletionmanual + $featurerate); $m3 = $generator->create_module('assign', array('course' => $course->id) + $featurecompletionautomatic + $featuregrade); // We need id of the grading item for the second module to create availability dependency in the 3rd module. $gradingitem = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod', 'itemmodule' => 'assign', 'iteminstance' => $m3->id)); // Now prepare option to create the 4th module with an availability condition. $optionsavailability = array('availability' => '{"op":"&","showc":[true],"c":[' . '{"type":"date","d":">=","t":' . (time() - WEEKSECS) . '}]}'); // Create module with conditional availability. $m4 = $generator->create_module('assign', array('course' => $course->id) + $optionsavailability); // Verifying that everything is generated correctly. $modinfo = get_fast_modinfo($course->id); $cm1 = $modinfo->cms[$m1->cmid]; $this->assertEquals($optionsgeneral['visible'], $cm1->visible); $this->assertEquals($optionsgeneral['section'], $cm1->sectionnum); // Note difference in key. $this->assertEquals($optionsgeneral['cmidnumber'], $cm1->idnumber); // Note difference in key. $this->assertEquals($optionsgeneral['groupmode'], $cm1->groupmode); $this->assertEquals($optionsgeneral['groupingid'], $cm1->groupingid); $cm2 = $modinfo->cms[$m2->cmid]; $this->assertEquals($featurecompletionmanual['completion'], $cm2->completion); $this->assertEquals($featurecompletionmanual['completionexpected'], $cm2->completionexpected); $this->assertEquals(null, $cm2->completiongradeitemnumber); // Rating info is stored in the module's table (in our test {data}). $data = $DB->get_record('data', array('id' => $m2->id)); $this->assertEquals($featurerate['assessed'], $data->assessed); $this->assertEquals($featurerate['scale'], $data->scale); $this->assertEquals($featurerate['assesstimestart'], $data->assesstimestart); $this->assertEquals($featurerate['assesstimefinish'], $data->assesstimefinish); // No validation for 'ratingtime'. It is only used in to enable/disable assesstime* when adding module. $cm3 = $modinfo->cms[$m3->cmid]; $this->assertEquals($featurecompletionautomatic['completion'], $cm3->completion); $this->assertEquals($featurecompletionautomatic['completionview'], $cm3->completionview); $this->assertEquals(0, $cm3->completiongradeitemnumber); // Zero instead of default null since 'completionusegrade' was set. $gradingitem = grade_item::fetch(array('courseid' => $course->id, 'itemtype' => 'mod', 'itemmodule' => 'assign', 'iteminstance' => $m3->id)); $this->assertEquals(0, $gradingitem->grademin); $this->assertEquals($featuregrade['grade'], $gradingitem->grademax); $this->assertEquals($featuregrade['gradecat'], $gradingitem->categoryid); $cm4 = $modinfo->cms[$m4->cmid]; $this->assertEquals($optionsavailability['availability'], $cm4->availability); }
/** * Testing function core_tag_tag::combine_tags() */ public function test_combine_tags() { $initialtags = array(array('Cat', 'Dog'), array('Dog', 'Cat'), array('Cats', 'Hippo'), array('Hippo', 'Cats'), array('Cat', 'Mouse', 'Kitten'), array('Cats', 'Mouse', 'Kitten'), array('Kitten', 'Mouse', 'Cat'), array('Kitten', 'Mouse', 'Cats'), array('Cats', 'Mouse', 'Kitten'), array('Mouse', 'Hippo')); $finaltags = array(array('Cat', 'Dog'), array('Dog', 'Cat'), array('Cat', 'Hippo'), array('Hippo', 'Cat'), array('Cat', 'Mouse'), array('Cat', 'Mouse'), array('Mouse', 'Cat'), array('Mouse', 'Cat'), array('Cat', 'Mouse'), array('Mouse', 'Hippo')); $collid = core_tag_collection::get_default(); $context = context_system::instance(); foreach ($initialtags as $id => $taglist) { core_tag_tag::set_item_tags('core', 'course', $id + 10, $context, $initialtags[$id]); } core_tag_tag::get_by_name($collid, 'Cats', '*')->update(array('isstandard' => 1)); // Combine tags 'Cats' and 'Kitten' into 'Cat'. $cat = core_tag_tag::get_by_name($collid, 'Cat', '*'); $cats = core_tag_tag::get_by_name($collid, 'Cats', '*'); $kitten = core_tag_tag::get_by_name($collid, 'Kitten', '*'); $cat->combine_tags(array($cats, $kitten)); foreach ($finaltags as $id => $taglist) { $this->assertEquals($taglist, array_values(core_tag_tag::get_item_tags_array('core', 'course', $id + 10)), 'Original array (' . join(', ', $initialtags[$id]) . ')'); } // Ensure combined tags are deleted and 'Cat' is now official (because 'Cats' was official). $this->assertEmpty(core_tag_tag::get_by_name($collid, 'Cats')); $this->assertEmpty(core_tag_tag::get_by_name($collid, 'Kitten')); $cattag = core_tag_tag::get_by_name($collid, 'Cat', '*'); $this->assertEquals(1, $cattag->isstandard); }
/** * * Give user record from mdl_user, build an array contains all user details. * * Warning: description file urls are 'webservice/pluginfile.php' is use. * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile * * @throws moodle_exception * @param stdClass $user user record from mdl_user * @param stdClass $course moodle course * @param array $userfields required fields * @return array|null */ function user_get_user_details($user, $course = null, array $userfields = array()) { global $USER, $DB, $CFG, $PAGE; require_once $CFG->dirroot . "/user/profile/lib.php"; // Custom field library. require_once $CFG->dirroot . "/lib/filelib.php"; // File handling on description and friends. $defaultfields = user_get_default_fields(); if (empty($userfields)) { $userfields = $defaultfields; } foreach ($userfields as $thefield) { if (!in_array($thefield, $defaultfields)) { throw new moodle_exception('invaliduserfield', 'error', '', $thefield); } } // Make sure id and fullname are included. if (!in_array('id', $userfields)) { $userfields[] = 'id'; } if (!in_array('fullname', $userfields)) { $userfields[] = 'fullname'; } if (!empty($course)) { $context = context_course::instance($course->id); $usercontext = context_user::instance($user->id); $canviewdetailscap = has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext); } else { $context = context_user::instance($user->id); $usercontext = $context; $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext); } $currentuser = $user->id == $USER->id; $isadmin = is_siteadmin($USER); $showuseridentityfields = get_extra_user_fields($context); if (!empty($course)) { $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context); } else { $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context); } $canviewfullnames = has_capability('moodle/site:viewfullnames', $context); if (!empty($course)) { $canviewuseremail = has_capability('moodle/course:useremail', $context); } else { $canviewuseremail = false; } $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id)); if (!empty($course)) { $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context); } else { $canaccessallgroups = false; } if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) { // Skip this user details. return null; } $userdetails = array(); $userdetails['id'] = $user->id; if (in_array('username', $userfields)) { if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) { $userdetails['username'] = $user->username; } } if ($isadmin or $canviewfullnames) { if (in_array('firstname', $userfields)) { $userdetails['firstname'] = $user->firstname; } if (in_array('lastname', $userfields)) { $userdetails['lastname'] = $user->lastname; } } $userdetails['fullname'] = fullname($user); if (in_array('customfields', $userfields)) { $fields = $DB->get_recordset_sql("SELECT f.*\n FROM {user_info_field} f\n JOIN {user_info_category} c\n ON f.categoryid=c.id\n ORDER BY c.sortorder ASC, f.sortorder ASC"); $userdetails['customfields'] = array(); foreach ($fields as $field) { require_once $CFG->dirroot . '/user/profile/field/' . $field->datatype . '/field.class.php'; $newfield = 'profile_field_' . $field->datatype; $formfield = new $newfield($field->id, $user->id); if ($formfield->is_visible() and !$formfield->is_empty()) { // TODO: Part of MDL-50728, this conditional coding must be moved to // proper profile fields API so they are self-contained. // We only use display_data in fields that require text formatting. if ($field->datatype == 'text' or $field->datatype == 'textarea') { $fieldvalue = $formfield->display_data(); } else { // Cases: datetime, checkbox and menu. $fieldvalue = $formfield->data; } $userdetails['customfields'][] = array('name' => $formfield->field->name, 'value' => $fieldvalue, 'type' => $field->datatype, 'shortname' => $formfield->field->shortname); } } $fields->close(); // Unset customfields if it's empty. if (empty($userdetails['customfields'])) { unset($userdetails['customfields']); } } // Profile image. if (in_array('profileimageurl', $userfields)) { $userpicture = new user_picture($user); $userpicture->size = 1; // Size f1. $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); } if (in_array('profileimageurlsmall', $userfields)) { if (!isset($userpicture)) { $userpicture = new user_picture($user); } $userpicture->size = 0; // Size f2. $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false); } // Hidden user field. if ($canviewhiddenuserfields) { $hiddenfields = array(); // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability // according to user/profile.php. if ($user->address && in_array('address', $userfields)) { $userdetails['address'] = $user->address; } } else { $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); } if ($user->phone1 && in_array('phone1', $userfields) && (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) { $userdetails['phone1'] = $user->phone1; } if ($user->phone2 && in_array('phone2', $userfields) && (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) { $userdetails['phone2'] = $user->phone2; } if (isset($user->description) && (!isset($hiddenfields['description']) && !$cannotviewdescription or $isadmin)) { if (in_array('description', $userfields)) { // Always return the descriptionformat if description is requested. list($userdetails['description'], $userdetails['descriptionformat']) = external_format_text($user->description, $user->descriptionformat, $usercontext->id, 'user', 'profile', null); } } if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) { $userdetails['country'] = $user->country; } if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) { $userdetails['city'] = $user->city; } if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) { $url = $user->url; if (strpos($user->url, '://') === false) { $url = 'http://' . $url; } $user->url = clean_param($user->url, PARAM_URL); $userdetails['url'] = $user->url; } if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) { $userdetails['icq'] = $user->icq; } if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) { $userdetails['skype'] = $user->skype; } if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) { $userdetails['yahoo'] = $user->yahoo; } if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) { $userdetails['aim'] = $user->aim; } if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) { $userdetails['msn'] = $user->msn; } if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) { if ($user->firstaccess) { $userdetails['firstaccess'] = $user->firstaccess; } else { $userdetails['firstaccess'] = 0; } } if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) { if ($user->lastaccess) { $userdetails['lastaccess'] = $user->lastaccess; } else { $userdetails['lastaccess'] = 0; } } if (in_array('email', $userfields) && ($isadmin or $currentuser or $canviewuseremail or in_array('email', $showuseridentityfields) or $user->maildisplay == 1 or $user->maildisplay == 2 and enrol_sharing_course($user, $USER))) { $userdetails['email'] = $user->email; } if (in_array('interests', $userfields)) { $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false); if ($interests) { $userdetails['interests'] = join(', ', $interests); } } // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile. if (in_array('idnumber', $userfields) && $user->idnumber) { if (in_array('idnumber', $showuseridentityfields) or $currentuser or has_capability('moodle/user:viewalldetails', $context)) { $userdetails['idnumber'] = $user->idnumber; } } if (in_array('institution', $userfields) && $user->institution) { if (in_array('institution', $showuseridentityfields) or $currentuser or has_capability('moodle/user:viewalldetails', $context)) { $userdetails['institution'] = $user->institution; } } // Isset because it's ok to have department 0. if (in_array('department', $userfields) && isset($user->department)) { if (in_array('department', $showuseridentityfields) or $currentuser or has_capability('moodle/user:viewalldetails', $context)) { $userdetails['department'] = $user->department; } } if (in_array('roles', $userfields) && !empty($course)) { // Not a big secret. $roles = get_user_roles($context, $user->id, false); $userdetails['roles'] = array(); foreach ($roles as $role) { $userdetails['roles'][] = array('roleid' => $role->roleid, 'name' => $role->name, 'shortname' => $role->shortname, 'sortorder' => $role->sortorder); } } // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group. if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) { $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name,g.description,g.descriptionformat'); $userdetails['groups'] = array(); foreach ($usergroups as $group) { list($group->description, $group->descriptionformat) = external_format_text($group->description, $group->descriptionformat, $context->id, 'group', 'description', $group->id); $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name, 'description' => $group->description, 'descriptionformat' => $group->descriptionformat); } } // List of courses where the user is enrolled. if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) { $enrolledcourses = array(); if ($mycourses = enrol_get_users_courses($user->id, true)) { foreach ($mycourses as $mycourse) { if ($mycourse->category) { $coursecontext = context_course::instance($mycourse->id); $enrolledcourse = array(); $enrolledcourse['id'] = $mycourse->id; $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext)); $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext)); $enrolledcourses[] = $enrolledcourse; } } $userdetails['enrolledcourses'] = $enrolledcourses; } } // User preferences. if (in_array('preferences', $userfields) && $currentuser) { $preferences = array(); $userpreferences = get_user_preferences(); foreach ($userpreferences as $prefname => $prefvalue) { $preferences[] = array('name' => $prefname, 'value' => $prefvalue); } $userdetails['preferences'] = $preferences; } return $userdetails; }
/** * Get a comma-separated string of tags associated to a record. * * Use {@link tag_get_tags()} to get the same information in an array. * * @package core_tag * @deprecated since 3.1 * @param string $record_type the record type for which we want to get the tags * @param int $record_id the record id for which we want to get the tags * @param int $html either TAG_RETURN_HTML or TAG_RETURN_TEXT, depending on the type of output desired * @param string $type either 'official' or 'default', if null, all tags are returned * @return string the comma-separated list of tags. */ function tag_get_tags_csv($record_type, $record_id, $html = null, $type = null) { global $CFG, $OUTPUT; debugging('Method tag_get_tags_csv() is deprecated. Instead you should use either ' . 'core_tag_tag::get_item_tags_array() or $OUTPUT->tag_list(core_tag_tag::get_item_tags()). ' . 'Component is now required when retrieving tag instances.', DEBUG_DEVELOPER); $standardonly = $type === 'official' ? core_tag_tag::STANDARD_ONLY : (!empty($type) ? core_tag_tag::NOT_STANDARD_ONLY : core_tag_tag::BOTH_STANDARD_AND_NOT); if ($html != TAG_RETURN_TEXT) { return $OUTPUT->tag_list(core_tag_tag::get_item_tags('', $record_type, $record_id, $standardonly), ''); } else { return join(', ', core_tag_tag::get_item_tags_array('', $record_type, $record_id, $standardonly, 0, false)); } }
require_login(); // Check capabilities but do not call require_login($course) - the user does not have to be enrolled. $context = context_course::instance($course->id); if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) { print_error('coursehidden', '', $CFG->wwwroot . '/'); } require_capability('moodle/course:tag', $context); if (!core_tag_tag::is_enabled('core', 'course')) { print_error('tagsaredisabled', 'tag'); } $PAGE->set_course($course); $PAGE->set_pagelayout('incourse'); $PAGE->set_url('/course/tags.php', array('id' => $course->id)); $PAGE->set_title(get_string('coursetags', 'tag')); $PAGE->set_heading($course->fullname); $form = new coursetags_form(); $data = array('id' => $course->id, 'tags' => core_tag_tag::get_item_tags_array('core', 'course', $course->id)); $form->set_data($data); $redirecturl = $returnurl ? new moodle_url($returnurl) : course_get_url($course); if ($form->is_cancelled()) { redirect($redirecturl); } else { if ($data = $form->get_data()) { core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags); redirect($redirecturl); } } echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('coursetags', 'tag')); $form->display(); echo $OUTPUT->footer();
$entry->courseassoc = $assocrec->contextid; break; case CONTEXT_MODULE: $entry->modassoc = $assocrec->contextid; break; } } } } $summaryoptions = array('maxfiles' => 99, 'maxbytes' => $CFG->maxbytes, 'trusttext' => true, 'context' => $sitecontext, 'subdirs' => file_area_contains_subdirs($sitecontext, 'blog', 'post', $entry->id)); $attachmentoptions = array('subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes); $blogeditform = new blog_edit_form(null, compact('entry', 'summaryoptions', 'attachmentoptions', 'sitecontext', 'courseid', 'modid')); $entry = file_prepare_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id); $entry = file_prepare_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id); if (!empty($entry->id)) { $entry->tags = core_tag_tag::get_item_tags_array('core', 'post', $entry->id); } $entry->action = $action; // Set defaults. $blogeditform->set_data($entry); if ($blogeditform->is_cancelled()) { redirect($returnurl); } else { if ($data = $blogeditform->get_data()) { switch ($action) { case 'add': $blogentry = new blog_entry(null, $data, $blogeditform); $blogentry->add(); $blogentry->edit($data, $blogeditform, $summaryoptions, $attachmentoptions); break; case 'edit':
/** * Adds all the standard elements to a form to edit the settings for an activity module. */ function standard_coursemodule_elements() { global $COURSE, $CFG, $DB; $mform =& $this->_form; $this->_outcomesused = false; if ($this->_features->outcomes) { if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) { $this->_outcomesused = true; $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades')); foreach ($outcomes as $outcome) { $mform->addElement('advcheckbox', 'outcome_' . $outcome->id, $outcome->get_name()); } } } if ($this->_features->rating) { require_once $CFG->dirroot . '/rating/lib.php'; $rm = new rating_manager(); $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating')); $permission = CAP_ALLOW; $rolenamestring = null; $isupdate = false; if (!empty($this->_cm)) { $isupdate = true; $context = context_module::instance($this->_cm->id); $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/' . $this->_cm->modname . ':rate')); $rolenamestring = implode(', ', $rolenames); } else { $rolenamestring = get_string('capabilitychecknotavailable', 'rating'); } $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring); $mform->addHelpButton('rolewarning', 'rolewarning', 'rating'); $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating'), $rm->get_aggregate_types()); $mform->setDefault('assessed', 0); $mform->addHelpButton('assessed', 'aggregatetype', 'rating'); $gradeoptions = array('isupdate' => $isupdate, 'currentgrade' => false, 'hasgrades' => false, 'canrescale' => $this->_features->canrescale, 'useratings' => $this->_features->rating); if ($isupdate) { $gradeitem = grade_item::fetch(array('itemtype' => 'mod', 'itemmodule' => $this->_cm->modname, 'iteminstance' => $this->_cm->instance, 'itemnumber' => 0, 'courseid' => $COURSE->id)); if ($gradeitem) { $gradeoptions['currentgrade'] = $gradeitem->grademax; $gradeoptions['currentgradetype'] = $gradeitem->gradetype; $gradeoptions['currentscaleid'] = $gradeitem->scaleid; $gradeoptions['hasgrades'] = $gradeitem->has_grades(); } } $mform->addElement('modgrade', 'scale', get_string('scale'), $gradeoptions); $mform->disabledIf('scale', 'assessed', 'eq', 0); $mform->addHelpButton('scale', 'modgrade', 'grades'); $mform->setDefault('scale', $CFG->gradepointdefault); $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating')); $mform->disabledIf('ratingtime', 'assessed', 'eq', 0); $mform->addElement('date_time_selector', 'assesstimestart', get_string('from')); $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0); $mform->disabledIf('assesstimestart', 'ratingtime'); $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to')); $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0); $mform->disabledIf('assesstimefinish', 'ratingtime'); } //doing this here means splitting up the grade related settings on the lesson settings page //$this->standard_grading_coursemodule_elements(); $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form')); $mform->addElement('modvisible', 'visible', get_string('visible')); if (!empty($this->_cm)) { $context = context_module::instance($this->_cm->id); if (!has_capability('moodle/course:activityvisibility', $context)) { $mform->hardFreeze('visible'); } } if ($this->_features->idnumber) { $mform->addElement('text', 'cmidnumber', get_string('idnumbermod')); $mform->setType('cmidnumber', PARAM_RAW); $mform->addHelpButton('cmidnumber', 'idnumbermod'); } if ($this->_features->groups) { $options = array(NOGROUPS => get_string('groupsnone'), SEPARATEGROUPS => get_string('groupsseparate'), VISIBLEGROUPS => get_string('groupsvisible')); $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS); $mform->addHelpButton('groupmode', 'groupmode', 'group'); } if ($this->_features->groupings) { // Groupings selector - used to select grouping for groups in activity. $options = array(); if ($groupings = $DB->get_records('groupings', array('courseid' => $COURSE->id))) { foreach ($groupings as $grouping) { $options[$grouping->id] = format_string($grouping->name); } } core_collator::asort($options); $options = array(0 => get_string('none')) + $options; $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options); $mform->addHelpButton('groupingid', 'grouping', 'group'); } if (!empty($CFG->enableavailability)) { // Add special button to end of previous section if groups/groupings // are enabled. if ($this->_features->groups || $this->_features->groupings) { $mform->addElement('static', 'restrictgroupbutton', '', html_writer::tag('button', get_string('restrictbygroup', 'availability'), array('id' => 'restrictbygroup', 'disabled' => 'disabled'))); } // Availability field. This is just a textarea; the user interface // interaction is all implemented in JavaScript. $mform->addElement('header', 'availabilityconditionsheader', get_string('restrictaccess', 'availability')); // Note: This field cannot be named 'availability' because that // conflicts with fields in existing modules (such as assign). // So it uses a long name that will not conflict. $mform->addElement('textarea', 'availabilityconditionsjson', get_string('accessrestrictions', 'availability')); // The _cm variable may not be a proper cm_info, so get one from modinfo. if ($this->_cm) { $modinfo = get_fast_modinfo($COURSE); $cm = $modinfo->get_cm($this->_cm->id); } else { $cm = null; } \core_availability\frontend::include_all_javascript($COURSE, $cm); } // Conditional activities: completion tracking section if (!isset($completion)) { $completion = new completion_info($COURSE); } if ($completion->is_enabled()) { $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion')); // Unlock button for if people have completed it (will // be removed in definition_after_data if they haven't) $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion')); $mform->registerNoSubmitButton('unlockcompletion'); $mform->addElement('hidden', 'completionunlocked', 0); $mform->setType('completionunlocked', PARAM_INT); $trackingdefault = COMPLETION_TRACKING_NONE; // If system and activity default is on, set it. if ($CFG->completiondefault && $this->_features->defaultcompletion) { $trackingdefault = COMPLETION_TRACKING_MANUAL; } $mform->addElement('select', 'completion', get_string('completion', 'completion'), array(COMPLETION_TRACKING_NONE => get_string('completion_none', 'completion'), COMPLETION_TRACKING_MANUAL => get_string('completion_manual', 'completion'))); $mform->setDefault('completion', $trackingdefault); $mform->addHelpButton('completion', 'completion', 'completion'); // Automatic completion once you view it $gotcompletionoptions = false; if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) { $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'), get_string('completionview_desc', 'completion')); $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC); $gotcompletionoptions = true; } // Automatic completion once it's graded if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) { $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'), get_string('completionusegrade_desc', 'completion')); $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC); $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion'); $gotcompletionoptions = true; // If using the rating system, there is no grade unless ratings are enabled. if ($this->_features->rating) { $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0); } } // Automatic completion according to module-specific rules $this->_customcompletionelements = $this->add_completion_rules(); foreach ($this->_customcompletionelements as $element) { $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC); } $gotcompletionoptions = $gotcompletionoptions || count($this->_customcompletionelements) > 0; // Automatic option only appears if possible if ($gotcompletionoptions) { $mform->getElement('completion')->addOption(get_string('completion_automatic', 'completion'), COMPLETION_TRACKING_AUTOMATIC); } // Completion expected at particular date? (For progress tracking) $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional' => true)); $mform->addHelpButton('completionexpected', 'completionexpected', 'completion'); $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE); } // Populate module tags. if (core_tag_tag::is_enabled('core', 'course_modules')) { $mform->addElement('header', 'tagshdr', get_string('tags', 'tag')); $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core')); if ($this->_cm) { $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id); $mform->setDefault('tags', $tags); } } $this->standard_hidden_coursemodule_elements(); $this->plugin_extend_coursemodule_standard_elements(); }
protected function print_edit($content = null) { global $CFG, $OUTPUT, $USER, $PAGE; if (!$this->check_locks()) { return; } //delete old locks (> 1 hour) wiki_delete_old_locks(); $version = wiki_get_current_version($this->page->id); $format = $version->contentformat; if ($content == null) { if (empty($this->section)) { $content = $version->content; } else { $content = $this->sectioncontent; } } $versionnumber = $version->version; if ($this->versionnumber >= 0) { if ($version->version != $this->versionnumber) { print $OUTPUT->box(get_string('wrongversionlock', 'wiki'), 'errorbox'); $versionnumber = $this->versionnumber; } } $url = $CFG->wwwroot . '/mod/wiki/edit.php?pageid=' . $this->page->id; if (!empty($this->section)) { $url .= "§ion=" . urlencode($this->section); } $params = array('attachmentoptions' => page_wiki_edit::$attachmentoptions, 'format' => $version->contentformat, 'version' => $versionnumber, 'pagetitle' => $this->page->title, 'contextid' => $this->modcontext->id); $data = new StdClass(); $data->newcontent = $content; $data->version = $versionnumber; $data->format = $format; switch ($format) { case 'html': $data->newcontentformat = FORMAT_HTML; // Append editor context to editor options, giving preference to existing context. page_wiki_edit::$attachmentoptions = array_merge(array('context' => $this->modcontext), page_wiki_edit::$attachmentoptions); $data = file_prepare_standard_editor($data, 'newcontent', page_wiki_edit::$attachmentoptions, $this->modcontext, 'mod_wiki', 'attachments', $this->subwiki->id); break; default: break; } if ($version->contentformat != 'html') { $params['fileitemid'] = $this->subwiki->id; $params['component'] = 'mod_wiki'; $params['filearea'] = 'attachments'; } $data->tags = core_tag_tag::get_item_tags_array('mod_wiki', 'wiki_pages', $this->page->id); $form = new mod_wiki_edit_form($url, $params); $form->set_data($data); $form->display(); }
if ($id !== null) { $url->param('id', $id); } $PAGE->set_url($url); $PAGE->set_context(context_user::instance($USER->id)); $PAGE->set_pagelayout('admin'); $returnurl = new moodle_url('/blog/external_blogs.php'); $action = empty($id) ? 'add' : 'edit'; $external = new stdClass(); // Check that this id exists. if (!empty($id) && !$DB->record_exists('blog_external', array('id' => $id))) { print_error('wrongexternalid', 'blog'); } else { if (!empty($id)) { $external = $DB->get_record('blog_external', array('id' => $id)); $external->autotags = core_tag_tag::get_item_tags_array('core', 'blog_external', $id); } } $strformheading = $action == 'edit' ? get_string('editexternalblog', 'blog') : get_string('addnewexternalblog', 'blog'); $strexternalblogs = get_string('externalblogs', 'blog'); $strblogs = get_string('blogs', 'blog'); $externalblogform = new blog_edit_external_form(); if ($externalblogform->is_cancelled()) { redirect($returnurl); } else { if ($data = $externalblogform->get_data()) { // Save stuff in db. switch ($action) { case 'add': $rss = new moodle_simplepie($data->url); $newexternal = new stdClass();
} } // Guest can not edit. if (isguestuser()) { print_error('guestnoeditprofile'); } // The user profile we are editing. if (!($user = $DB->get_record('user', array('id' => $userid)))) { print_error('invaliduserid'); } // Guest can not be edited. if (isguestuser($user)) { print_error('guestnoeditprofile'); } // User interests separated by commas. $user->interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id); // Remote users cannot be edited. We have to perform the strict // user_not_fully_set_up() check, otherwise the remote user could end up in // endless loop between user/view.php and herein. Note that required custom // fields are not supported in MNet environment anyway. if (is_mnet_remote_user($user)) { if (user_not_fully_set_up($user, true)) { $hostwwwroot = $DB->get_field('mnet_host', 'wwwroot', array('id' => $user->mnethostid)); print_error('usernotfullysetup', 'mnet', '', $hostwwwroot); } redirect($CFG->wwwroot . "/user/view.php?course={$course->id}"); } // Load the appropriate auth plugin. $userauth = get_auth_plugin($user->auth); if (!$userauth->can_edit_profile()) { print_error('noprofileedit', 'auth');
$data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced $data->groupingid = $cm->groupingid; $data->course = $course->id; $data->module = $module->id; $data->modulename = $module->name; $data->instance = $cm->instance; $data->return = $return; $data->sr = $sectionreturn; $data->update = $update; $data->completion = $cm->completion; $data->completionview = $cm->completionview; $data->completionexpected = $cm->completionexpected; $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1; $data->showdescription = $cm->showdescription; $data->tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $cm->id); if (!empty($CFG->enableavailability)) { $data->availabilityconditionsjson = $cm->availability; } if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) { $draftid_editor = file_get_submitted_draft_itemid('introeditor'); $currentintro = file_prepare_draft_area($draftid_editor, $context->id, 'mod_' . $data->modulename, 'intro', 0, array('subdirs' => true), $data->intro); $data->introeditor = array('text' => $currentintro, 'format' => $data->introformat, 'itemid' => $draftid_editor); } if (plugin_supports('mod', $data->modulename, FEATURE_ADVANCED_GRADING, false) and has_capability('moodle/grade:managegradingforms', $context)) { require_once $CFG->dirroot . '/grade/grading/lib.php'; $gradingman = get_grading_manager($context, 'mod_' . $data->modulename); $data->_advancedgradingdata['methods'] = $gradingman->get_available_methods(); $areas = $gradingman->get_available_areas(); foreach ($areas as $areaname => $areatitle) { $gradingman->set_area($areaname);