Merge branch 'MDL-55785-master' of git://github.com/jleyva/moodle

This commit is contained in:
Eloy Lafuente (stronk7) 2016-09-28 19:59:20 +02:00
commit 7bc32ebccd
7 changed files with 461 additions and 122 deletions

View file

@ -226,6 +226,7 @@ class mod_glossary_external extends external_api {
$modes[$glossary->displayformat] = self::get_browse_modes_from_display_format($glossary->displayformat);
}
$glossary->browsemodes = $modes[$glossary->displayformat];
$glossary->canaddentry = has_capability('mod/glossary:write', $context) ? 1 : 0;
}
}
@ -292,7 +293,8 @@ class mod_glossary_external extends external_api {
'groupingid' => new external_value(PARAM_INT, 'Grouping ID'),
'browsemodes' => new external_multiple_structure(
new external_value(PARAM_ALPHA, 'Modes of browsing allowed')
)
),
'canaddentry' => new external_value(PARAM_INT, 'Whether the user can add a new entry', VALUE_OPTIONAL),
), 'Glossaries')
),
'warnings' => new external_warnings())
@ -1395,4 +1397,136 @@ class mod_glossary_external extends external_api {
));
}
/**
* Returns the description of the external function parameters.
*
* @return external_function_parameters
* @since Moodle 3.2
*/
public static function add_entry_parameters() {
return new external_function_parameters(array(
'glossaryid' => new external_value(PARAM_INT, 'Glossary id'),
'concept' => new external_value(PARAM_TEXT, 'Glossary concept'),
'definition' => new external_value(PARAM_TEXT, 'Glossary concept definition'),
'definitionformat' => new external_format_value('definition'),
'options' => new external_multiple_structure (
new external_single_structure(
array(
'name' => new external_value(PARAM_ALPHANUM,
'The allowed keys (value format) are:
inlineattachmentsid (int); the draft file area id for inline attachments
attachmentsid (int); the draft file area id for attachments
categories (comma separated int); comma separated category ids
aliases (comma separated str); comma separated aliases
usedynalink (bool); whether the entry should be automatically linked.
casesensitive (bool); whether the entry is case sensitive.
fullmatch (bool); whether to match whole words only.'),
'value' => new external_value(PARAM_RAW, 'the value of the option (validated inside the function)')
)
), 'Optional settings', VALUE_DEFAULT, array()
)
));
}
/**
* Add a new entry to a given glossary.
*
* @param int $glossaryid the glosary id
* @param string $concept the glossary concept
* @param string $definition the concept definition
* @param int $definitionformat the concept definition format
* @param array $options additional settings
* @return array Containing entry and warnings.
* @since Moodle 3.2
* @throws moodle_exception
* @throws invalid_parameter_exception
*/
public static function add_entry($glossaryid, $concept, $definition, $definitionformat, $options = array()) {
global $CFG;
$params = self::validate_parameters(self::add_entry_parameters(), array(
'glossaryid' => $glossaryid,
'concept' => $concept,
'definition' => $definition,
'definitionformat' => $definitionformat,
'options' => $options,
));
$warnings = array();
// Get and validate the glossary.
list($glossary, $context, $course, $cm) = self::validate_glossary($params['glossaryid']);
require_capability('mod/glossary:write', $context);
if (!$glossary->allowduplicatedentries) {
if (glossary_concept_exists($glossary, $params['concept'])) {
throw new moodle_exception('errconceptalreadyexists', 'glossary');
}
}
// Prepare the entry object.
$entry = new stdClass;
$entry->id = null;
$entry->aliases = '';
$entry->usedynalink = $CFG->glossary_linkentries;
$entry->casesensitive = $CFG->glossary_casesensitive;
$entry->fullmatch = $CFG->glossary_fullmatch;
$entry->concept = $params['concept'];
$entry->definition_editor = array(
'text' => $params['definition'],
'format' => $params['definitionformat'],
);
// Options.
foreach ($params['options'] as $option) {
$name = trim($option['name']);
switch ($name) {
case 'inlineattachmentsid':
$entry->definition_editor['itemid'] = clean_param($option['value'], PARAM_INT);
break;
case 'attachmentsid':
$entry->attachment_filemanager = clean_param($option['value'], PARAM_INT);
break;
case 'categories':
$entry->categories = clean_param($option['value'], PARAM_SEQUENCE);
$entry->categories = explode(',', $entry->categories);
break;
case 'aliases':
$entry->aliases = clean_param($option['value'], PARAM_NOTAGS);
// Convert to the expected format.
$entry->aliases = str_replace(",", "\n", $entry->aliases);
break;
case 'usedynalink':
case 'casesensitive':
case 'fullmatch':
// Only allow if linking is enabled.
if ($glossary->usedynalink) {
$entry->{$name} = clean_param($option['value'], PARAM_BOOL);
}
break;
default:
throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
}
}
$entry = glossary_edit_entry($entry, $course, $cm, $glossary, $context);
return array(
'entryid' => $entry->id,
'warnings' => $warnings
);
}
/**
* Returns the description of the external function return value.
*
* @return external_description
* @since Moodle 3.2
*/
public static function add_entry_returns() {
return new external_single_structure(array(
'entryid' => new external_value(PARAM_INT, 'New glossary entry ID'),
'warnings' => new external_warnings()
));
}
}

View file

@ -153,4 +153,13 @@ $functions = array(
'services' => array(MOODLE_OFFICIAL_MOBILE_SERVICE)
),
'mod_glossary_add_entry' => array(
'classname' => 'mod_glossary_external',
'methodname' => 'add_entry',
'description' => 'Add a new entry to a given glossary',
'type' => 'write',
'capabilities' => 'mod/glossary:write',
'services' => array(MOODLE_OFFICIAL_MOBILE_SERVICE)
),
);

View file

@ -63,12 +63,7 @@ if ($id) { // if entry is specified
$entry->id = null;
}
$maxfiles = 99; // TODO: add some setting
$maxbytes = $course->maxbytes; // TODO: add some setting
$definitionoptions = array('trusttext'=>true, 'maxfiles'=>$maxfiles, 'maxbytes'=>$maxbytes, 'context'=>$context,
'subdirs'=>file_area_contains_subdirs($context, 'mod_glossary', 'entry', $entry->id));
$attachmentoptions = array('subdirs'=>false, 'maxfiles'=>$maxfiles, 'maxbytes'=>$maxbytes);
list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
$entry = file_prepare_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry', $entry->id);
$entry = file_prepare_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary', 'attachment', $entry->id);
@ -87,116 +82,7 @@ if ($mform->is_cancelled()){
}
} else if ($entry = $mform->get_data()) {
$timenow = time();
$categories = empty($entry->categories) ? array() : $entry->categories;
unset($entry->categories);
$aliases = trim($entry->aliases);
unset($entry->aliases);
if (empty($entry->id)) {
$entry->glossaryid = $glossary->id;
$entry->timecreated = $timenow;
$entry->userid = $USER->id;
$entry->timecreated = $timenow;
$entry->sourceglossaryid = 0;
$entry->teacherentry = has_capability('mod/glossary:manageentries', $context);
$isnewentry = true;
} else {
$isnewentry = false;
}
$entry->concept = trim($entry->concept);
$entry->definition = ''; // updated later
$entry->definitionformat = FORMAT_HTML; // updated later
$entry->definitiontrust = 0; // updated later
$entry->timemodified = $timenow;
$entry->approved = 0;
$entry->usedynalink = isset($entry->usedynalink) ? $entry->usedynalink : 0;
$entry->casesensitive = isset($entry->casesensitive) ? $entry->casesensitive : 0;
$entry->fullmatch = isset($entry->fullmatch) ? $entry->fullmatch : 0;
if ($glossary->defaultapproval or has_capability('mod/glossary:approve', $context)) {
$entry->approved = 1;
}
if ($isnewentry) {
// Add new entry.
$entry->id = $DB->insert_record('glossary_entries', $entry);
} else {
// Update existing entry.
$DB->update_record('glossary_entries', $entry);
}
// save and relink embedded images and save attachments
$entry = file_postupdate_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry', $entry->id);
$entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary', 'attachment', $entry->id);
// store the updated value values
$DB->update_record('glossary_entries', $entry);
//refetch complete entry
$entry = $DB->get_record('glossary_entries', array('id'=>$entry->id));
// update entry categories
$DB->delete_records('glossary_entries_categories', array('entryid'=>$entry->id));
// TODO: this deletes cats from both both main and secondary glossary :-(
if (!empty($categories) and array_search(0, $categories) === false) {
foreach ($categories as $catid) {
$newcategory = new stdClass();
$newcategory->entryid = $entry->id;
$newcategory->categoryid = $catid;
$DB->insert_record('glossary_entries_categories', $newcategory, false);
}
}
// update aliases
$DB->delete_records('glossary_alias', array('entryid'=>$entry->id));
if ($aliases !== '') {
$aliases = explode("\n", $aliases);
foreach ($aliases as $alias) {
$alias = trim($alias);
if ($alias !== '') {
$newalias = new stdClass();
$newalias->entryid = $entry->id;
$newalias->alias = $alias;
$DB->insert_record('glossary_alias', $newalias, false);
}
}
}
// Trigger event and update completion (if entry was created).
$eventparams = array(
'context' => $context,
'objectid' => $entry->id,
'other' => array('concept' => $entry->concept)
);
if ($isnewentry) {
$event = \mod_glossary\event\entry_created::create($eventparams);
} else {
$event = \mod_glossary\event\entry_updated::create($eventparams);
}
$event->add_record_snapshot('glossary_entries', $entry);
$event->trigger();
if ($isnewentry) {
// Update completion state
$completion = new completion_info($course);
if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $glossary->completionentries && $entry->approved) {
$completion->update_state($cm, COMPLETION_COMPLETE);
}
}
// Reset caches.
if ($isnewentry) {
if ($entry->usedynalink and $entry->approved) {
\mod_glossary\local\concept_cache::reset_glossary($glossary);
}
} else {
// So many things may affect the linking, let's just purge the cache always on edit.
\mod_glossary\local\concept_cache::reset_glossary($glossary);
}
$entry = glossary_edit_entry($entry, $course, $cm, $glossary, $context);
redirect("view.php?id=$cm->id&mode=entry&hook=$entry->id");
}

View file

@ -126,10 +126,7 @@ class mod_glossary_entry_form extends moodleform {
} else {
if (!$glossary->allowduplicatedentries) {
if ($DB->record_exists_select('glossary_entries',
'glossaryid = :glossaryid AND LOWER(concept) = :concept', array(
'glossaryid' => $glossary->id,
'concept' => core_text::strtolower($data['concept'])))) {
if (glossary_concept_exists($glossary, $data['concept'])) {
$errors['concept'] = get_string('errconceptalreadyexists', 'glossary');
}
}

View file

@ -3929,3 +3929,174 @@ function glossary_can_view_entry($entry, $cminfo) {
return true;
}
/**
* Check if a concept exists in a glossary.
*
* @param stdClass $glossary glossary object
* @param string $concept the concept to check
* @return bool true if exists
* @since Moodle 3.2
*/
function glossary_concept_exists($glossary, $concept) {
global $DB;
return $DB->record_exists_select('glossary_entries', 'glossaryid = :glossaryid AND LOWER(concept) = :concept',
array(
'glossaryid' => $glossary->id,
'concept' => core_text::strtolower($concept)
)
);
}
/**
* Return the editor and attachment options when editing a glossary entry
*
* @param stdClass $course course object
* @param stdClass $context context object
* @param stdClass $entry entry object
* @return array array containing the editor and attachment options
* @since Moodle 3.2
*/
function glossary_get_editor_and_attachment_options($course, $context, $entry) {
$maxfiles = 99; // TODO: add some setting.
$maxbytes = $course->maxbytes; // TODO: add some setting.
$definitionoptions = array('trusttext' => true, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes, 'context' => $context,
'subdirs' => file_area_contains_subdirs($context, 'mod_glossary', 'entry', $entry->id));
$attachmentoptions = array('subdirs' => false, 'maxfiles' => $maxfiles, 'maxbytes' => $maxbytes);
return array($definitionoptions, $attachmentoptions);
}
/**
* Creates or updates a glossary entry
*
* @param stdClass $entry entry data
* @param stdClass $course course object
* @param stdClass $cm course module object
* @param stdClass $glossary glossary object
* @param stdClass $context context object
* @return stdClass the complete new or updated entry
* @since Moodle 3.2
*/
function glossary_edit_entry($entry, $course, $cm, $glossary, $context) {
global $DB, $USER;
list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
$timenow = time();
$categories = empty($entry->categories) ? array() : $entry->categories;
unset($entry->categories);
$aliases = trim($entry->aliases);
unset($entry->aliases);
if (empty($entry->id)) {
$entry->glossaryid = $glossary->id;
$entry->timecreated = $timenow;
$entry->userid = $USER->id;
$entry->timecreated = $timenow;
$entry->sourceglossaryid = 0;
$entry->teacherentry = has_capability('mod/glossary:manageentries', $context);
$isnewentry = true;
} else {
$isnewentry = false;
}
$entry->concept = trim($entry->concept);
$entry->definition = ''; // Updated later.
$entry->definitionformat = FORMAT_HTML; // Updated later.
$entry->definitiontrust = 0; // Updated later.
$entry->timemodified = $timenow;
$entry->approved = 0;
$entry->usedynalink = isset($entry->usedynalink) ? $entry->usedynalink : 0;
$entry->casesensitive = isset($entry->casesensitive) ? $entry->casesensitive : 0;
$entry->fullmatch = isset($entry->fullmatch) ? $entry->fullmatch : 0;
if ($glossary->defaultapproval or has_capability('mod/glossary:approve', $context)) {
$entry->approved = 1;
}
if ($isnewentry) {
// Add new entry.
$entry->id = $DB->insert_record('glossary_entries', $entry);
} else {
// Update existing entry.
$DB->update_record('glossary_entries', $entry);
}
// Save and relink embedded images and save attachments.
if (!empty($entry->definition_editor)) {
$entry = file_postupdate_standard_editor($entry, 'definition', $definitionoptions, $context, 'mod_glossary', 'entry',
$entry->id);
}
if (!empty($entry->attachment_filemanager)) {
$entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $context, 'mod_glossary',
'attachment', $entry->id);
}
// Store the updated value values.
$DB->update_record('glossary_entries', $entry);
// Refetch complete entry.
$entry = $DB->get_record('glossary_entries', array('id' => $entry->id));
// Update entry categories.
$DB->delete_records('glossary_entries_categories', array('entryid' => $entry->id));
// TODO: this deletes cats from both both main and secondary glossary :-(.
if (!empty($categories) and array_search(0, $categories) === false) {
foreach ($categories as $catid) {
$newcategory = new stdClass();
$newcategory->entryid = $entry->id;
$newcategory->categoryid = $catid;
$DB->insert_record('glossary_entries_categories', $newcategory, false);
}
}
// Update aliases.
$DB->delete_records('glossary_alias', array('entryid' => $entry->id));
if ($aliases !== '') {
$aliases = explode("\n", $aliases);
foreach ($aliases as $alias) {
$alias = trim($alias);
if ($alias !== '') {
$newalias = new stdClass();
$newalias->entryid = $entry->id;
$newalias->alias = $alias;
$DB->insert_record('glossary_alias', $newalias, false);
}
}
}
// Trigger event and update completion (if entry was created).
$eventparams = array(
'context' => $context,
'objectid' => $entry->id,
'other' => array('concept' => $entry->concept)
);
if ($isnewentry) {
$event = \mod_glossary\event\entry_created::create($eventparams);
} else {
$event = \mod_glossary\event\entry_updated::create($eventparams);
}
$event->add_record_snapshot('glossary_entries', $entry);
$event->trigger();
if ($isnewentry) {
// Update completion state.
$completion = new completion_info($course);
if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $glossary->completionentries && $entry->approved) {
$completion->update_state($cm, COMPLETION_COMPLETE);
}
}
// Reset caches.
if ($isnewentry) {
if ($entry->usedynalink and $entry->approved) {
\mod_glossary\local\concept_cache::reset_glossary($glossary);
}
} else {
// So many things may affect the linking, let's just purge the cache always on edit.
\mod_glossary\local\concept_cache::reset_glossary($glossary);
}
return $entry;
}

View file

@ -62,6 +62,8 @@ class mod_glossary_external_testcase extends externallib_advanced_testcase {
$this->assertCount(2, $glossaries['glossaries']);
$this->assertEquals('First Glossary', $glossaries['glossaries'][0]['name']);
$this->assertEquals('Second Glossary', $glossaries['glossaries'][1]['name']);
$this->assertEquals(1, $glossaries['glossaries'][0]['canaddentry']);
$this->assertEquals(1, $glossaries['glossaries'][1]['canaddentry']);
// Check results with specific course IDs.
$glossaries = mod_glossary_external::get_glossaries_by_courses(array($c1->id, $c2->id));
@ -74,6 +76,7 @@ class mod_glossary_external_testcase extends externallib_advanced_testcase {
$this->assertEquals('course', $glossaries['warnings'][0]['item']);
$this->assertEquals($c2->id, $glossaries['warnings'][0]['itemid']);
$this->assertEquals('1', $glossaries['warnings'][0]['warningcode']);
$this->assertEquals(1, $glossaries['glossaries'][0]['canaddentry']);
// Now as admin.
$this->setAdminUser();
@ -83,6 +86,7 @@ class mod_glossary_external_testcase extends externallib_advanced_testcase {
$this->assertCount(1, $glossaries['glossaries']);
$this->assertEquals('Third Glossary', $glossaries['glossaries'][0]['name']);
$this->assertEquals(1, $glossaries['glossaries'][0]['canaddentry']);
}
public function test_view_glossary() {
@ -1094,4 +1098,142 @@ class mod_glossary_external_testcase extends externallib_advanced_testcase {
$this->assertEquals($e3->id, $return['entry']['id']);
}
public function test_add_entry_without_optional_settings() {
global $CFG, $DB;
$this->resetAfterTest(true);
$course = $this->getDataGenerator()->create_course();
$glossary = $this->getDataGenerator()->create_module('glossary', array('course' => $course->id));
$this->setAdminUser();
$concept = 'A concept';
$definition = 'A definition';
$return = mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML);
$return = external_api::clean_returnvalue(mod_glossary_external::add_entry_returns(), $return);
// Get entry from DB.
$entry = $DB->get_record('glossary_entries', array('id' => $return['entryid']));
$this->assertEquals($concept, $entry->concept);
$this->assertEquals($definition, $entry->definition);
$this->assertEquals($CFG->glossary_linkentries, $entry->usedynalink);
$this->assertEquals($CFG->glossary_casesensitive, $entry->casesensitive);
$this->assertEquals($CFG->glossary_fullmatch, $entry->fullmatch);
$this->assertEmpty($DB->get_records('glossary_alias', array('entryid' => $return['entryid'])));
$this->assertEmpty($DB->get_records('glossary_entries_categories', array('entryid' => $return['entryid'])));
}
public function test_add_entry_with_aliases() {
global $DB;
$this->resetAfterTest(true);
$course = $this->getDataGenerator()->create_course();
$glossary = $this->getDataGenerator()->create_module('glossary', array('course' => $course->id));
$this->setAdminUser();
$concept = 'A concept';
$definition = 'A definition';
$paramaliases = 'abc, def, gez';
$options = array(
array(
'name' => 'aliases',
'value' => $paramaliases,
)
);
$return = mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML, $options);
$return = external_api::clean_returnvalue(mod_glossary_external::add_entry_returns(), $return);
$aliases = $DB->get_records('glossary_alias', array('entryid' => $return['entryid']));
$this->assertCount(3, $aliases);
foreach ($aliases as $alias) {
$this->assertContains($alias->alias, $paramaliases);
}
}
public function test_add_entry_in_categories() {
global $DB;
$this->resetAfterTest(true);
$course = $this->getDataGenerator()->create_course();
$glossary = $this->getDataGenerator()->create_module('glossary', array('course' => $course->id));
$gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
$cat1 = $gg->create_category($glossary);
$cat2 = $gg->create_category($glossary);
$this->setAdminUser();
$concept = 'A concept';
$definition = 'A definition';
$paramcategories = "$cat1->id, $cat2->id";
$options = array(
array(
'name' => 'categories',
'value' => $paramcategories,
)
);
$return = mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML, $options);
$return = external_api::clean_returnvalue(mod_glossary_external::add_entry_returns(), $return);
$categories = $DB->get_records('glossary_entries_categories', array('entryid' => $return['entryid']));
$this->assertCount(2, $categories);
foreach ($categories as $category) {
$this->assertContains($category->categoryid, $paramcategories);
}
}
public function test_add_entry_with_attachments() {
global $DB, $USER;
$this->resetAfterTest(true);
$course = $this->getDataGenerator()->create_course();
$glossary = $this->getDataGenerator()->create_module('glossary', array('course' => $course->id));
$context = context_module::instance($glossary->cmid);
$this->setAdminUser();
$concept = 'A concept';
$definition = 'A definition';
// Draft files.
$draftidinlineattach = file_get_unused_draft_itemid();
$draftidattach = file_get_unused_draft_itemid();
$usercontext = context_user::instance($USER->id);
$filerecordinline = array(
'contextid' => $usercontext->id,
'component' => 'user',
'filearea' => 'draft',
'itemid' => $draftidinlineattach,
'filepath' => '/',
'filename' => 'shouldbeanimage.txt',
);
$fs = get_file_storage();
// Create a file in a draft area for regular attachments.
$filerecordattach = $filerecordinline;
$attachfilename = 'attachment.txt';
$filerecordattach['filename'] = $attachfilename;
$filerecordattach['itemid'] = $draftidattach;
$fs->create_file_from_string($filerecordinline, 'image contents (not really)');
$fs->create_file_from_string($filerecordattach, 'simple text attachment');
$options = array(
array(
'name' => 'inlineattachmentsid',
'value' => $draftidinlineattach,
),
array(
'name' => 'attachmentsid',
'value' => $draftidattach,
)
);
$return = mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML, $options);
$return = external_api::clean_returnvalue(mod_glossary_external::add_entry_returns(), $return);
$editorfiles = external_util::get_area_files($context->id, 'mod_glossary', 'entry', $return['entryid']);
$attachmentfiles = external_util::get_area_files($context->id, 'mod_glossary', 'attachment', $return['entryid']);
$this->assertCount(1, $editorfiles);
$this->assertCount(1, $attachmentfiles);
$this->assertEquals('shouldbeanimage.txt', $editorfiles[0]['filename']);
$this->assertEquals('attachment.txt', $attachmentfiles[0]['filename']);
}
}

View file

@ -24,7 +24,7 @@
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2016052300; // The current module version (Date: YYYYMMDDXX)
$plugin->version = 2016052301; // The current module version (Date: YYYYMMDDXX)
$plugin->requires = 2016051900; // Requires this Moodle version
$plugin->component = 'mod_glossary'; // Full name of the plugin (used for diagnostics)
$plugin->cron = 0;