--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Upload a zip of custom lang php files.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_customlang\form;
+
+use tool_customlang\local\importer;
+
+/**
+ * Upload a zip/php of custom lang php files.
+ *
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class import extends \moodleform {
+
+ /**
+ * Form definition.
+ */
+ public function definition() {
+ $mform = $this->_form;
+ $mform->addElement('header', 'settingsheader', get_string('import', 'tool_customlang'));
+
+ $mform->addElement('hidden', 'lng');
+ $mform->setType('lng', PARAM_LANG);
+ $mform->setDefault('lng', $this->_customdata['lng']);
+
+ $filemanageroptions = array(
+ 'accepted_types' => array('.php', '.zip'),
+ 'maxbytes' => 0,
+ 'maxfiles' => 1,
+ 'subdirs' => 0
+ );
+
+ $mform->addElement('filepicker', 'pack', get_string('langpack', 'tool_customlang'),
+ null, $filemanageroptions);
+ $mform->addRule('pack', null, 'required');
+
+ $modes = [
+ importer::IMPORTALL => get_string('import_all', 'tool_customlang'),
+ importer::IMPORTUPDATE => get_string('import_update', 'tool_customlang'),
+ importer::IMPORTNEW => get_string('import_new', 'tool_customlang'),
+ ];
+ $mform->addElement('select', 'importmode', get_string('import_mode', 'tool_customlang'), $modes);
+
+ $mform->addElement('submit', 'importcustomstrings', get_string('importfile', 'tool_customlang'));
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Custom lang importer.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_customlang\local;
+
+use tool_customlang\local\mlang\phpparser;
+use tool_customlang\local\mlang\logstatus;
+use tool_customlang\local\mlang\langstring;
+use core\output\notification;
+use stored_file;
+use coding_exception;
+use moodle_exception;
+use core_component;
+use stdClass;
+
+/**
+ * Class containing tha custom lang importer
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class importer {
+
+ /** @var int imports will only create new customizations */
+ public const IMPORTNEW = 1;
+ /** @var int imports will only update the current customizations */
+ public const IMPORTUPDATE = 2;
+ /** @var int imports all strings */
+ public const IMPORTALL = 3;
+
+ /**
+ * @var string the language name
+ */
+ protected $lng;
+
+ /**
+ * @var int the importation mode (new, update, all)
+ */
+ protected $importmode;
+
+ /**
+ * @var string request folder path
+ */
+ private $folder;
+
+ /**
+ * @var array import log messages
+ */
+ private $log;
+
+ /**
+ * Constructor for the importer class.
+ *
+ * @param string $lng the current language to import.
+ * @param int $importmode the import method (IMPORTALL, IMPORTNEW, IMPORTUPDATE).
+ */
+ public function __construct(string $lng, int $importmode = self::IMPORTALL) {
+ $this->lng = $lng;
+ $this->importmode = $importmode;
+ $this->log = [];
+ }
+
+ /**
+ * Returns the last parse log.
+ *
+ * @return logstatus[] mlang logstatus with the messages
+ */
+ public function get_log(): array {
+ return $this->log;
+ }
+
+ /**
+ * Import customlang files.
+ *
+ * @param stored_file[] $files array of files to import
+ */
+ public function import(array $files): void {
+ // Create a temporal folder to store the files.
+ $this->folder = make_request_directory(false);
+
+ $langfiles = $this->deploy_files($files);
+
+ $this->process_files($langfiles);
+ }
+
+ /**
+ * Deploy all files into a request folder.
+ *
+ * @param stored_file[] $files array of files to deploy
+ * @return string[] of file paths
+ */
+ private function deploy_files(array $files): array {
+ $result = [];
+ // Desploy all files.
+ foreach ($files as $file) {
+ if ($file->get_mimetype() == 'application/zip') {
+ $result = array_merge($result, $this->unzip_file($file));
+ } else {
+ $path = $this->folder.'/'.$file->get_filename();
+ $file->copy_content_to($path);
+ $result = array_merge($result, [$path]);
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * Unzip a file into the request folder.
+ *
+ * @param stored_file $file the zip file to unzip
+ * @return string[] of zip content paths
+ */
+ private function unzip_file(stored_file $file): array {
+ $fp = get_file_packer('application/zip');
+ $zipcontents = $fp->extract_to_pathname($file, $this->folder);
+ if (!$zipcontents) {
+ throw new moodle_exception("Error Unzipping file", 1);
+ }
+ $result = [];
+ foreach ($zipcontents as $contentname => $success) {
+ if ($success) {
+ $result[] = $this->folder.'/'.$contentname;
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * Import strings from a list of langfiles.
+ *
+ * @param string[] $langfiles an array with file paths
+ */
+ private function process_files(array $langfiles): void {
+ $parser = phpparser::get_instance();
+ foreach ($langfiles as $filepath) {
+ $component = $this->component_from_filepath($filepath);
+ if ($component) {
+ $strings = $parser->parse(file_get_contents($filepath));
+ $this->import_strings($strings, $component);
+ }
+ }
+ }
+
+ /**
+ * Try to get the component from a filepath.
+ *
+ * @param string $filepath the filepath
+ * @return stdCalss|null the DB record of that component
+ */
+ private function component_from_filepath(string $filepath) {
+ global $DB;
+
+ // Get component from filename.
+ $pathparts = pathinfo($filepath);
+ if (empty($pathparts['filename'])) {
+ throw new coding_exception("Cannot get filename from $filepath", 1);
+ }
+ $filename = $pathparts['filename'];
+
+ $normalized = core_component::normalize_component($filename);
+ if (count($normalized) == 1 || empty($normalized[1])) {
+ $componentname = $normalized[0];
+ } else {
+ $componentname = implode('_', $normalized);
+ }
+
+ $result = $DB->get_record('tool_customlang_components', ['name' => $componentname]);
+
+ if (!$result) {
+ $this->log[] = new logstatus('notice_missingcomponent', notification::NOTIFY_ERROR, null, $componentname);
+ return null;
+ }
+ return $result;
+ }
+
+ /**
+ * Import an array of strings into the customlang tables.
+ *
+ * @param langstring[] $strings the langstring to set
+ * @param stdClass $component the target component
+ */
+ private function import_strings(array $strings, stdClass $component): void {
+ global $DB;
+
+ foreach ($strings as $newstring) {
+ // Check current DB entry.
+ $customlang = $DB->get_record('tool_customlang', [
+ 'componentid' => $component->id,
+ 'stringid' => $newstring->id,
+ 'lang' => $this->lng,
+ ]);
+ if (!$customlang) {
+ $customlang = null;
+ }
+
+ if ($this->can_save_string($customlang, $newstring, $component)) {
+ $customlang->local = $newstring->text;
+ $customlang->timecustomized = $newstring->timemodified;
+ $customlang->outdated = 0;
+ $customlang->modified = 1;
+ $DB->update_record('tool_customlang', $customlang);
+ }
+ }
+ }
+
+ /**
+ * Determine if a specific string can be saved based on the current importmode.
+ *
+ * @param stdClass $customlang customlang original record
+ * @param langstring $newstring the new strign to store
+ * @param stdClass $component the component target
+ * @return bool if the string can be stored
+ */
+ private function can_save_string(?stdClass $customlang, langstring $newstring, stdClass $component): bool {
+ $result = false;
+ $message = 'notice_success';
+ if (empty($customlang)) {
+ $message = 'notice_inexitentstring';
+ $this->log[] = new logstatus($message, notification::NOTIFY_ERROR, null, $component->name, $newstring);
+ return $result;
+ }
+
+ switch ($this->importmode) {
+ case self::IMPORTNEW:
+ $result = empty($customlang->local);
+ $warningmessage = 'notice_ignoreupdate';
+ break;
+ case self::IMPORTUPDATE:
+ $result = !empty($customlang->local);
+ $warningmessage = 'notice_ignorenew';
+ break;
+ case self::IMPORTALL:
+ $result = true;
+ break;
+ }
+ if ($result) {
+ $errorlevel = notification::NOTIFY_SUCCESS;
+ } else {
+ $errorlevel = notification::NOTIFY_ERROR;
+ $message = $warningmessage;
+ }
+ $this->log[] = new logstatus($message, $errorlevel, null, $component->name, $newstring);
+
+ return $result;
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Language string based on David Mudrak langstring from local_amos.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_customlang\local\mlang;
+
+use moodle_exception;
+use stdclass;
+
+/**
+ * Class containing a lang string cleaned.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+/**
+ * Represents a single string
+ */
+class langstring {
+
+ /** @var string identifier */
+ public $id = null;
+
+ /** @var string */
+ public $text = '';
+
+ /** @var int the time stamp when this string was saved */
+ public $timemodified = null;
+
+ /** @var bool is deleted */
+ public $deleted = false;
+
+ /** @var stdclass extra information about the string */
+ public $extra = null;
+
+ /**
+ * Class constructor.
+ *
+ * @param string $id string identifier
+ * @param string $text string text
+ * @param int $timemodified
+ * @param int $deleted
+ * @param stdclass $extra
+ */
+ public function __construct(string $id, string $text = '', int $timemodified = null,
+ int $deleted = 0, stdclass $extra = null) {
+
+ if (is_null($timemodified)) {
+ $timemodified = time();
+ }
+ $this->id = $id;
+ $this->text = $text;
+ $this->timemodified = $timemodified;
+ $this->deleted = $deleted;
+ $this->extra = $extra;
+ }
+
+ /**
+ * Given a string text, returns it being formatted properly for storing in AMOS repository.
+ *
+ * Note: This method is taken directly from local_amos as it is highly tested and robust.
+ * The Moodle 1.x part is keep on puspose to make it easier the copy paste from both codes.
+ * This could change in the future when AMOS stop suporting the 1.x langstrings.
+ *
+ * We need to know for what branch the string should be prepared due to internal changes in
+ * format required by get_string()
+ * - for get_string() in Moodle 1.6 - 1.9 use $format == 1
+ * - for get_string() in Moodle 2.0 and higher use $format == 2
+ *
+ * Typical usages of this methods:
+ * $t = langstring::fix_syntax($t); // sanity new translations of 2.x strings
+ * $t = langstring::fix_syntax($t, 1); // sanity legacy 1.x strings
+ * $t = langstring::fix_syntax($t, 2, 1); // convert format of 1.x strings into 2.x
+ *
+ * Backward converting 2.x format into 1.x is not supported
+ *
+ * @param string $text string text to be fixed
+ * @param int $format target get_string() format version
+ * @param int $from which format version does the text come from, defaults to the same as $format
+ * @return string
+ */
+ public static function fix_syntax(string $text, int $format = 2, ?int $from = null): string {
+ if (is_null($from)) {
+ $from = $format;
+ }
+
+ // Common filter.
+ $clean = trim($text);
+ $search = [
+ // Remove \r if it is part of \r\n.
+ '/\r(?=\n)/',
+
+ // Control characters to be replaced with \n
+ // LINE TABULATION, FORM FEED, CARRIAGE RETURN, END OF TRANSMISSION BLOCK,
+ // END OF MEDIUM, SUBSTITUTE, BREAK PERMITTED HERE, NEXT LINE, START OF STRING,
+ // STRING TERMINATOR and Unicode character categorys Zl and Zp.
+ '/[\x{0B}-\r\x{17}\x{19}\x{1A}\x{82}\x{85}\x{98}\x{9C}\p{Zl}\p{Zp}]/u',
+
+ // Control characters to be removed
+ // NULL, ENQUIRY, ACKNOWLEDGE, BELL, SHIFT {OUT,IN}, DATA LINK ESCAPE,
+ // DEVICE CONTROL {ONE,TWO,THREE,FOUR}, NEGATIVE ACKNOWLEDGE, SYNCHRONOUS IDLE, ESCAPE,
+ // DELETE, PADDING CHARACTER, HIGH OCTET PRESET, NO BREAK HERE, INDEX,
+ // {START,END} OF SELECTED AREA, CHARACTER TABULATION {SET,WITH JUSTIFICATION},
+ // LINE TABULATION SET, PARTIAL LINE {FORWARD,BACKWARD}, REVERSE LINE FEED,
+ // SINGLE SHIFT {TWO,THREE}, DEVICE CONTROL STRING, PRIVATE USE {ONE,TWO},
+ // SET TRANSMIT STATE, MESSAGE WAITING, {START,END} OF GUARDED AREA,
+ // {SINGLE {GRAPHIC,} CHARACTER,CONTROL SEQUENCE} INTRODUCER, OPERATING SYSTEM COMMAND,
+ // PRIVACY MESSAGE, APPLICATION PROGRAM COMMAND, ZERO WIDTH {,NO-BREAK} SPACE,
+ // REPLACEMENT CHARACTER.
+ '/[\0\x{05}-\x{07}\x{0E}-\x{16}\x{1B}\x{7F}\x{80}\x{81}\x{83}\x{84}\x{86}-\x{93}\x{95}-\x{97}\x{99}-\x{9B}\x{9D}-\x{9F}\x{200B}\x{FEFF}\x{FFFD}]++/u',
+
+ // Remove trailing whitespace at the end of lines in a multiline string.
+ '/[ \t]+(?=\n)/',
+ ];
+ $replace = [
+ '',
+ "\n",
+ '',
+ '',
+ ];
+ $clean = preg_replace($search, $replace, $clean);
+
+ if (($format === 2) && ($from === 2)) {
+ // Sanity translations of 2.x strings.
+ $clean = preg_replace("/\n{3,}/", "\n\n\n", $clean); // Collapse runs of blank lines.
+
+ } else if (($format === 2) && ($from === 1)) {
+ // Convert 1.x string into 2.x format.
+ $clean = preg_replace("/\n{3,}/", "\n\n\n", $clean); // Collapse runs of blank lines.
+ $clean = preg_replace('/%+/', '%', $clean); // Collapse % characters.
+ $clean = str_replace('\$', '@@@___XXX_ESCAPED_DOLLAR__@@@', $clean); // Remember for later.
+ $clean = str_replace("\\", '', $clean); // Delete all slashes.
+ $clean = preg_replace('/(^|[^{])\$a\b(\->[a-zA-Z0-9_]+)?/', '\\1{$a\\2}', $clean); // Wrap placeholders.
+ $clean = str_replace('@@@___XXX_ESCAPED_DOLLAR__@@@', '$', $clean);
+ $clean = str_replace('$', '$', $clean);
+
+ } else if (($format === 1) && ($from === 1)) {
+ // Sanity legacy 1.x strings.
+ $clean = preg_replace("/\n{3,}/", "\n\n", $clean); // Collapse runs of blank lines.
+ $clean = str_replace('\$', '@@@___XXX_ESCAPED_DOLLAR__@@@', $clean);
+ $clean = str_replace("\\", '', $clean); // Delete all slashes.
+ $clean = str_replace('$', '\$', $clean); // Escape all embedded variables.
+ // Unescape placeholders: only $a and $a->something are allowed. All other $variables are left escaped.
+ $clean = preg_replace('/\\\\\$a\b(\->[a-zA-Z0-9_]+)?/', '$a\\1', $clean); // Unescape placeholders.
+ $clean = str_replace('@@@___XXX_ESCAPED_DOLLAR__@@@', '\$', $clean);
+ $clean = str_replace('"', "\\\"", $clean); // Add slashes for ".
+ $clean = preg_replace('/%+/', '%', $clean); // Collapse % characters.
+ $clean = str_replace('%', '%%', $clean); // Duplicate %.
+
+ } else {
+ throw new moodle_exception('Unknown get_string() format version');
+ }
+ return $clean;
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Language string based on David Mudrak langstring from local_amos.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_customlang\local\mlang;
+
+use moodle_exception;
+use stdclass;
+
+/**
+ * Class containing a lang string cleaned.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+/**
+ * Represents a single string
+ */
+class logstatus {
+
+ /** @var langstring the current string */
+ public $langstring = null;
+
+ /** @var string the component */
+ public $component = null;
+
+ /** @var string the string ID */
+ public $stringid = null;
+
+ /** @var string the original filename */
+ public $filename = null;
+
+ /** @var int the error level */
+ public $errorlevel = null;
+
+ /** @var string the message identifier */
+ private $message;
+
+ /**
+ * Class creator.
+ *
+ * @param string $message the message identifier to display
+ * @param string $errorlevel the notice level
+ * @param string|null $filename the filename of this log
+ * @param string|null $component the component of this log
+ * @param langstring|null $langstring the langstring of this log
+ */
+ public function __construct(string $message, string $errorlevel, ?string $filename = null,
+ ?string $component = null, ?langstring $langstring = null) {
+
+ $this->filename = $filename;
+ $this->component = $component;
+ $this->langstring = $langstring;
+ $this->message = $message;
+ $this->errorlevel = $errorlevel;
+
+ if ($langstring) {
+ $this->stringid = $langstring->id;
+ }
+ }
+
+ /**
+ * Get the log message.
+ *
+ * @return string the log message.
+ */
+ public function get_message(): string {
+ return get_string($this->message, 'tool_customlang', $this);
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Mlang PHP based on David Mudrak phpparser for local_amos.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_customlang\local\mlang;
+
+use coding_exception;
+use moodle_exception;
+
+/**
+ * Parser of Moodle strings defined as associative array.
+ *
+ * Moodle core just includes this file format directly as normal PHP code. However
+ * for security reasons, we must not do this for files uploaded by anonymous users.
+ * This parser reconstructs the associative $string array without actually including
+ * the file.
+ */
+class phpparser {
+
+ /** @var holds the singleton instance of self */
+ private static $instance = null;
+
+ /**
+ * Prevents direct creation of object
+ */
+ private function __construct() {
+ }
+
+ /**
+ * Prevent from cloning the instance
+ */
+ public function __clone() {
+ throw new coding_exception('Cloning os singleton is not allowed');
+ }
+
+ /**
+ * Get the singleton instance fo this class
+ *
+ * @return phpparser singleton instance of phpparser
+ */
+ public static function get_instance(): phpparser {
+ if (is_null(self::$instance)) {
+ self::$instance = new phpparser();
+ }
+ return self::$instance;
+ }
+
+ /**
+ * Parses the given data in Moodle PHP string format
+ *
+ * Note: This method is adapted from local_amos as it is highly tested and robust.
+ * The priority is keeping it similar to the original one to make it easier to mantain.
+ *
+ * @param string $data definition of the associative array
+ * @param int $format the data format on the input, defaults to the one used since 2.0
+ * @return langstring[] array of langstrings of this file
+ */
+ public function parse(string $data, int $format = 2): array {
+ $result = [];
+ $strings = $this->extract_strings($data);
+ foreach ($strings as $id => $text) {
+ $cleaned = clean_param($id, PARAM_STRINGID);
+ if ($cleaned !== $id) {
+ continue;
+ }
+ $text = langstring::fix_syntax($text, 2, $format);
+ $result[] = new langstring($id, $text);
+ }
+ return $result;
+ }
+
+ /**
+ * Low level parsing method
+ *
+ * Note: This method is adapted from local_amos as it is highly tested and robust.
+ * The priority is keeping it similar to the original one to make it easier to mantain.
+ *
+ * @param string $data
+ * @return string[] the data strings
+ */
+ protected function extract_strings(string $data): array {
+
+ $strings = []; // To be returned.
+
+ if (empty($data)) {
+ return $strings;
+ }
+
+ // Tokenize data - we expect valid PHP code.
+ $tokens = token_get_all($data);
+
+ // Get rid of all non-relevant tokens.
+ $rubbish = [T_WHITESPACE, T_INLINE_HTML, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG, T_CLOSE_TAG];
+ foreach ($tokens as $i => $token) {
+ if (is_array($token)) {
+ if (in_array($token[0], $rubbish)) {
+ unset($tokens[$i]);
+ }
+ }
+ }
+
+ $id = null;
+ $text = null;
+ $line = 0;
+ $expect = 'STRING_VAR'; // The first expected token is '$string'.
+
+ // Iterate over tokens and look for valid $string array assignment patterns.
+ foreach ($tokens as $token) {
+ $foundtype = null;
+ $founddata = null;
+ if (is_array($token)) {
+ $foundtype = $token[0];
+ $founddata = $token[1];
+ if (!empty($token[2])) {
+ $line = $token[2];
+ }
+
+ } else {
+ $foundtype = 'char';
+ $founddata = $token;
+ }
+
+ if ($expect == 'STRING_VAR') {
+ if ($foundtype === T_VARIABLE and $founddata === '$string') {
+ $expect = 'LEFT_BRACKET';
+ continue;
+ } else {
+ // Allow other code at the global level.
+ continue;
+ }
+ }
+
+ if ($expect == 'LEFT_BRACKET') {
+ if ($foundtype === 'char' and $founddata === '[') {
+ $expect = 'STRING_ID';
+ continue;
+ } else {
+ throw new moodle_exception('Parsing error. Expected character [ at line '.$line);
+ }
+ }
+
+ if ($expect == 'STRING_ID') {
+ if ($foundtype === T_CONSTANT_ENCAPSED_STRING) {
+ $id = $this->decapsulate($founddata);
+ $expect = 'RIGHT_BRACKET';
+ continue;
+ } else {
+ throw new moodle_exception('Parsing error. Expected T_CONSTANT_ENCAPSED_STRING array key at line '.$line);
+ }
+ }
+
+ if ($expect == 'RIGHT_BRACKET') {
+ if ($foundtype === 'char' and $founddata === ']') {
+ $expect = 'ASSIGNMENT';
+ continue;
+ } else {
+ throw new moodle_exception('Parsing error. Expected character ] at line '.$line);
+ }
+ }
+
+ if ($expect == 'ASSIGNMENT') {
+ if ($foundtype === 'char' and $founddata === '=') {
+ $expect = 'STRING_TEXT';
+ continue;
+ } else {
+ throw new moodle_exception('Parsing error. Expected character = at line '.$line);
+ }
+ }
+
+ if ($expect == 'STRING_TEXT') {
+ if ($foundtype === T_CONSTANT_ENCAPSED_STRING) {
+ $text = $this->decapsulate($founddata);
+ $expect = 'SEMICOLON';
+ continue;
+ } else {
+ throw new moodle_exception(
+ 'Parsing error. Expected T_CONSTANT_ENCAPSED_STRING array item value at line '.$line
+ );
+ }
+ }
+
+ if ($expect == 'SEMICOLON') {
+ if (is_null($id) or is_null($text)) {
+ throw new moodle_exception('Parsing error. NULL string id or value at line '.$line);
+ }
+ if ($foundtype === 'char' and $founddata === ';') {
+ if (!empty($id)) {
+ $strings[$id] = $text;
+ }
+ $id = null;
+ $text = null;
+ $expect = 'STRING_VAR';
+ continue;
+ } else {
+ throw new moodle_exception('Parsing error. Expected character ; at line '.$line);
+ }
+ }
+
+ }
+
+ return $strings;
+ }
+
+ /**
+ * Given one T_CONSTANT_ENCAPSED_STRING, return its value without quotes
+ *
+ * Also processes escaped quotes inside the text.
+ *
+ * Note: This method is taken directly from local_amos as it is highly tested and robust.
+ *
+ * @param string $text value obtained by token_get_all()
+ * @return string value without quotes
+ */
+ protected function decapsulate(string $text): string {
+
+ if (strlen($text) < 2) {
+ throw new moodle_exception('Parsing error. Expected T_CONSTANT_ENCAPSED_STRING in decapsulate()');
+ }
+
+ if (substr($text, 0, 1) == "'" and substr($text, -1) == "'") {
+ // Single quoted string.
+ $text = trim($text, "'");
+ $text = str_replace("\'", "'", $text);
+ $text = str_replace('\\\\', '\\', $text);
+ return $text;
+
+ } else if (substr($text, 0, 1) == '"' and substr($text, -1) == '"') {
+ // Double quoted string.
+ $text = trim($text, '"');
+ $text = str_replace('\"', '"', $text);
+ $text = str_replace('\\\\', '\\', $text);
+ return $text;
+
+ } else {
+ throw new moodle_exception(
+ 'Parsing error. Unexpected quotation in T_CONSTANT_ENCAPSED_STRING in decapsulate(): '.$text
+ );
+ }
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * CLI customlang import tool.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+use tool_customlang\local\importer;
+use core\output\notification;
+
+define('CLI_SCRIPT', true);
+
+require(__DIR__ . '/../../../../config.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/customlang/locallib.php');
+require_once("$CFG->libdir/clilib.php");
+
+$usage =
+"Import lang customization.
+
+It can get a single file or a folder.
+If no lang is provided it will try to infere from the filename
+
+Options:
+--lang The target language (will get from filename if not provided)
+--source=path File or folder of the custom lang files (zip or php files)
+--mode What string should be imported. Options are:
+ - all: all string will be imported (default)
+ - new: only string with no previous customisation
+ - update: only strings already modified
+--checkin Save strings to the language pack
+-h, --help Print out this help
+
+Examples:
+\$ sudo -u www-data /usr/bin/php admin/tool/customlang/cli/import.php --lang=en --source=customlangs.zip
+
+\$ sudo -u www-data /usr/bin/php admin/tool/customlang/cli/import.php --source=/tmp/customlangs --checkin
+
+\$ sudo -u www-data /usr/bin/php admin/tool/customlang/cli/import.php --lang=en --source=/tmp/customlangs
+
+";
+
+list($options, $unrecognized) = cli_get_params(
+ [
+ 'help' => false,
+ 'lang' => false,
+ 'source' => false,
+ 'mode' => 'all',
+ 'checkin' => false,
+ ],
+ ['h' => 'help']
+);
+
+if ($unrecognized) {
+ $unrecognized = implode("\n ", $unrecognized);
+ cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
+}
+
+if ($options['help']) {
+ cli_write($usage);
+ exit(0);
+}
+
+$source = $options['source'] ?? null;
+$lang = $options['lang'] ?? null;
+$modeparam = $options['mode'] ?? 'all';
+$checkin = $options['checkin'] ?? false;
+
+$modes = [
+ 'all' => importer::IMPORTALL,
+ 'update' => importer::IMPORTUPDATE,
+ 'new' => importer::IMPORTNEW,
+];
+if (!isset($modes[$modeparam])) {
+ cli_error(get_string('climissingmode', 'tool_customlang'));
+}
+$mode = $modes[$modeparam];
+
+if (empty($source)) {
+ $source = $CFG->dataroot.'/temp/customlang';
+}
+
+if (!file_exists($source)) {
+ cli_error(get_string('climissingsource', 'tool_customlang'));
+}
+
+// Emulate normal session - we use admin account by default.
+cron_setup_user();
+
+// Get the file list.
+$files = [];
+$langfiles = [];
+
+if (is_file($source)) {
+ $files[] = $source;
+}
+if (is_dir($source)) {
+ $filelist = glob("$source/*");
+ foreach ($filelist as $filename) {
+ $files[] = "$filename";
+ }
+}
+
+$countfiles = 0;
+foreach ($files as $filepath) {
+ // Try to get the lang.
+ $filelang = $lang;
+ // Get component from filename.
+ $pathparts = pathinfo($filepath);
+ $filename = $pathparts['filename'];
+ $extension = $pathparts['extension'];
+ if ($extension == 'zip') {
+ if (!$filelang) {
+ // Try to get the lang from the filename.
+ if (strrpos($filename, 'customlang_') === 0) {
+ $parts = explode('_', $filename);
+ if (!empty($parts[1])) {
+ $filelang = $parts[1];
+ }
+ }
+ }
+ } else if ($extension != 'php') {
+ // Ignore any other file extension.
+ continue;
+ }
+ if (empty($filelang)) {
+ cli_error(get_string('climissinglang', 'tool_customlang'));
+ }
+ if (!isset($langfiles[$filelang])) {
+ $langfiles[$filelang] = [];
+ }
+ $langfiles[$filelang][] = $filepath;
+ $countfiles ++;
+}
+
+if (!$countfiles) {
+ cli_error(get_string('climissingfiles', 'tool_customlang'));
+}
+
+foreach ($langfiles as $lng => $files) {
+ $importer = new importer($lng, $mode);
+ $storedfiles = [];
+ $fs = get_file_storage();
+
+ cli_heading(get_string('clifiles', 'tool_customlang', $lng));
+
+ foreach ($files as $file) {
+ // Generate a valid stored_file from this file.
+ $record = (object)[
+ 'filearea' => 'draft',
+ 'component' => 'user',
+ 'filepath' => '/',
+ 'itemid' => file_get_unused_draft_itemid(),
+ 'license' => $CFG->sitedefaultlicense,
+ 'author' => '',
+ 'filename' => clean_param(basename($file), PARAM_FILE),
+ 'contextid' => \context_user::instance($USER->id)->id,
+ 'userid' => $USER->id,
+ ];
+ cli_writeln($file);
+ $storedfiles[] = $fs->create_file_from_pathname($record, $file);
+ }
+ cli_writeln("");
+
+ // Import files.
+ cli_heading(get_string('cliimporting', 'tool_customlang', $modeparam));
+ $importer->import($storedfiles);
+ // Display logs.
+ $log = $importer->get_log();
+ if (empty($log)) {
+ cli_problem(get_string('clinolog', 'tool_customlang', $lng));
+ }
+ foreach ($log as $message) {
+ if ($message->errorlevel == notification::NOTIFY_ERROR) {
+ cli_problem($message->get_message());
+ } else {
+ cli_writeln($message->get_message());
+ }
+ }
+ // Do the checkin if necessary.
+ if ($checkin) {
+ tool_customlang_utils::checkin($lng);
+ cli_writeln(get_string('savecheckin', 'tool_customlang'));
+ }
+ cli_writeln("");
+}
+
+exit(0);
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Import custom lang files.
+ *
+ * @package tool_customlang
+ * @subpackage customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+use tool_customlang\form\import;
+use tool_customlang\local\importer;
+
+require(__DIR__ . '/../../../config.php');
+require_once($CFG->dirroot.'/'.$CFG->admin.'/tool/customlang/locallib.php');
+require_once($CFG->libdir.'/adminlib.php');
+
+require_login(SITEID, false);
+require_capability('tool/customlang:edit', context_system::instance());
+
+$lng = required_param('lng', PARAM_LANG);
+
+admin_externalpage_setup('toolcustomlang', '', null,
+ new moodle_url('/admin/tool/customlang/import.php', ['lng' => $lng]));
+
+$output = $PAGE->get_renderer('tool_customlang');
+
+$form = new import(null, ['lng' => $lng]);
+if ($data = $form->get_data()) {
+ require_sesskey();
+
+ // Get the file from the users draft area.
+ $usercontext = context_user::instance($USER->id);
+ $fs = get_file_storage();
+ $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $data->pack, 'id',
+ false);
+
+ // Send files to the importer.
+ $importer = new importer($data->lng, $data->importmode);
+ $importer->import($files);
+
+ echo $output->header();
+
+ // Display logs.
+ $log = $importer->get_log();
+ foreach ($log as $message) {
+ echo $output->notification($message->get_message(), $message->errorlevel);
+ }
+
+ // Show continue button.
+ echo $output->continue_button(new moodle_url('index.php', array('lng' => $lng)));
+
+} else {
+ echo $output->header();
+
+ $form->display();
+}
+
+echo $OUTPUT->footer();
'method' => 'post',
);
}
+ $menu['import'] = array(
+ 'title' => get_string('import', 'tool_customlang'),
+ 'url' => new moodle_url($PAGE->url, ['action' => 'checkout', 'lng' => $lng, 'next' => 'import']),
+ 'method' => 'post',
+ );
}
if (has_capability('tool/customlang:export', context_system::instance())) {
$langdir = tool_customlang_utils::get_localpack_location($lng);
$string['cliexportstartexport'] = 'Exporting language "{$a}"';
$string['cliexportzipdone'] = 'Zip created: {$a}';
$string['cliexportzipfail'] = 'Cannot create zip {$a}';
+$string['clifiles'] = 'Files to import into {$a}';
+$string['cliimporting'] = 'Import files string (mode {$a})';
+$string['clinolog'] = 'Nothing to import into {$a}';
+$string['climissinglang'] = 'Missing language';
+$string['climissingfiles'] = 'Missing valid files';
+$string['climissingmode'] = 'Missing or invalid mode (valid is all, new or update)';
+$string['climissingsource'] = 'Missing file or folder';
$string['confirmcheckin'] = 'You are about to save modifications to your local language pack. This will export the customised strings from the translator into your site data directory and your site will start using the modified strings. Press \'Continue\' to proceed with saving.';
$string['customlang:edit'] = 'Edit local translation';
$string['customlang:export'] = 'Export local translation';
$string['headinglocal'] = 'Local customisation';
$string['headingstandard'] = 'Standard text';
$string['headingstringid'] = 'String';
+$string['import'] = 'Import custom strings';
+$string['import_mode'] = 'Import mode';
+$string['import_new'] = 'Create only strings without local customisation';
+$string['import_update'] = 'Update only strings with local customisation';
+$string['import_all'] = 'Create or update all strings from the component(s)';
+$string['importfile'] = 'Import file';
+$string['langpack'] = 'Language component(s)';
$string['markinguptodate'] = 'Marking the customisation as up-to-date';
$string['markinguptodate_help'] = 'The customised translation may get outdated if either the English original or the master translation has modified since the string was customised on your site. Review the customised translation. If you find it up-to-date, click the checkbox. Edit it otherwise.';
$string['markuptodate'] = 'mark as up-to-date';
$string['modifiedno'] = 'There are no modified strings to save.';
$string['modifiednum'] = 'There are {$a} modified strings. Do you wish to save these changes to your local language pack?';
$string['nolocallang'] = 'No local strings found.';
+$string['notice_ignorenew'] = 'Ignoring string {$a->component}/{$a->stringid} because it is not customised.';
+$string['notice_ignoreupdate'] = 'Ignoring string {$a->component}/{$a->stringid} because it is already defined.';
+$string['notice_inexitentstring'] = 'String {$a->component}/{$a->stringid} not found.';
+$string['notice_missingcomponent'] = 'Missing component {$a->component}.';
+$string['notice_success'] = 'String {$a->component}/{$a->stringid} updated successfully.';
$string['nostringsfound'] = 'No strings found, please modify the filter settings';
$string['placeholder'] = 'Placeholders';
$string['placeholder_help'] = 'Placeholders are special statements like `{$a}` or `{$a->something}` within the string. They are replaced with a value when the string is actually printed.
--- /dev/null
+@tool @tool_customlang @_file_upload
+Feature: Within a moodle instance, an administrator should be able to import modified langstrings.
+ In order to import modified langstrings in the adminsettings from one to another instance,
+ As an admin
+ I need to be able to import the zips and php files of the language customisation of a language.
+
+ Background:
+ Given I log in as "admin"
+ And I navigate to "Language > Language customisation" in site administration
+ And I set the field "lng" to "en"
+ And I click on "Import custom strings" "button"
+ And I press "Continue"
+
+ @javascript
+ Scenario: Import a PHP file to add a new core lang customization
+ When I upload "admin/tool/customlang/tests/fixtures/tool_customlang.php" file to "Language component(s)" filemanager
+ And I press "Import file"
+ Then I should see "String tool_customlang/pluginname updated successfully."
+ And I should see "String tool_customlang/nonexistentinvetedstring not found."
+ And I click on "Continue" "button"
+ And I should see "There are 1 modified strings."
+ And I click on "Save strings to language pack" "button"
+ And I click on "Continue" "button"
+ And I should see "An amazing import feature" in the "page-header" "region"
+
+ @javascript
+ Scenario: Try to import a PHP file from a non existent component
+ When I upload "admin/tool/customlang/tests/fixtures/mod_fakecomponent.php" file to "Language component(s)" filemanager
+ And I press "Import file"
+ Then I should see "Missing component mod_fakecomponent."
+
+ @javascript
+ Scenario: Import a zip file with some PHP files in it.
+ When I upload "admin/tool/customlang/tests/fixtures/customlang.zip" file to "Language component(s)" filemanager
+ And I press "Import file"
+ Then I should see "String core/administrationsite updated successfully."
+ And I should see "String core/language updated successfully."
+ And I should see "String core/nonexistentinvetedstring not found."
+ And I should see "String tool_customlang/pluginname updated successfully."
+ And I should see "String tool_customlang/nonexistentinvetedstring not found."
+ And I should see "Missing component mod_fakecomponent."
+ And I click on "Continue" "button"
+ And I should see "There are 3 modified strings."
+ And I click on "Save strings to language pack" "button"
+ And I click on "Continue" "button"
+ And I should see "Uploaded custom string" in the "page-header" "region"
+ And I should see "Another Uploaded string" in the "page-header" "region"
+ And I should see "An amazing import feature" in the "page-header" "region"
--- /dev/null
+@tool @tool_customlang @_file_upload
+Feature: Within a moodle instance, an administrator should be able to import langstrings with several modes.
+ In order to import modified langstrings in the adminsettings from one to another instance,
+ As an admin
+ I need to be able to import only some language customisation strings depending on some conditions.
+
+ Background:
+ # Add one customization.
+ Given I log in as "admin"
+ And I navigate to "Language > Language customisation" in site administration
+ And I set the field "lng" to "en"
+ And I press "Open language pack for editing"
+ And I press "Continue"
+ And I set the field "Show strings of these components" to "moodle.php"
+ And I set the field "String identifier" to "administrationsite"
+ And I press "Show strings"
+ And I set the field "core/administrationsite" to "Custom string example"
+ And I press "Save changes to the language pack"
+ And I should see "There are 1 modified strings."
+ And I click on "Continue" "button"
+ And I should see "Custom string example" in the "page-header" "region"
+
+ @javascript
+ Scenario: Update only customized strings
+ When I set the field "lng" to "en"
+ And I click on "Import custom strings" "button"
+ And I press "Continue"
+ And I upload "admin/tool/customlang/tests/fixtures/moodle.php" file to "Language component(s)" filemanager
+ And I set the field "Import mode" to "Update only strings with local customisation"
+ And I press "Import file"
+ Then I should see "String core/administrationsite updated successfully."
+ And I should see "Ignoring string core/language because it is not customised."
+ And I should see "String core/nonexistentinvetedstring not found."
+ And I click on "Continue" "button"
+ And I should see "There are 1 modified strings."
+ And I should not see "Uploaded custom string" in the "page-header" "region"
+ And I click on "Save strings to language pack" "button"
+ And I click on "Continue" "button"
+ And I should not see "Custom string example" in the "page-header" "region"
+ And I should see "Uploaded custom string" in the "page-header" "region"
+ And I should not see "Another Uploaded string" in the "page-header" "region"
+
+ @javascript
+ Scenario: Create only new strings
+ When I set the field "lng" to "en"
+ And I click on "Import custom strings" "button"
+ And I press "Continue"
+ And I upload "admin/tool/customlang/tests/fixtures/moodle.php" file to "Language component(s)" filemanager
+ And I set the field "Import mode" to "Create only strings without local customisation"
+ And I press "Import file"
+ Then I should see "Ignoring string core/administrationsite because it is already defined."
+ And I should see "String core/language updated successfully."
+ And I should see "String core/nonexistentinvetedstring not found."
+ And I click on "Continue" "button"
+ And I should see "There are 1 modified strings."
+ And I should not see "Uploaded custom string" in the "page-header" "region"
+ And I click on "Save strings to language pack" "button"
+ And I click on "Continue" "button"
+ And I should see "Custom string example" in the "page-header" "region"
+ And I should not see "Uploaded custom string" in the "page-header" "region"
+ And I should see "Another Uploaded string" in the "page-header" "region"
+
+ @javascript
+ Scenario: Import all strings
+ When I set the field "lng" to "en"
+ And I click on "Import custom strings" "button"
+ And I press "Continue"
+ And I upload "admin/tool/customlang/tests/fixtures/moodle.php" file to "Language component(s)" filemanager
+ And I set the field "Import mode" to "Create or update all strings from the component(s)"
+ And I press "Import file"
+ Then I should see "String core/administrationsite updated successfully."
+ And I should see "String core/language updated successfully."
+ And I should see "String core/nonexistentinvetedstring not found."
+ And I click on "Continue" "button"
+ And I should see "There are 2 modified strings."
+ And I should not see "Uploaded custom string" in the "page-header" "region"
+ And I click on "Save strings to language pack" "button"
+ And I click on "Continue" "button"
+ And I should not see "Custom string example" in the "page-header" "region"
+ And I should see "Uploaded custom string" in the "page-header" "region"
+ And I should see "Another Uploaded string" in the "page-header" "region"
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Local language pack.
+ *
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+
+$string['administrationsite'] = 'Uploaded custom string';
+$string['language'] = 'Another Uploaded string';
+$string['nonexistentinvetedstring'] = 'This should not be imported';
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Local language pack.
+ *
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+$string['administrationsite'] = 'Uploaded custom string';
+$string['language'] = 'Another Uploaded string';
+$string['nonexistentinvetedstring'] = 'This should not be imported';
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Local language pack from http://localhost/m/MDL-69583
+ *
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+
+$string['pluginname'] = 'An amazing import feature';
+$string['nonexistentinvetedstring'] = 'This string should not be imported';
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * mlang langstring tests.
+ *
+ * Based on local_amos mlang_langstring tests.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_customlang\local\mlang;
+
+use advanced_testcase;
+use moodle_exception;
+
+/**
+ * Langstring tests.
+ *
+ * @package tool_customlang
+ * @copyright 2020 Ferran Recio <ferran@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class langstring_testcase extends advanced_testcase {
+
+ /**
+ * Sanity 1.x string
+ * - all variables but $a placeholders must be escaped because the string is eval'ed
+ * - all ' and " must be escaped
+ * - all single % must be converted into %% for backwards compatibility
+ *
+ * @dataProvider fix_syntax_data
+ * @param string $text the text to test
+ * @param int $version the lang package version (1 or 2)
+ * @param int|null $fromversion the version to convert (null for none)
+ * @param string $expected the expected result
+ *
+ */
+ public function test_fix_syntax(string $text, int $version, ?int $fromversion, string $expected): void {
+ $this->assertEquals(langstring::fix_syntax($text, $version, $fromversion), $expected);
+ }
+
+ /**
+ * Data provider for the test_parse.
+ *
+ * @return array
+ */
+ public function fix_syntax_data() : array {
+ return [
+ // Syntax sanity v1 strings.
+ [
+ 'No change', 1, null,
+ 'No change'
+ ],
+ [
+ 'Completed 100% of work', 1, null,
+ 'Completed 100%% of work'
+ ],
+ [
+ 'Completed 100%% of work', 1, null,
+ 'Completed 100%% of work'
+ ],
+ [
+ "Windows\r\nsucks", 1, null,
+ "Windows\nsucks"
+ ],
+ [
+ "Linux\nsucks", 1, null,
+ "Linux\nsucks"
+ ],
+ [
+ "Mac\rsucks", 1, null,
+ "Mac\nsucks"
+ ],
+ [
+ "LINE TABULATION\x0Bnewline", 1, null,
+ "LINE TABULATION\nnewline"
+ ],
+ [
+ "FORM FEED\x0Cnewline", 1, null,
+ "FORM FEED\nnewline"
+ ],
+ [
+ "END OF TRANSMISSION BLOCK\x17newline", 1, null,
+ "END OF TRANSMISSION BLOCK\nnewline"
+ ],
+ [
+ "END OF MEDIUM\x19newline", 1, null,
+ "END OF MEDIUM\nnewline"
+ ],
+ [
+ "SUBSTITUTE\x1Anewline", 1, null,
+ "SUBSTITUTE\nnewline"
+ ],
+ [
+ "BREAK PERMITTED HERE\xC2\x82newline", 1, null,
+ "BREAK PERMITTED HERE\nnewline"
+ ],
+ [
+ "NEXT LINE\xC2\x85newline", 1, null,
+ "NEXT LINE\nnewline"
+ ],
+ [
+ "START OF STRING\xC2\x98newline", 1, null,
+ "START OF STRING\nnewline"
+ ],
+ [
+ "STRING TERMINATOR\xC2\x9Cnewline", 1, null,
+ "STRING TERMINATOR\nnewline"
+ ],
+ [
+ "Unicode Zl\xE2\x80\xA8newline", 1, null,
+ "Unicode Zl\nnewline"
+ ],
+ [
+ "Unicode Zp\xE2\x80\xA9newline", 1, null,
+ "Unicode Zp\nnewline"
+ ],
+ [
+ "Empty\n\n\n\n\n\nlines", 1, null,
+ "Empty\n\nlines"
+ ],
+ [
+ "Trailing \n whitespace \t \nat \nmultilines ", 1, null,
+ "Trailing\n whitespace\nat\nmultilines"
+ ],
+ [
+ 'Escape $variable names', 1, null,
+ 'Escape \$variable names'
+ ],
+ [
+ 'Escape $alike names', 1, null,
+ 'Escape \$alike names'
+ ],
+ [
+ 'String $a placeholder', 1, null,
+ 'String $a placeholder'
+ ],
+ [
+ 'Escaped \$a', 1, null,
+ 'Escaped \$a'
+ ],
+ [
+ 'Wrapped {$a}', 1, null,
+ 'Wrapped {$a}'
+ ],
+ [
+ 'Trailing $a', 1, null,
+ 'Trailing $a'
+ ],
+ [
+ '$a leading', 1, null,
+ '$a leading'
+ ],
+ [
+ 'Hit $a-times', 1, null,
+ 'Hit $a-times'
+ ], // This is placeholder.
+ [
+ 'This is $a_book', 1, null,
+ 'This is \$a_book'
+ ], // This is not a place holder.
+ [
+ 'Bye $a, ttyl', 1, null,
+ 'Bye $a, ttyl'
+ ],
+ [
+ 'Object $a->foo placeholder', 1, null,
+ 'Object $a->foo placeholder'
+ ],
+ [
+ 'Trailing $a->bar', 1, null,
+ 'Trailing $a->bar'
+ ],
+ [
+ '<strong>AMOS</strong>', 1, null,
+ '<strong>AMOS</strong>'
+ ],
+ [
+ '<a href="http://localhost">AMOS</a>', 1, null,
+ '<a href=\"http://localhost\">AMOS</a>'
+ ],
+ [
+ '<a href=\"http://localhost\">AMOS</a>', 1, null,
+ '<a href=\"http://localhost\">AMOS</a>'
+ ],
+ [
+ "'Murder!', she wrote", 1, null,
+ "'Murder!', she wrote"
+ ], // Will be escaped by var_export().
+ [
+ "\t Trim Hunter \t\t", 1, null,
+ 'Trim Hunter'
+ ],
+ [
+ 'Delete role "$a->role"?', 1, null,
+ 'Delete role \"$a->role\"?'
+ ],
+ [
+ 'Delete role \"$a->role\"?', 1, null,
+ 'Delete role \"$a->role\"?'
+ ],
+ [
+ "Delete ASCII\0 NULL control character", 1, null,
+ 'Delete ASCII NULL control character'
+ ],
+ [
+ "Delete ASCII\x05 ENQUIRY control character", 1, null,
+ 'Delete ASCII ENQUIRY control character'
+ ],
+ [
+ "Delete ASCII\x06 ACKNOWLEDGE control character", 1, null,
+ 'Delete ASCII ACKNOWLEDGE control character'
+ ],
+ [
+ "Delete ASCII\x07 BELL control character", 1, null,
+ 'Delete ASCII BELL control character'
+ ],
+ [
+ "Delete ASCII\x0E SHIFT OUT control character", 1, null,
+ 'Delete ASCII SHIFT OUT control character'
+ ],
+ [
+ "Delete ASCII\x0F SHIFT IN control character", 1, null,
+ 'Delete ASCII SHIFT IN control character'
+ ],
+ [
+ "Delete ASCII\x10 DATA LINK ESCAPE control character", 1, null,
+ 'Delete ASCII DATA LINK ESCAPE control character'
+ ],
+ [
+ "Delete ASCII\x11 DEVICE CONTROL ONE control character", 1, null,
+ 'Delete ASCII DEVICE CONTROL ONE control character'
+ ],
+ [
+ "Delete ASCII\x12 DEVICE CONTROL TWO control character", 1, null,
+ 'Delete ASCII DEVICE CONTROL TWO control character'
+ ],
+ [
+ "Delete ASCII\x13 DEVICE CONTROL THREE control character", 1, null,
+ 'Delete ASCII DEVICE CONTROL THREE control character'
+ ],
+ [
+ "Delete ASCII\x14 DEVICE CONTROL FOUR control character", 1, null,
+ 'Delete ASCII DEVICE CONTROL FOUR control character'
+ ],
+ [
+ "Delete ASCII\x15 NEGATIVE ACKNOWLEDGE control character", 1, null,
+ 'Delete ASCII NEGATIVE ACKNOWLEDGE control character'
+ ],
+ [
+ "Delete ASCII\x16 SYNCHRONOUS IDLE control character", 1, null,
+ 'Delete ASCII SYNCHRONOUS IDLE control character'
+ ],
+ [
+ "Delete ASCII\x1B ESCAPE control character", 1, null,
+ 'Delete ASCII ESCAPE control character'
+ ],
+ [
+ "Delete ASCII\x7F DELETE control character", 1, null,
+ 'Delete ASCII DELETE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x80 PADDING CHARACTER control character", 1, null,
+ 'Delete ISO 8859 PADDING CHARACTER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x81 HIGH OCTET PRESET control character", 1, null,
+ 'Delete ISO 8859 HIGH OCTET PRESET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x83 NO BREAK HERE control character", 1, null,
+ 'Delete ISO 8859 NO BREAK HERE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x84 INDEX control character", 1, null,
+ 'Delete ISO 8859 INDEX control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x86 START OF SELECTED AREA control character", 1, null,
+ 'Delete ISO 8859 START OF SELECTED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x87 END OF SELECTED AREA control character", 1, null,
+ 'Delete ISO 8859 END OF SELECTED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x88 CHARACTER TABULATION SET control character", 1, null,
+ 'Delete ISO 8859 CHARACTER TABULATION SET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x89 CHARACTER TABULATION WITH JUSTIFICATION control character", 1, null,
+ 'Delete ISO 8859 CHARACTER TABULATION WITH JUSTIFICATION control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8A LINE TABULATION SET control character", 1, null,
+ 'Delete ISO 8859 LINE TABULATION SET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8B PARTIAL LINE FORWARD control character", 1, null,
+ 'Delete ISO 8859 PARTIAL LINE FORWARD control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8C PARTIAL LINE BACKWARD control character", 1, null,
+ 'Delete ISO 8859 PARTIAL LINE BACKWARD control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8D REVERSE LINE FEED control character", 1, null,
+ 'Delete ISO 8859 REVERSE LINE FEED control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8E SINGLE SHIFT TWO control character", 1, null,
+ 'Delete ISO 8859 SINGLE SHIFT TWO control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8F SINGLE SHIFT THREE control character", 1, null,
+ 'Delete ISO 8859 SINGLE SHIFT THREE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x90 DEVICE CONTROL STRING control character", 1, null,
+ 'Delete ISO 8859 DEVICE CONTROL STRING control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x91 PRIVATE USE ONE control character", 1, null,
+ 'Delete ISO 8859 PRIVATE USE ONE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x92 PRIVATE USE TWO control character", 1, null,
+ 'Delete ISO 8859 PRIVATE USE TWO control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x93 SET TRANSMIT STATE control character", 1, null,
+ 'Delete ISO 8859 SET TRANSMIT STATE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x95 MESSAGE WAITING control character", 1, null,
+ 'Delete ISO 8859 MESSAGE WAITING control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x96 START OF GUARDED AREA control character", 1, null,
+ 'Delete ISO 8859 START OF GUARDED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x97 END OF GUARDED AREA control character", 1, null,
+ 'Delete ISO 8859 END OF GUARDED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x99 SINGLE GRAPHIC CHARACTER INTRODUCER control character", 1, null,
+ 'Delete ISO 8859 SINGLE GRAPHIC CHARACTER INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9A SINGLE CHARACTER INTRODUCER control character", 1, null,
+ 'Delete ISO 8859 SINGLE CHARACTER INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9B CONTROL SEQUENCE INTRODUCER control character", 1, null,
+ 'Delete ISO 8859 CONTROL SEQUENCE INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9D OPERATING SYSTEM COMMAND control character", 1, null,
+ 'Delete ISO 8859 OPERATING SYSTEM COMMAND control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9E PRIVACY MESSAGE control character", 1, null,
+ 'Delete ISO 8859 PRIVACY MESSAGE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9F APPLICATION PROGRAM COMMAND control character", 1, null,
+ 'Delete ISO 8859 APPLICATION PROGRAM COMMAND control character'
+ ],
+ [
+ "Delete Unicode\xE2\x80\x8B ZERO WIDTH SPACE control character", 1, null,
+ 'Delete Unicode ZERO WIDTH SPACE control character'
+ ],
+ [
+ "Delete Unicode\xEF\xBB\xBF ZERO WIDTH NO-BREAK SPACE control character", 1, null,
+ 'Delete Unicode ZERO WIDTH NO-BREAK SPACE control character'
+ ],
+ [
+ "Delete Unicode\xEF\xBF\xBD REPLACEMENT CHARACTER control character", 1, null,
+ 'Delete Unicode REPLACEMENT CHARACTER control character'
+ ],
+ // Syntax sanity v2 strings.
+ [
+ 'No change', 2, null,
+ 'No change'
+ ],
+ [
+ 'Completed 100% of work', 2, null,
+ 'Completed 100% of work'
+ ],
+ [
+ '%%%% HEADER %%%%', 2, null,
+ '%%%% HEADER %%%%'
+ ], // Was not possible before.
+ [
+ "Windows\r\nsucks", 2, null,
+ "Windows\nsucks"
+ ],
+ [
+ "Linux\nsucks", 2, null,
+ "Linux\nsucks"
+ ],
+ [
+ "Mac\rsucks", 2, null,
+ "Mac\nsucks"
+ ],
+ [
+ "LINE TABULATION\x0Bnewline", 2, null,
+ "LINE TABULATION\nnewline"
+ ],
+ [
+ "FORM FEED\x0Cnewline", 2, null,
+ "FORM FEED\nnewline"
+ ],
+ [
+ "END OF TRANSMISSION BLOCK\x17newline", 2, null,
+ "END OF TRANSMISSION BLOCK\nnewline"
+ ],
+ [
+ "END OF MEDIUM\x19newline", 2, null,
+ "END OF MEDIUM\nnewline"
+ ],
+ [
+ "SUBSTITUTE\x1Anewline", 2, null,
+ "SUBSTITUTE\nnewline"
+ ],
+ [
+ "BREAK PERMITTED HERE\xC2\x82newline", 2, null,
+ "BREAK PERMITTED HERE\nnewline"
+ ],
+ [
+ "NEXT LINE\xC2\x85newline", 2, null,
+ "NEXT LINE\nnewline"
+ ],
+ [
+ "START OF STRING\xC2\x98newline", 2, null,
+ "START OF STRING\nnewline"
+ ],
+ [
+ "STRING TERMINATOR\xC2\x9Cnewline", 2, null,
+ "STRING TERMINATOR\nnewline"
+ ],
+ [
+ "Unicode Zl\xE2\x80\xA8newline", 2, null,
+ "Unicode Zl\nnewline"
+ ],
+ [
+ "Unicode Zp\xE2\x80\xA9newline", 2, null,
+ "Unicode Zp\nnewline"
+ ],
+ [
+ "Empty\n\n\n\n\n\nlines", 2, null,
+ "Empty\n\n\nlines"
+ ], // Now allows up to two empty lines.
+ [
+ "Trailing \n whitespace\t\nat \nmultilines ", 2, null,
+ "Trailing\n whitespace\nat\nmultilines"
+ ],
+ [
+ 'Do not escape $variable names', 2, null,
+ 'Do not escape $variable names'
+ ],
+ [
+ 'Do not escape $alike names', 2, null,
+ 'Do not escape $alike names'
+ ],
+ [
+ 'Not $a placeholder', 2, null,
+ 'Not $a placeholder'
+ ],
+ [
+ 'String {$a} placeholder', 2, null,
+ 'String {$a} placeholder'
+ ],
+ [
+ 'Trailing {$a}', 2, null,
+ 'Trailing {$a}'
+ ],
+ [
+ '{$a} leading', 2, null,
+ '{$a} leading'
+ ],
+ [
+ 'Trailing $a', 2, null,
+ 'Trailing $a'
+ ],
+ [
+ '$a leading', 2, null,
+ '$a leading'
+ ],
+ [
+ 'Not $a->foo placeholder', 2, null,
+ 'Not $a->foo placeholder'
+ ],
+ [
+ 'Object {$a->foo} placeholder', 2, null,
+ 'Object {$a->foo} placeholder'
+ ],
+ [
+ 'Trailing $a->bar', 2, null,
+ 'Trailing $a->bar'
+ ],
+ [
+ 'Invalid $a-> placeholder', 2, null,
+ 'Invalid $a-> placeholder'
+ ],
+ [
+ '<strong>AMOS</strong>', 2, null,
+ '<strong>AMOS</strong>'
+ ],
+ [
+ "'Murder!', she wrote", 2, null,
+ "'Murder!', she wrote"
+ ], // Will be escaped by var_export().
+ [
+ "\t Trim Hunter \t\t", 2, null,
+ 'Trim Hunter'
+ ],
+ [
+ 'Delete role "$a->role"?', 2, null,
+ 'Delete role "$a->role"?'
+ ],
+ [
+ 'Delete role \"$a->role\"?', 2, null,
+ 'Delete role \"$a->role\"?'
+ ],
+ [
+ "Delete ASCII\0 NULL control character", 2, null,
+ 'Delete ASCII NULL control character'
+ ],
+ [
+ "Delete ASCII\x05 ENQUIRY control character", 2, null,
+ 'Delete ASCII ENQUIRY control character'
+ ],
+ [
+ "Delete ASCII\x06 ACKNOWLEDGE control character", 2, null,
+ 'Delete ASCII ACKNOWLEDGE control character'
+ ],
+ [
+ "Delete ASCII\x07 BELL control character", 2, null,
+ 'Delete ASCII BELL control character'
+ ],
+ [
+ "Delete ASCII\x0E SHIFT OUT control character", 2, null,
+ 'Delete ASCII SHIFT OUT control character'
+ ],
+ [
+ "Delete ASCII\x0F SHIFT IN control character", 2, null,
+ 'Delete ASCII SHIFT IN control character'
+ ],
+ [
+ "Delete ASCII\x10 DATA LINK ESCAPE control character", 2, null,
+ 'Delete ASCII DATA LINK ESCAPE control character'
+ ],
+ [
+ "Delete ASCII\x11 DEVICE CONTROL ONE control character", 2, null,
+ 'Delete ASCII DEVICE CONTROL ONE control character'
+ ],
+ [
+ "Delete ASCII\x12 DEVICE CONTROL TWO control character", 2, null,
+ 'Delete ASCII DEVICE CONTROL TWO control character'
+ ],
+ [
+ "Delete ASCII\x13 DEVICE CONTROL THREE control character", 2, null,
+ 'Delete ASCII DEVICE CONTROL THREE control character'
+ ],
+ [
+ "Delete ASCII\x14 DEVICE CONTROL FOUR control character", 2, null,
+ 'Delete ASCII DEVICE CONTROL FOUR control character'
+ ],
+ [
+ "Delete ASCII\x15 NEGATIVE ACKNOWLEDGE control character", 2, null,
+ 'Delete ASCII NEGATIVE ACKNOWLEDGE control character'
+ ],
+ [
+ "Delete ASCII\x16 SYNCHRONOUS IDLE control character", 2, null,
+ 'Delete ASCII SYNCHRONOUS IDLE control character'
+ ],
+ [
+ "Delete ASCII\x1B ESCAPE control character", 2, null,
+ 'Delete ASCII ESCAPE control character'
+ ],
+ [
+ "Delete ASCII\x7F DELETE control character", 2, null,
+ 'Delete ASCII DELETE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x80 PADDING CHARACTER control character", 2, null,
+ 'Delete ISO 8859 PADDING CHARACTER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x81 HIGH OCTET PRESET control character", 2, null,
+ 'Delete ISO 8859 HIGH OCTET PRESET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x83 NO BREAK HERE control character", 2, null,
+ 'Delete ISO 8859 NO BREAK HERE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x84 INDEX control character", 2, null,
+ 'Delete ISO 8859 INDEX control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x86 START OF SELECTED AREA control character", 2, null,
+ 'Delete ISO 8859 START OF SELECTED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x87 END OF SELECTED AREA control character", 2, null,
+ 'Delete ISO 8859 END OF SELECTED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x88 CHARACTER TABULATION SET control character", 2, null,
+ 'Delete ISO 8859 CHARACTER TABULATION SET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x89 CHARACTER TABULATION WITH JUSTIFICATION control character", 2, null,
+ 'Delete ISO 8859 CHARACTER TABULATION WITH JUSTIFICATION control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8A LINE TABULATION SET control character", 2, null,
+ 'Delete ISO 8859 LINE TABULATION SET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8B PARTIAL LINE FORWARD control character", 2, null,
+ 'Delete ISO 8859 PARTIAL LINE FORWARD control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8C PARTIAL LINE BACKWARD control character", 2, null,
+ 'Delete ISO 8859 PARTIAL LINE BACKWARD control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8D REVERSE LINE FEED control character", 2, null,
+ 'Delete ISO 8859 REVERSE LINE FEED control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8E SINGLE SHIFT TWO control character", 2, null,
+ 'Delete ISO 8859 SINGLE SHIFT TWO control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8F SINGLE SHIFT THREE control character", 2, null,
+ 'Delete ISO 8859 SINGLE SHIFT THREE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x90 DEVICE CONTROL STRING control character", 2, null,
+ 'Delete ISO 8859 DEVICE CONTROL STRING control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x91 PRIVATE USE ONE control character", 2, null,
+ 'Delete ISO 8859 PRIVATE USE ONE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x92 PRIVATE USE TWO control character", 2, null,
+ 'Delete ISO 8859 PRIVATE USE TWO control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x93 SET TRANSMIT STATE control character", 2, null,
+ 'Delete ISO 8859 SET TRANSMIT STATE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x95 MESSAGE WAITING control character", 2, null,
+ 'Delete ISO 8859 MESSAGE WAITING control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x96 START OF GUARDED AREA control character", 2, null,
+ 'Delete ISO 8859 START OF GUARDED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x97 END OF GUARDED AREA control character", 2, null,
+ 'Delete ISO 8859 END OF GUARDED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x99 SINGLE GRAPHIC CHARACTER INTRODUCER control character", 2, null,
+ 'Delete ISO 8859 SINGLE GRAPHIC CHARACTER INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9A SINGLE CHARACTER INTRODUCER control character", 2, null,
+ 'Delete ISO 8859 SINGLE CHARACTER INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9B CONTROL SEQUENCE INTRODUCER control character", 2, null,
+ 'Delete ISO 8859 CONTROL SEQUENCE INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9D OPERATING SYSTEM COMMAND control character", 2, null,
+ 'Delete ISO 8859 OPERATING SYSTEM COMMAND control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9E PRIVACY MESSAGE control character", 2, null,
+ 'Delete ISO 8859 PRIVACY MESSAGE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9F APPLICATION PROGRAM COMMAND control character", 2, null,
+ 'Delete ISO 8859 APPLICATION PROGRAM COMMAND control character'
+ ],
+ [
+ "Delete Unicode\xE2\x80\x8B ZERO WIDTH SPACE control character", 2, null,
+ 'Delete Unicode ZERO WIDTH SPACE control character'
+ ],
+ [
+ "Delete Unicode\xEF\xBB\xBF ZERO WIDTH NO-BREAK SPACE control character", 2, null,
+ 'Delete Unicode ZERO WIDTH NO-BREAK SPACE control character'
+ ],
+ [
+ "Delete Unicode\xEF\xBF\xBD REPLACEMENT CHARACTER control character", 2, null,
+ 'Delete Unicode REPLACEMENT CHARACTER control character'
+ ],
+ // Conterting from v1 to v2.
+ [
+ 'No change', 2, 1,
+ 'No change'
+ ],
+ [
+ 'Completed 100% of work', 2, 1,
+ 'Completed 100% of work'
+ ],
+ [
+ 'Completed 100%% of work', 2, 1,
+ 'Completed 100% of work'
+ ],
+ [
+ "Windows\r\nsucks", 2, 1,
+ "Windows\nsucks"
+ ],
+ [
+ "Linux\nsucks", 2, 1,
+ "Linux\nsucks"
+ ],
+ [
+ "Mac\rsucks", 2, 1,
+ "Mac\nsucks"
+ ],
+ [
+ "LINE TABULATION\x0Bnewline", 2, 1,
+ "LINE TABULATION\nnewline"
+ ],
+ [
+ "FORM FEED\x0Cnewline", 2, 1,
+ "FORM FEED\nnewline"
+ ],
+ [
+ "END OF TRANSMISSION BLOCK\x17newline", 2, 1,
+ "END OF TRANSMISSION BLOCK\nnewline"
+ ],
+ [
+ "END OF MEDIUM\x19newline", 2, 1,
+ "END OF MEDIUM\nnewline"
+ ],
+ [
+ "SUBSTITUTE\x1Anewline", 2, 1,
+ "SUBSTITUTE\nnewline"
+ ],
+ [
+ "BREAK PERMITTED HERE\xC2\x82newline", 2, 1,
+ "BREAK PERMITTED HERE\nnewline"
+ ],
+ [
+ "NEXT LINE\xC2\x85newline", 2, 1,
+ "NEXT LINE\nnewline"
+ ],
+ [
+ "START OF STRING\xC2\x98newline", 2, 1,
+ "START OF STRING\nnewline"
+ ],
+ [
+ "STRING TERMINATOR\xC2\x9Cnewline", 2, 1,
+ "STRING TERMINATOR\nnewline"
+ ],
+ [
+ "Unicode Zl\xE2\x80\xA8newline", 2, 1,
+ "Unicode Zl\nnewline"
+ ],
+ [
+ "Unicode Zp\xE2\x80\xA9newline", 2, 1,
+ "Unicode Zp\nnewline"
+ ],
+ [
+ "Empty\n\n\n\n\n\nlines", 2, 1,
+ "Empty\n\n\nlines"
+ ],
+ [
+ "Trailing \n whitespace\t\nat \nmultilines ", 2, 1,
+ "Trailing\n whitespace\nat\nmultilines"
+ ],
+ [
+ 'Do not escape $variable names', 2, 1,
+ 'Do not escape $variable names'
+ ],
+ [
+ 'Do not escape \$variable names', 2, 1,
+ 'Do not escape $variable names'
+ ],
+ [
+ 'Do not escape $alike names', 2, 1,
+ 'Do not escape $alike names'
+ ],
+ [
+ 'Do not escape \$alike names', 2, 1,
+ 'Do not escape $alike names'
+ ],
+ [
+ 'Do not escape \$a names', 2, 1,
+ 'Do not escape $a names'
+ ],
+ [
+ 'String $a placeholder', 2, 1,
+ 'String {$a} placeholder'
+ ],
+ [
+ 'String {$a} placeholder', 2, 1,
+ 'String {$a} placeholder'
+ ],
+ [
+ 'Trailing $a', 2, 1,
+ 'Trailing {$a}'
+ ],
+ [
+ '$a leading', 2, 1,
+ '{$a} leading'
+ ],
+ [
+ '$a', 2, 1,
+ '{$a}'
+ ],
+ [
+ '$a->single', 2, 1,
+ '{$a->single}'
+ ],
+ [
+ 'Trailing $a->foobar', 2, 1,
+ 'Trailing {$a->foobar}'
+ ],
+ [
+ 'Trailing {$a}', 2, 1,
+ 'Trailing {$a}'
+ ],
+ [
+ 'Hit $a-times', 2, 1,
+ 'Hit {$a}-times'
+ ],
+ [
+ 'This is $a_book', 2, 1,
+ 'This is $a_book'
+ ],
+ [
+ 'Object $a->foo placeholder', 2, 1,
+ 'Object {$a->foo} placeholder'
+ ],
+ [
+ 'Object {$a->foo} placeholder', 2, 1,
+ 'Object {$a->foo} placeholder'
+ ],
+ [
+ 'Trailing $a->bar', 2, 1,
+ 'Trailing {$a->bar}'
+ ],
+ [
+ 'Trailing {$a->bar}', 2, 1,
+ 'Trailing {$a->bar}'
+ ],
+ [
+ 'Invalid $a-> placeholder', 2, 1,
+ 'Invalid {$a}-> placeholder'
+ ], // Weird but BC.
+ [
+ '<strong>AMOS</strong>', 2, 1,
+ '<strong>AMOS</strong>'
+ ],
+ [
+ "'Murder!', she wrote", 2, 1,
+ "'Murder!', she wrote"
+ ], // Will be escaped by var_export().
+ [
+ "\'Murder!\', she wrote", 2, 1,
+ "'Murder!', she wrote"
+ ], // Will be escaped by var_export().
+ [
+ "\t Trim Hunter \t\t", 2, 1,
+ 'Trim Hunter'
+ ],
+ [
+ 'Delete role "$a->role"?', 2, 1,
+ 'Delete role "{$a->role}"?'
+ ],
+ [
+ 'Delete role \"$a->role\"?', 2, 1,
+ 'Delete role "{$a->role}"?'
+ ],
+ [
+ 'See $CFG->foo', 2, 1,
+ 'See $CFG->foo'
+ ],
+ [
+ "Delete ASCII\0 NULL control character", 2, 1,
+ 'Delete ASCII NULL control character'
+ ],
+ [
+ "Delete ASCII\x05 ENQUIRY control character", 2, 1,
+ 'Delete ASCII ENQUIRY control character'
+ ],
+ [
+ "Delete ASCII\x06 ACKNOWLEDGE control character", 2, 1,
+ 'Delete ASCII ACKNOWLEDGE control character'
+ ],
+ [
+ "Delete ASCII\x07 BELL control character", 2, 1,
+ 'Delete ASCII BELL control character'
+ ],
+ [
+ "Delete ASCII\x0E SHIFT OUT control character", 2, 1,
+ 'Delete ASCII SHIFT OUT control character'
+ ],
+ [
+ "Delete ASCII\x0F SHIFT IN control character", 2, 1,
+ 'Delete ASCII SHIFT IN control character'
+ ],
+ [
+ "Delete ASCII\x10 DATA LINK ESCAPE control character", 2, 1,
+ 'Delete ASCII DATA LINK ESCAPE control character'
+ ],
+ [
+ "Delete ASCII\x11 DEVICE CONTROL ONE control character", 2, 1,
+ 'Delete ASCII DEVICE CONTROL ONE control character'
+ ],
+ [
+ "Delete ASCII\x12 DEVICE CONTROL TWO control character", 2, 1,
+ 'Delete ASCII DEVICE CONTROL TWO control character'
+ ],
+ [
+ "Delete ASCII\x13 DEVICE CONTROL THREE control character", 2, 1,
+ 'Delete ASCII DEVICE CONTROL THREE control character'
+ ],
+ [
+ "Delete ASCII\x14 DEVICE CONTROL FOUR control character", 2, 1,
+ 'Delete ASCII DEVICE CONTROL FOUR control character'
+ ],
+ [
+ "Delete ASCII\x15 NEGATIVE ACKNOWLEDGE control character", 2, 1,
+ 'Delete ASCII NEGATIVE ACKNOWLEDGE control character'
+ ],
+ [
+ "Delete ASCII\x16 SYNCHRONOUS IDLE control character", 2, 1,
+ 'Delete ASCII SYNCHRONOUS IDLE control character'
+ ],
+ [
+ "Delete ASCII\x1B ESCAPE control character", 2, 1,
+ 'Delete ASCII ESCAPE control character'
+ ],
+ [
+ "Delete ASCII\x7F DELETE control character", 2, 1,
+ 'Delete ASCII DELETE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x80 PADDING CHARACTER control character", 2, 1,
+ 'Delete ISO 8859 PADDING CHARACTER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x81 HIGH OCTET PRESET control character", 2, 1,
+ 'Delete ISO 8859 HIGH OCTET PRESET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x83 NO BREAK HERE control character", 2, 1,
+ 'Delete ISO 8859 NO BREAK HERE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x84 INDEX control character", 2, 1,
+ 'Delete ISO 8859 INDEX control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x86 START OF SELECTED AREA control character", 2, 1,
+ 'Delete ISO 8859 START OF SELECTED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x87 END OF SELECTED AREA control character", 2, 1,
+ 'Delete ISO 8859 END OF SELECTED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x88 CHARACTER TABULATION SET control character", 2, 1,
+ 'Delete ISO 8859 CHARACTER TABULATION SET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x89 CHARACTER TABULATION WITH JUSTIFICATION control character", 2, 1,
+ 'Delete ISO 8859 CHARACTER TABULATION WITH JUSTIFICATION control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8A LINE TABULATION SET control character", 2, 1,
+ 'Delete ISO 8859 LINE TABULATION SET control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8B PARTIAL LINE FORWARD control character", 2, 1,
+ 'Delete ISO 8859 PARTIAL LINE FORWARD control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8C PARTIAL LINE BACKWARD control character", 2, 1,
+ 'Delete ISO 8859 PARTIAL LINE BACKWARD control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8D REVERSE LINE FEED control character", 2, 1,
+ 'Delete ISO 8859 REVERSE LINE FEED control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8E SINGLE SHIFT TWO control character", 2, 1,
+ 'Delete ISO 8859 SINGLE SHIFT TWO control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x8F SINGLE SHIFT THREE control character", 2, 1,
+ 'Delete ISO 8859 SINGLE SHIFT THREE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x90 DEVICE CONTROL STRING control character", 2, 1,
+ 'Delete ISO 8859 DEVICE CONTROL STRING control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x91 PRIVATE USE ONE control character", 2, 1,
+ 'Delete ISO 8859 PRIVATE USE ONE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x92 PRIVATE USE TWO control character", 2, 1,
+ 'Delete ISO 8859 PRIVATE USE TWO control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x93 SET TRANSMIT STATE control character", 2, 1,
+ 'Delete ISO 8859 SET TRANSMIT STATE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x95 MESSAGE WAITING control character", 2, 1,
+ 'Delete ISO 8859 MESSAGE WAITING control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x96 START OF GUARDED AREA control character", 2, 1,
+ 'Delete ISO 8859 START OF GUARDED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x97 END OF GUARDED AREA control character", 2, 1,
+ 'Delete ISO 8859 END OF GUARDED AREA control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x99 SINGLE GRAPHIC CHARACTER INTRODUCER control character", 2, 1,
+ 'Delete ISO 8859 SINGLE GRAPHIC CHARACTER INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9A SINGLE CHARACTER INTRODUCER control character", 2, 1,
+ 'Delete ISO 8859 SINGLE CHARACTER INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9B CONTROL SEQUENCE INTRODUCER control character", 2, 1,
+ 'Delete ISO 8859 CONTROL SEQUENCE INTRODUCER control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9D OPERATING SYSTEM COMMAND control character", 2, 1,
+ 'Delete ISO 8859 OPERATING SYSTEM COMMAND control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9E PRIVACY MESSAGE control character", 2, 1,
+ 'Delete ISO 8859 PRIVACY MESSAGE control character'
+ ],
+ [
+ "Delete ISO 8859\xC2\x9F APPLICATION PROGRAM COMMAND control character", 2, 1,
+ 'Delete ISO 8859 APPLICATION PROGRAM COMMAND control character'
+ ],
+ [
+ "Delete Unicode\xE2\x80\x8B ZERO WIDTH SPACE control character", 2, 1,
+ 'Delete Unicode ZERO WIDTH SPACE control character'
+ ],
+ [
+ "Delete Unicode\xEF\xBB\xBF ZERO WIDTH NO-BREAK SPACE control character", 2, 1,
+ 'Delete Unicode ZERO WIDTH NO-BREAK SPACE control character'
+ ],
+ [
+ "Delete Unicode\xEF\xBF\xBD REPLACEMENT CHARACTER control character", 2, 1,
+ 'Delete Unicode REPLACEMENT CHARACTER control character'
+ ],
+ ];
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * PHP lang parser test.
+ *
+ * @package tool_customlang
+ * @copyright 2015 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_customlang\local\mlang;
+
+use advanced_testcase;
+use moodle_exception;
+
+/**
+ * PHP lang parser test class.
+ *
+ * @package tool_customlang
+ * @copyright 2015 Damyon Wiese
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class phpparser_testcase extends advanced_testcase {
+
+
+ /**
+ * Test get instance static method.
+ *
+ */
+ public function test_get_instance(): void {
+
+ $instance = phpparser::get_instance();
+
+ $this->assertInstanceOf('tool_customlang\local\mlang\phpparser', $instance);
+ $this->assertEquals($instance, phpparser::get_instance());
+ }
+
+ /**
+ * Test get instance parse method.
+ *
+ * @dataProvider parse_provider
+ * @param string $phpcode PHP code to test
+ * @param array $expected Expected result
+ * @param bool $exception if an exception is expected
+ */
+ public function test_parse(string $phpcode, array $expected, bool $exception): void {
+
+ $instance = phpparser::get_instance();
+
+ if ($exception) {
+ $this->expectException(moodle_exception::class);
+ }
+
+ $strings = $instance->parse($phpcode);
+
+ $this->assertEquals(count($expected), count($strings));
+ foreach ($strings as $key => $langstring) {
+ $this->assertEquals($expected[$key][0], $langstring->id);
+ $this->assertEquals($expected[$key][1], $langstring->text);
+ }
+ }
+
+ /**
+ * Data provider for the test_parse.
+ *
+ * @return array
+ */
+ public function parse_provider() : array {
+ return [
+ 'Invalid PHP code' => [
+ 'No PHP code', [], false
+ ],
+ 'No PHP open tag' => [
+ "\$string['example'] = 'text';\n", [], false
+ ],
+ 'One string code' => [
+ "<?php \$string['example'] = 'text';\n", [['example', 'text']], false
+ ],
+ 'Extra spaces' => [
+ "<?php \$string['example'] = 'text';\n", [['example', 'text']], false
+ ],
+ 'Extra tabs' => [
+ "<?php \$string['example']\t=\t'text';\n", [['example', 'text']], false
+ ],
+ 'Double quote string' => [
+ "<?php
+ \$string['example'] = \"text\";
+ \$string[\"example2\"] = 'text2';
+ \$string[\"example3\"] = \"text3\";
+ ", [
+ ['example', 'text'],
+ ['example2', 'text2'],
+ ['example3', 'text3'],
+ ], false
+ ],
+ 'Multiple lines strings' => [
+ "<?php
+ \$string['example'] = 'First line\nsecondline';
+ \$string['example2'] = \"First line\nsecondline2\";
+ ", [
+ ['example', "First line\nsecondline"],
+ ['example2', "First line\nsecondline2"],
+ ], false
+ ],
+ 'Two strings code' => [
+ "<?php
+ \$string['example'] = 'text';
+ \$string['example2'] = 'text2';
+ ", [
+ ['example', 'text'],
+ ['example2', 'text2'],
+ ], false
+ ],
+ 'Scaped characters' => [
+ "<?php
+ \$string['example'] = 'Thos are \\' quotes \" 1';
+ \$string['example2'] = \"Thos are ' quotes \\\" 2\";
+ ", [
+ ['example', "Thos are ' quotes \" 1"],
+ ['example2', "Thos are ' quotes \" 2"],
+ ], false
+ ],
+ 'PHP with single line comments' => [
+ "<?php
+ // This is a comment.
+ \$string['example'] = 'text';
+ // This is another commment.
+ ", [
+ ['example', 'text'],
+ ], false
+ ],
+ 'PHP with block comments' => [
+ "<?php
+ /* This is a block comment. */
+ \$string['example'] = 'text';
+ /* This is another
+ block comment. */
+ ", [
+ ['example', 'text'],
+ ], false
+ ],
+ 'Wrong variable name' => [
+ "<?php
+ \$stringwrong['example'] = 'text';
+ \$wringstring['example'] = 'text';
+ ", [], false
+ ],
+ 'Single line commented valid line' => [
+ "<?php
+ // \$string['example'] = 'text';
+ ", [], false
+ ],
+ 'Block commented valid line' => [
+ "<?php
+ /*
+ \$string['example'] = 'text';
+ */
+ ", [], false
+ ],
+ 'Syntax error 1 (double assignation)' => [
+ "<?php
+ \$string['example'] = 'text' = 'wrong';
+ ", [], true
+ ],
+ 'Syntax error 2 (no closing string)' => [
+ "<?php
+ \$string['example'] = 'wrong;
+ ", [], true
+ ],
+ 'Syntax error 3 (Array without key)' => [
+ "<?php
+ \$string[] = 'wrong';
+ ", [], true
+ ],
+ 'Syntax error 4 (Array not open)' => [
+ "<?php
+ \$string'example'] = 'wrong';
+ ", [], true
+ ],
+ 'Syntax error 5 (Array not closed)' => [
+ "<?php
+ \$string['example' = 'wrong';
+ ", [], true
+ ],
+ 'Syntax error 6 (Missing assignment)' => [
+ "<?php
+ \$string['example'] 'wrong';
+ ", [], true
+ ],
+ ];
+ }
+
+}
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2020100101;
+$plugin->version = 2020101300;
$plugin->requires = 2020060900;
$plugin->component = 'tool_customlang'; // Full name of the plugin (used for diagnostics)
--- /dev/null
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * CSS selector client side filter.
+ *
+ * @module tool_usertours/filter_cssselector
+ * @class filter_cssselector
+ * @package tool_usertours
+ * @copyright 2020 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+/**
+ * Checks whether the configured CSS selector exists on this page.
+ *
+ * @param {array} tourConfig The tour configuration.
+ * @returns {boolean}
+ */
+export const filterMatches = function(tourConfig) {
+ let filterValues = tourConfig.filtervalues.cssselector;
+ if (filterValues[0]) {
+ return !!document.querySelector(filterValues[0]);
+ }
+ // If there is no CSS selector configured, this page matches.
+ return true;
+};
currentTour: null,
- context: null,
-
/**
* Initialise the user tour for the current page.
*
* @method init
- * @param {Number} tourId The ID of the tour to start.
- * @param {Bool} startTour Attempt to start the tour now.
- * @param {Number} context The context of the current page.
+ * @param {Array} tourDetails The matching tours for this page.
+ * @param {Array} filters The names of all client side filters.
*/
- init: function(tourId, startTour, context) {
- // Only one tour per page is allowed.
- usertours.tourId = tourId;
+ init: function(tourDetails, filters) {
+ let requirements = [];
+ for (var req = 0; req < filters.length; req++) {
+ requirements[req] = 'tool_usertours/filter_' + filters[req];
+ }
+ require(requirements, function() {
+ // Run the client side filters to find the first matching tour.
+ let matchingTour = null;
+ for (let key in tourDetails) {
+ let tour = tourDetails[key];
+ for (let i = 0; i < filters.length; i++) {
+ let filter = arguments[i];
+ if (filter.filterMatches(tour)) {
+ matchingTour = tour;
+ } else {
+ // If any filter doesn't match, move on to the next tour.
+ matchingTour = null;
+ break;
+ }
+ }
+ // If all filters matched then use this tour.
+ if (matchingTour) {
+ break;
+ }
+ }
- usertours.context = context;
+ if (matchingTour === null) {
+ return;
+ }
- if (typeof startTour === 'undefined') {
- startTour = true;
- }
+ // Only one tour per page is allowed.
+ usertours.tourId = matchingTour.tourId;
- if (startTour) {
- // Fetch the tour configuration.
- usertours.fetchTour(tourId);
- }
+ let startTour = matchingTour.startTour;
+ if (typeof startTour === 'undefined') {
+ startTour = true;
+ }
+
+ if (startTour) {
+ // Fetch the tour configuration.
+ usertours.fetchTour(usertours.tourId);
+ }
- usertours.addResetLink();
- // Watch for the reset link.
- $('body').on('click', '[data-action="tool_usertours/resetpagetour"]', function(e) {
- e.preventDefault();
- usertours.resetTourState(usertours.tourId);
+ usertours.addResetLink();
+ // Watch for the reset link.
+ $('body').on('click', '[data-action="tool_usertours/resetpagetour"]', function(e) {
+ e.preventDefault();
+ usertours.resetTourState(usertours.tourId);
+ });
});
},
methodname: 'tool_usertours_fetch_and_start_tour',
args: {
tourid: tourId,
- context: usertours.context,
+ context: M.cfg.contextid,
pageurl: window.location.href,
}
}
methodname: 'tool_usertours_step_shown',
args: {
tourid: usertours.tourId,
- context: usertours.context,
+ context: M.cfg.contextid,
pageurl: window.location.href,
stepid: stepConfig.stepid,
stepindex: this.getCurrentStepNumber(),
methodname: 'tool_usertours_complete_tour',
args: {
tourid: usertours.tourId,
- context: usertours.context,
+ context: M.cfg.contextid,
pageurl: window.location.href,
stepid: stepConfig.stepid,
stepindex: this.getCurrentStepNumber(),
methodname: 'tool_usertours_reset_tour',
args: {
tourid: tourId,
- context: usertours.context,
+ context: M.cfg.contextid,
pageurl: window.location.href,
}
}
$result = [];
- if ($tourinstance = \tool_usertours\manager::get_matching_tours(new \moodle_url($params['pageurl']))) {
- if ($tour->get_id() === $tourinstance->get_id()) {
+ $matchingtours = \tool_usertours\manager::get_matching_tours(new \moodle_url($params['pageurl']));
+ foreach ($matchingtours as $match) {
+ if ($tour->get_id() === $match->get_id()) {
$result['startTour'] = $tour->get_id();
\tool_usertours\event\tour_reset::create([
'pageurl' => $params['pageurl'],
],
])->trigger();
-
+ break;
}
}
namespace tool_usertours;
+use tool_usertours\local\clientside_filter\clientside_filter;
+
defined('MOODLE_INTERNAL') || die();
/**
}
self::$bootstrapped = true;
- if ($tour = manager::get_current_tour()) {
+ $tours = manager::get_current_tours();
+
+ if ($tours) {
+ $filters = static::get_all_clientside_filters();
+
+ $tourdetails = array_map(function($tour) use ($filters) {
+ return [
+ 'tourId' => $tour->get_id(),
+ 'startTour' => $tour->should_show_for_user(),
+ 'filtervalues' => $tour->get_client_filter_values($filters),
+ ];
+ }, $tours);
+
+ $filternames = [];
+ foreach ($filters as $filter) {
+ $filternames[] = $filter::get_filter_name();
+ }
+
$PAGE->requires->js_call_amd('tool_usertours/usertours', 'init', [
- $tour->get_id(),
- $tour->should_show_for_user(),
- $PAGE->context->id,
- ]);
+ $tourdetails,
+ $filternames,
+ ]);
}
}
/**
- * Add the reset link to the current page.
+ * Get a list of all possible filters.
+ *
+ * @return array
*/
- public static function bootstrap_reset() {
- if (manager::get_current_tour()) {
- echo \html_writer::link('', get_string('resettouronpage', 'tool_usertours'), [
- 'data-action' => 'tool_usertours/resetpagetour',
- ]);
- }
+ public static function get_all_filters() {
+ $filters = \core_component::get_component_classes_in_namespace('tool_usertours', 'local\filter');
+ $filters = array_keys($filters);
+
+ $filters = array_filter($filters, function($filterclass) {
+ $rc = new \ReflectionClass($filterclass);
+ return $rc->isInstantiable();
+ });
+
+ $filters = array_merge($filters, static::get_all_clientside_filters());
+
+ return $filters;
}
/**
- * Get a list of all possible filters.
+ * Get a list of all clientside filters.
*
* @return array
*/
- public static function get_all_filters() {
- $filters = \core_component::get_component_classes_in_namespace('tool_usertours', 'local\filter');
+ public static function get_all_clientside_filters() {
+ $filters = \core_component::get_component_classes_in_namespace('tool_usertours', 'local\clientside_filter');
$filters = array_keys($filters);
$filters = array_filter($filters, function($filterclass) {
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Clientside filter base.
+ *
+ * @package tool_usertours
+ * @copyright 2020 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace tool_usertours\local\clientside_filter;
+
+defined('MOODLE_INTERNAL') || die();
+
+use stdClass;
+use tool_usertours\local\filter\base;
+use tool_usertours\tour;
+
+/**
+ * Clientside filter base.
+ *
+ * @copyright 2020 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+abstract class clientside_filter extends base {
+ /**
+ * Returns the filter values needed for client side filtering.
+ *
+ * @param tour $tour The tour to find the filter values for
+ * @return stdClass
+ */
+ public static function get_client_side_values(tour $tour): stdClass {
+ $data = (object) [];
+
+ if (is_a(static::class, clientside_filter::class, true)) {
+ $data->filterdata = $tour->get_filter_values(static::get_filter_name());
+ }
+
+ return $data;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Selector filter.
+ *
+ * @package tool_usertours
+ * @copyright 2020 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+namespace tool_usertours\local\clientside_filter;
+
+use stdClass;
+use tool_usertours\tour;
+
+/**
+ * Course filter.
+ *
+ * @copyright 2020 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class cssselector extends clientside_filter {
+ /**
+ * The name of the filter.
+ *
+ * @return string
+ */
+ public static function get_filter_name() {
+ return 'cssselector';
+ }
+
+ /**
+ * Overrides the base add form element with a selector text box.
+ *
+ * @param \MoodleQuickForm $mform
+ */
+ public static function add_filter_to_form(\MoodleQuickForm &$mform) {
+ $filtername = self::get_filter_name();
+ $key = "filter_{$filtername}";
+
+ $mform->addElement('text', $key, get_string($key, 'tool_usertours'));
+ $mform->setType($key, PARAM_RAW);
+ $mform->addHelpButton($key, $key, 'tool_usertours');
+ }
+
+ /**
+ * Prepare the filter values for the form.
+ *
+ * @param tour $tour The tour to prepare values from
+ * @param stdClass $data The data value
+ * @return stdClass
+ */
+ public static function prepare_filter_values_for_form(tour $tour, \stdClass $data) {
+ $filtername = static::get_filter_name();
+
+ $key = "filter_{$filtername}";
+ $values = $tour->get_filter_values($filtername);
+ if (empty($values)) {
+ $values = [""];
+ }
+ $data->$key = $values[0];
+
+ return $data;
+ }
+
+ /**
+ * Save the filter values from the form to the tour.
+ *
+ * @param tour $tour The tour to save values to
+ * @param stdClass $data The data submitted in the form
+ */
+ public static function save_filter_values_from_form(tour $tour, \stdClass $data) {
+ $filtername = static::get_filter_name();
+
+ $key = "filter_{$filtername}";
+
+ $newvalue = [$data->$key];
+ if (empty($data->$key)) {
+ $newvalue = [];
+ }
+
+ $tour->set_filter_values($filtername, $newvalue);
+ }
+
+ /**
+ * Returns the filter values needed for client side filtering.
+ *
+ * @param tour $tour The tour to find the filter values for
+ * @return stdClass
+ */
+ public static function get_client_side_values(tour $tour): stdClass {
+ $filtername = static::get_filter_name();
+ $filtervalues = $tour->get_filter_values($filtername);
+
+ // Filter values might not exist for tours that were created before this filter existed.
+ if (!$filtervalues) {
+ return new stdClass;
+ }
+
+ return (object) $filtervalues;
+ }
+}
}
/**
- * Get the first tour matching the current page URL.
+ * Get all tours for the current page URL.
*
- * @param bool $reset Forcibly update the current tour
- * @return tour
+ * @param bool $reset Forcibly update the current tours
+ * @return array
*/
- public static function get_current_tour($reset = false) {
+ public static function get_current_tours($reset = false): array {
global $PAGE;
- static $tour = false;
+ static $tours = false;
- if ($tour === false || $reset) {
- $tour = self::get_matching_tours($PAGE->url);
+ if ($tours === false || $reset) {
+ $tours = self::get_matching_tours($PAGE->url);
}
- return $tour;
+ return $tours;
}
/**
- * Get the first tour matching the specified URL.
+ * Get all tours matching the specified URL.
*
* @param moodle_url $pageurl The URL to match.
- * @return tour
+ * @return array
*/
- public static function get_matching_tours(\moodle_url $pageurl) {
+ public static function get_matching_tours(\moodle_url $pageurl): array {
global $PAGE;
$tours = cache::get_matching_tourdata($pageurl);
+ $matches = [];
+ $filters = helper::get_all_filters();
foreach ($tours as $record) {
$tour = tour::load_from_record($record);
- if ($tour->is_enabled() && $tour->matches_all_filters($PAGE->context)) {
- return $tour;
+ if ($tour->is_enabled() && $tour->matches_all_filters($PAGE->context, $filters)) {
+ $matches[] = $tour;
}
}
- return null;
+ return $matches;
}
/**
namespace tool_usertours;
+use tool_usertours\local\clientside_filter\clientside_filter;
+
defined('MOODLE_INTERNAL') || die();
/**
/**
* Check whether this tour matches all filters.
*
- * @param context $context The context to check
+ * @param \context $context The context to check.
+ * @param array|null $filters Optional array of filters.
* @return bool
*/
- public function matches_all_filters(\context $context) {
- $filters = helper::get_all_filters();
+ public function matches_all_filters(\context $context, array $filters = null): bool {
+ if (!$filters) {
+ $filters = helper::get_all_filters();
+ }
// All filters must match.
// If any one filter fails to match, we return false.
return true;
}
+
+ /**
+ * Gets all filter values for use in client side filters.
+ *
+ * @param array $filters Array of clientside filters.
+ * @return array
+ */
+ public function get_client_filter_values(array $filters): array {
+ $results = [];
+
+ foreach ($filters as $filter) {
+ $results[$filter::get_filter_name()] = $filter::get_client_side_values($this);
+ }
+
+ return $results;
+ }
}
$string['filter_course_help'] = 'Show the tour on a page that is associated with the selected course.';
$string['filter_courseformat'] = 'Course format';
$string['filter_courseformat_help'] = 'Show the tour on a page that is associated with a course using the selected course format.';
+$string['filter_cssselector'] = 'CSS selector';
+$string['filter_cssselector_help'] = 'Only show the tour when the specified CSS selector is found on the page.';
$string['filter_header'] = 'Tour filters';
$string['filter_help'] = 'Select the conditions under which the tour will be shown. All of the filters must match for a tour to be shown to a user.';
$string['filter_date_account_creation'] = 'User account creation date within';
When I am on "Course 2" course homepage
And I wait until the page is ready
Then I should not see "Welcome to your course tour."
+
+ @javascript
+ Scenario: Add tours with CSS selectors
+ Given the following "users" exist:
+ | username | firstname | lastname | email |
+ | student1 | Student | 1 | student1@example.com |
+ Given the following "courses" exist:
+ | fullname | shortname | format | enablecompletion |
+ | Course 1 | C1 | topics | 1 |
+ | Course 2 | C2 | topics | 1 |
+ And I log in as "admin"
+ And I am on "Course 1" course homepage with editing mode on
+ And I add a "Wiki" to section "1" and I fill the form with:
+ | Wiki name | Test wiki name |
+ | Description | Test wiki description |
+ | First page name | First page |
+ | Wiki mode | Collaborative wiki |
+ And I am on "Course 2" course homepage
+ And I add a "Forum" to section "1" and I fill the form with:
+ | Forum name | Test forum name |
+ | Forum type | Standard forum for general use |
+ | Description | Test forum description |
+ And I add a new user tour with:
+ | Name | Wiki tour |
+ | Description | A tour with both matches |
+ | Apply to URL match | /course/view.php% |
+ | Tour is enabled | 1 |
+ | CSS selector | .modtype_wiki |
+ And I add steps to the "Wiki tour" tour:
+ | targettype | Title | Content |
+ | Display in middle of page | Welcome | Welcome to the Wiki tour |
+ And I add a new user tour with:
+ | Name | Forum tour |
+ | Description | A tour with both matches |
+ | Apply to URL match | /course/view.php% |
+ | Tour is enabled | 1 |
+ | CSS selector | .modtype_forum |
+ And I add steps to the "Forum tour" tour:
+ | targettype | Title | Content |
+ | Display in middle of page | Welcome | Welcome to the Forum tour |
+ And I am on "Course 1" course homepage
+ Then I should see "Welcome to the Wiki tour"
+ And I am on "Course 2" course homepage
+ Then I should see "Welcome to the Forum tour"
+
+ @javascript
+ Scenario: Check filtering respects the sort order
+ Given the following "users" exist:
+ | username | firstname | lastname | email |
+ | student1 | Student | 1 | student1@example.com |
+ And I log in as "admin"
+ And I add a new user tour with:
+ | Name | First tour |
+ | Description | The first tour |
+ | Apply to URL match | /my/% |
+ | Tour is enabled | 1 |
+ | CSS selector | #page-my-index |
+ And I add steps to the "First tour" tour:
+ | targettype | Title | Content |
+ | Display in middle of page | Welcome | Welcome to the First tour |
+ And I add a new user tour with:
+ | Name | Second tour |
+ | Description | The second tour |
+ | Apply to URL match | /my/% |
+ | Tour is enabled | 0 |
+ | CSS selector | #page-my-index |
+ And I add steps to the "Second tour" tour:
+ | targettype | Title | Content |
+ | Display in middle of page | Welcome | Welcome to the Second tour |
+ And I add a new user tour with:
+ | Name | Third tour |
+ | Description | The third tour |
+ | Apply to URL match | /my/% |
+ | Tour is enabled | 1 |
+ | CSS selector | #page-my-index |
+ And I add steps to the "Third tour" tour:
+ | targettype | Title | Content |
+ | Display in middle of page | Welcome | Welcome to the Third tour |
+ And I am on homepage
+ Then I should see "Welcome to the First tour"
+ And I open the User tour settings page
+ And I click on "Move tour down" "link" in the "The first tour" "table_row"
+ And I click on "Move tour down" "link" in the "The first tour" "table_row"
+ And I am on homepage
+ Then I should see "Welcome to the Third tour"
'description' => '',
'configdata' => '',
],
+ [
+ 'pathmatch' => '/my/%',
+ 'enabled' => true,
+ 'name' => 'My tour enabled 2',
+ 'description' => '',
+ 'configdata' => '',
+ ],
[
'pathmatch' => '/my/%',
'enabled' => false,
'No matches found' => [
$alltours,
$CFG->wwwroot . '/some/invalid/value',
- null,
+ [],
],
'Never return a disabled tour' => [
$alltours,
$CFG->wwwroot . '/my/index.php',
- 'My tour enabled',
+ ['My tour enabled', 'My tour enabled 2'],
],
'My not course' => [
$alltours,
$CFG->wwwroot . '/my/index.php',
- 'My tour enabled',
+ ['My tour enabled', 'My tour enabled 2'],
],
'My with params' => [
$alltours,
$CFG->wwwroot . '/my/index.php?id=42',
- 'My tour enabled',
+ ['My tour enabled', 'My tour enabled 2'],
],
'Course with params' => [
$alltours,
$CFG->wwwroot . '/course/?id=42',
- 'course tour enabled',
+ ['course tour enabled'],
],
'Course with params and trailing content' => [
$alltours,
$CFG->wwwroot . '/course/?id=42&foo=bar',
- 'course tour with additional params enabled',
+ ['course tour with additional params enabled', 'course tour enabled'],
],
];
}
* Tests for the get_matching_tours function.
*
* @dataProvider get_matching_tours_provider
- * @param array $alltours The list of tours to insert
- * @param string $url The URL to test
- * @param string $expected The name of the expected matching tour
+ * @param array $alltours The list of tours to insert.
+ * @param string $url The URL to test.
+ * @param array $expected List of names of the expected matching tours.
*/
- public function test_get_matching_tours($alltours, $url, $expected) {
+ public function test_get_matching_tours(array $alltours, string $url, array $expected) {
$this->resetAfterTest();
foreach ($alltours as $tourconfig) {
$this->helper_create_step((object) ['tourid' => $tour->get_id()]);
}
- $match = \tool_usertours\manager::get_matching_tours(new moodle_url($url));
- if ($expected === null) {
- $this->assertNull($match);
- } else {
- $this->assertNotNull($match);
- $this->assertEquals($expected, $match->get_name());
+ $matches = \tool_usertours\manager::get_matching_tours(new moodle_url($url));
+ $this->assertEquals(count($expected), count($matches));
+ for ($i = 0; $i < count($matches); $i++) {
+ $this->assertEquals($expected[$i], $matches[$i]->get_name());
}
}
}
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2020082700; // The current module version (Date: YYYYMMDDXX).
+$plugin->version = 2020082701; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2020060900; // Requires this Moodle version.
$plugin->component = 'tool_usertours'; // Full name of the plugin (used for diagnostics).
ksort($default);
$return = $return + $default;
- foreach ($instance->get_definition_mappings() as $mapping) {
+ $mappings = $instance->get_definition_mappings();
+ foreach ($mappings as $mapping) {
if (!array_key_exists($mapping['store'], $return)) {
continue;
}
$return[$mapping['store']]['mappings']++;
}
+ // Now get all definitions, and if not mapped, increment the defaults for the mode.
+ $modemappings = $instance->get_mode_mappings();
+ foreach ($instance->get_definitions() as $definition) {
+ // Construct the definition name to search for.
+ $defname = $definition['component'] . '/' . $definition['area'];
+ // Skip if definition is already mapped.
+ if (array_search($defname, array_column($mappings, 'definition')) !== false) {
+ continue;
+ }
+
+ $mode = $definition['mode'];
+ // Get the store name of the default mapping from the mode.
+ $index = array_search($mode, array_column($modemappings, 'mode'));
+ $store = $modemappings[$index]['store'];
+ $return[$store]['mappings']++;
+ }
+
return $return;
}
$this->assertEquals(0, $summary['default']);
$this->assertEquals(1, $summary['isready']);
$this->assertEquals(1, $summary['requirementsmet']);
- $this->assertEquals(1, $summary['mappings']);
+
+ // Find the number of mappings to sessionstore.
+ $mappingcount = count(array_filter($config->get_definitions(), function($element) {
+ return $element['mode'] === cache_store::MODE_APPLICATION;
+ }));
+ $this->assertEquals($mappingcount, $summary['mappings']);
$definitionsummaries = core_cache\administration_helper::get_definition_summaries();
$this->assertInternalType('array', $definitionsummaries);
'minorVersion' => $type->version->minor,
'patchVersion' => $type->version->patch,
];
+ // Add example and tutorial to the library, to store this information too.
+ if (isset($type->example)) {
+ $library['example'] = $type->example;
+ }
+ if (isset($type->tutorial)) {
+ $library['tutorial'] = $type->tutorial;
+ }
$shoulddownload = true;
if ($framework->getLibraryId($type->id, $type->version->major, $type->version->minor)) {
* @return int|null Returns the id of the content type library installed, null otherwise.
*/
public function fetch_content_type(array $library): ?int {
+ global $DB;
+
$factory = new factory();
// Download the latest content type from the H5P official repository.
$librarykey = static::libraryToString($library);
$libraryid = $factory->get_storage()->h5pC->librariesJsonData[$librarykey]["libraryId"];
+ // Update example and tutorial (if any of them are defined in $library).
+ $params = ['id' => $libraryid];
+ if (array_key_exists('example', $library)) {
+ $params['example'] = $library['example'];
+ }
+ if (array_key_exists('tutorial', $library)) {
+ $params['tutorial'] = $library['tutorial'];
+ }
+ if (count($params) > 1) {
+ $DB->update_record('h5p_libraries', $params);
+ }
+
return $libraryid;
}
* @return mixed|null Returns results from querying the database
*/
public function getContentTypeCache($machinename = null) {
- // This is to be implemented when the Hub client is used.
- return [];
+ global $DB;
+
+ // Added some extra fields to the result because they are expected by functions calling this. They have been
+ // taken from method getCachedLibsMap() in h5peditor.class.php.
+ $sql = "SELECT l.id, l.machinename AS machine_name, l.majorversion AS major_version,
+ l.minorversion AS minor_version, l.patchversion AS patch_version, l.coremajor AS h5p_major_version,
+ l.coreminor AS h5p_minor_version, l.title, l.tutorial, l.example,
+ '' AS summary, '' AS description, '' AS icon, 0 AS created_at, 0 AS updated_at, 0 AS is_recommended,
+ 0 AS popularity, '' AS screenshots, '' AS license, '' AS owner
+ FROM {h5p_libraries} l";
+ $params = [];
+ if (!empty($machinename)) {
+ $sql .= ' WHERE l.machinename = :machine_name';
+ $params = ['machine_name' => $machinename];
+ }
+
+ return $DB->get_records_sql($sql, $params);
}
/**
if ($libraries !== null) {
// Get details for the specified libraries.
$librariesin = [];
- $fields = 'title, runnable, metadatasettings';
+ $fields = 'title, runnable, metadatasettings, example, tutorial';
foreach ($libraries as $library) {
$params = [
$library->title = $details->title;
$library->runnable = $details->runnable;
$library->metadataSettings = json_decode($details->metadatasettings);
+ $library->example = $details->example;
+ $library->tutorial = $details->tutorial;
$librariesin[] = $library;
}
}
} else {
- $fields = 'id, machinename as name, title, majorversion, minorversion, metadatasettings';
+ $fields = 'id, machinename as name, title, majorversion, minorversion, metadatasettings, example, tutorial';
$librariesin = api::get_contenttype_libraries($fields);
}
* @param string $url
*/
public function setLibraryTutorialUrl($libraryname, $url) {
- // Tutorial url is currently not being used or stored in libraries.
+ global $DB;
+
+ $sql = 'UPDATE {h5p_libraries}
+ SET tutorial = :tutorial
+ WHERE machinename = :machinename';
+ $params = [
+ 'tutorial' => $url,
+ 'machinename' => $libraryname,
+ ];
+ $DB->execute($sql, $params);
}
/**
$this->assertEquals($expectedlibraries, array_keys($actuallibraries));
}
+ /**
+ * Test that getContentTypeCache method retrieves the latest library versions that exists locally.
+ */
+ public function test_getContentTypeCache(): void {
+ $this->resetAfterTest();
+
+ $h5pgenerator = \testing_util::get_data_generator()->get_plugin_generator('core_h5p');
+
+ // Create several libraries records.
+ $lib1 = $h5pgenerator->create_library_record('Library1', 'Lib1', 1, 0, 1, '', null, 'http://tutorial.org',
+ 'http://example.org');
+ $lib2 = $h5pgenerator->create_library_record('Library2', 'Lib2', 2, 0, 1, '', null, 'http://tutorial.org');
+ $lib3 = $h5pgenerator->create_library_record('Library3', 'Lib3', 3, 0);
+ $libs = [$lib1, $lib2, $lib3];
+
+ $libraries = $this->editorajax->getContentTypeCache();
+ $this->assertCount(3, $libraries);
+ foreach ($libs as $lib) {
+ $library = $libraries[$lib->id];
+ $this->assertEquals($library->id, $lib->id);
+ $this->assertEquals($library->machine_name, $lib->machinename);
+ $this->assertEquals($library->major_version, $lib->majorversion);
+ $this->assertEquals($library->tutorial, $lib->tutorial);
+ $this->assertEquals($library->example, $lib->example);
+ $this->assertEquals($library->is_recommended, 0);
+ $this->assertEquals($library->summary, '');
+ }
+ }
+
/**
* Test that the method getTranslations retrieves the translations of several libraries.
*
namespace core_h5p;
-defined('MOODLE_INTERNAL') || die();
+use core_collator;
/**
*
$this->assertEmpty($data);
}
+ /**
+ * Test the behaviour of setLibraryTutorialUrl().
+ */
+ public function test_setLibraryTutorialUrl() {
+ global $DB;
+
+ $this->resetAfterTest();
+
+ $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
+
+ // Create several libraries records.
+ $lib1 = $generator->create_library_record('Library1', 'Lib1', 1, 0, 1, '', null, 'http://tutorial1.org',
+ 'http://example.org');
+ $lib2 = $generator->create_library_record('Library2', 'Lib2', 2, 0, 1, '', null, 'http://tutorial2.org');
+ $lib3 = $generator->create_library_record('Library3', 'Lib3', 3, 0);
+
+ // Check only lib1 tutorial URL is updated.
+ $url = 'https://newtutorial.cat';
+ $this->framework->setLibraryTutorialUrl($lib1->machinename, $url);
+
+ $libraries = $DB->get_records('h5p_libraries');
+ $this->assertEquals($libraries[$lib1->id]->tutorial, $url);
+ $this->assertNotEquals($libraries[$lib2->id]->tutorial, $url);
+
+ // Check lib1 tutorial URL is set to null.
+ $this->framework->setLibraryTutorialUrl($lib1->machinename, null);
+
+ $libraries = $DB->get_records('h5p_libraries');
+ $this->assertCount(3, $libraries);
+ $this->assertNull($libraries[$lib1->id]->tutorial);
+
+ // Check no tutorial URL is set if library name doesn't exist.
+ $this->framework->setLibraryTutorialUrl('Unexisting library', $url);
+
+ $libraries = $DB->get_records('h5p_libraries');
+ $this->assertCount(3, $libraries);
+ $this->assertNull($libraries[$lib1->id]->tutorial);
+ $this->assertEquals($libraries[$lib2->id]->tutorial, 'http://tutorial2.org');
+ $this->assertNull($libraries[$lib3->id]->tutorial);
+
+ // Check tutorial is set as expected when it was null.
+ $this->framework->setLibraryTutorialUrl($lib3->machinename, $url);
+
+ $libraries = $DB->get_records('h5p_libraries');
+ $this->assertEquals($libraries[$lib3->id]->tutorial, $url);
+ $this->assertNull($libraries[$lib1->id]->tutorial);
+ $this->assertEquals($libraries[$lib2->id]->tutorial, 'http://tutorial2.org');
+ }
+
/**
* Test the behaviour of setErrorMessage().
*/
// The addons array should return 2 results (Library and Library1 addon).
$this->assertCount(2, $addons);
+ // Ensure the addons array is consistently ordered before asserting their contents.
+ core_collator::asort_array_of_arrays_by_key($addons, 'machineName');
+ [$addonone, $addontwo] = array_values($addons);
+
// Make sure the version 1.3 is the latest 'Library' addon version.
- $this->assertEquals('Library', $addons[0]['machineName']);
- $this->assertEquals(1, $addons[0]['majorVersion']);
- $this->assertEquals(3, $addons[0]['minorVersion']);
+ $this->assertEquals('Library', $addonone['machineName']);
+ $this->assertEquals(1, $addonone['majorVersion']);
+ $this->assertEquals(3, $addonone['minorVersion']);
// Make sure the version 1.2 is the latest 'Library1' addon version.
- $this->assertEquals('Library1', $addons[1]['machineName']);
- $this->assertEquals(1, $addons[1]['majorVersion']);
- $this->assertEquals(2, $addons[1]['minorVersion']);
+ $this->assertEquals('Library1', $addontwo['machineName']);
+ $this->assertEquals(1, $addontwo['majorVersion']);
+ $this->assertEquals(2, $addontwo['minorVersion']);
}
/**
$this->assertEquals('1', $libraries['MainLibrary'][0]->major_version);
$this->assertEquals('0', $libraries['MainLibrary'][0]->minor_version);
$this->assertEquals('1', $libraries['MainLibrary'][0]->patch_version);
- $this->assertEquals('MainLibrary', $libraries['MainLibrary'][0]->machine_name);
}
/**
*/
public function generate_h5p_data(bool $createlibraryfiles = false): stdClass {
// Create libraries.
- $mainlib = $libraries[] = $this->create_library_record('MainLibrary', 'Main Lib', 1, 0);
- $lib1 = $libraries[] = $this->create_library_record('Library1', 'Lib1', 2, 0);
- $lib2 = $libraries[] = $this->create_library_record('Library2', 'Lib2', 2, 1);
+ $mainlib = $libraries[] = $this->create_library_record('MainLibrary', 'Main Lib', 1, 0, 1, '', null,
+ 'http://tutorial.org', 'http://example.org');
+ $lib1 = $libraries[] = $this->create_library_record('Library1', 'Lib1', 2, 0, 1, '', null, null, 'http://example.org');
+ $lib2 = $libraries[] = $this->create_library_record('Library2', 'Lib2', 2, 1, 1, '', null, 'http://tutorial.org');
$lib3 = $libraries[] = $this->create_library_record('Library3', 'Lib3', 3, 2);
$lib4 = $libraries[] = $this->create_library_record('Library4', 'Lib4', 1, 1);
$lib5 = $libraries[] = $this->create_library_record('Library5', 'Lib5', 1, 3);
* @param int $patchversion The library's patch version
* @param string $semantics Json describing the content structure for the library
* @param string $addto The plugin configuration data
+ * @param string $tutorial The tutorial URL
+ * @param string $examlpe The example URL
* @return stdClass An object representing the added library record
*/
public function create_library_record(string $machinename, string $title, int $majorversion = 1,
- int $minorversion = 0, int $patchversion = 1, string $semantics = '', string $addto = null): stdClass {
+ int $minorversion = 0, int $patchversion = 1, string $semantics = '', string $addto = null,
+ string $tutorial = null, string $example = null): stdClass {
global $DB;
$content = array(
'preloadedcss' => 'css/example.css',
'droplibrarycss' => '',
'semantics' => $semantics,
- 'addto' => $addto
+ 'addto' => $addto,
+ 'tutorial' => $tutorial,
+ 'example' => $example
);
$libraryid = $DB->insert_record('h5p_libraries', $content);
$generator = $this->getDataGenerator()->get_plugin_generator('core_h5p');
- $data = $generator->create_library_record('Library', 'Lib', 1, 2, 3, 'Semantics example', '/regex11/');
+ $data = $generator->create_library_record(
+ 'Library', 'Lib', 1, 2, 3, 'Semantics example', '/regex11/', 'http://tutorial.org/', 'http://example.org/'
+ );
unset($data->id);
$expected = (object) [
'droplibrarycss' => '',
'semantics' => 'Semantics example',
'addto' => '/regex11/',
+ 'tutorial' => 'http://tutorial.org/',
+ 'example' => 'http://example.org/',
'coremajor' => null,
'coreminor' => null,
'metadatasettings' => null,
// Get info of latest content types versions.
$contenttypes = $this->core->get_latest_content_types()->contentTypes;
- // We are installing the first content type.
+ // We are installing the first content type with tutorial and example fields (or the first one if none has them).
$librarydata = $contenttypes[0];
+ foreach ($contenttypes as $contentype) {
+ if (isset($contenttype->tutorial) && isset($contenttype->example)) {
+ $librarydata = $contenttype;
+ break;
+ }
+ }
$library = [
'machineName' => $librarydata->id,
'minorVersion' => $librarydata->version->minor,
'patchVersion' => $librarydata->version->patch,
];
+ // Add example and tutorial to the library.
+ if (isset($librarydata->example)) {
+ $library['example'] = $librarydata->example;
+ }
+ if (isset($librarydata->tutorial)) {
+ $library['tutorial'] = $librarydata->tutorial;
+ }
// Verify that the content type is not yet installed.
$conditions['machinename'] = $library['machineName'];
$this->assertEquals($librarydata->id, $typeinstalled->machinename);
$this->assertEquals($librarydata->coreApiVersionNeeded->major, $typeinstalled->coremajor);
$this->assertEquals($librarydata->coreApiVersionNeeded->minor, $typeinstalled->coreminor);
+ if (isset($librarydata->tutorial)) {
+ $this->assertEquals($librarydata->tutorial, $typeinstalled->tutorial);
+ $this->assertEquals($librarydata->example, $typeinstalled->example);
+ }
}
/**
$string['loginasonecourse'] = 'You cannot enter this course.<br /> You have to terminate the "Login as" session before entering any other course.';
$string['maxbytesfile'] = 'The file {$a->file} is too large. The maximum size you can upload is {$a->size}.';
$string['maxareabytes'] = 'The file is larger than the space remaining in this area.';
+$string['messageundeliveredbynotificationsettings'] = 'The message could not be sent because personal messages between users (in Notification settings) has been disabled by a site administrator.';
$string['messagingdisable'] = 'Messaging is disabled on this site';
$string['mimetexisnotexist'] = 'Your system is not configured to run mimeTeX. You need to obtain the C source from <a href="https://www.forkosh.com/mimetex.zip">https://www.forkosh.com/mimetex.zip</a>, compile it and put the executable into your moodle/filter/tex/ directory.';
$string['mimetexnotexecutable'] = 'Custom mimetex is not executable!';
<FIELD NAME="coremajor" TYPE="int" LENGTH="4" NOTNULL="false" SEQUENCE="false" COMMENT="H5P core API major version required"/>
<FIELD NAME="coreminor" TYPE="int" LENGTH="4" NOTNULL="false" SEQUENCE="false" COMMENT="H5P core API minor version required"/>
<FIELD NAME="metadatasettings" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Library metadata settings"/>
+ <FIELD NAME="tutorial" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Tutorial URL"/>
+ <FIELD NAME="example" TYPE="text" NOTNULL="false" SEQUENCE="false" COMMENT="Example URL"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
upgrade_main_savepoint(true, 2020100700.00);
}
+ if ($oldversion < 2020101300.01) {
+ // Define fields tutorial and example to be added to h5p_libraries.
+ $table = new xmldb_table('h5p_libraries');
+
+ // Add tutorial field.
+ $field = new xmldb_field('tutorial', XMLDB_TYPE_TEXT, null, null, null, null, null, 'metadatasettings');
+ if (!$dbman->field_exists($table, $field)) {
+ $dbman->add_field($table, $field);
+ }
+
+ // Add example field.
+ $field = new xmldb_field('example', XMLDB_TYPE_TEXT, null, null, null, null, null, 'tutorial');
+ if (!$dbman->field_exists($table, $field)) {
+ $dbman->add_field($table, $field);
+ }
+
+ // Main savepoint reached.
+ upgrade_main_savepoint(true, 2020101300.01);
+ }
+
return true;
}
* A new admin externalpage type `\core_admin\local\externalpage\accesscallback` for use in plugin settings is available that allows
a callback to be provided to determine whether page can be accessed.
* New setting $CFG->localtempdir overrides which defaults to sys_get_temp_dir()
+* Function redirect() now emits a line of backtrace into the X-Redirect-By header when debugging is on
=== 3.9 ===
* Following function has been deprecated, please use \core\task\manager::run_from_cli().
\core\session\manager::write_close();
if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
+
// This helps when debugging redirect issues like loops and it is not clear
- // which layer in the stack sent the redirect header.
- @header('X-Redirect-By: Moodle');
+ // which layer in the stack sent the redirect header. If debugging is on
+ // then the file and line is also shown.
+ $redirectby = 'Moodle';
+ if (debugging('', DEBUG_DEVELOPER)) {
+ $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
+ $redirectby .= ' /' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
+ }
+ @header("X-Redirect-By: $redirectby");
+
// 302 might not work for POST requests, 303 is ignored by obsolete clients.
@header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
@header('Location: '.$url);
$messageid = message_send($eventdata);
+ if (!$messageid) {
+ throw new \moodle_exception('messageundeliveredbynotificationsettings', 'moodle');
+ }
+
$messagerecord = $DB->get_record('messages', ['id' => $messageid], 'id, useridfrom, fullmessage,
timecreated, fullmessagetrust');
$message = (object) [
// We should have thrown exceptions as these errors prevent results to be returned.
// See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
$resultmsg['msgid'] = -1;
+ if (!isset($errormessage)) { // Nobody has set a message error or thrown an exception, let's set it.
+ $errormessage = get_string('messageundeliveredbynotificationsettings', 'error');
+ }
$resultmsg['errormessage'] = $errormessage;
}
if ($oldversion < 2020020600) {
// Clean up orphaned popup notification records.
- $DB->delete_records_select('message_popup_notifications', 'notificationid NOT IN (SELECT id FROM {notifications})');
+ $fromsql = "FROM {message_popup_notifications} mpn
+ LEFT JOIN {notifications} n
+ ON mpn.notificationid = n.id
+ WHERE n.id IS NULL";
+ $total = $DB->count_records_sql("SELECT COUNT(mpn.id) " . $fromsql);
+ $i = 0;
+ $pbar = new progress_bar('deletepopupnotification', 500, true);
+ do {
+ if ($popupnotifications = $DB->get_records_sql("SELECT mpn.id " . $fromsql, null, 0, 1000)) {
+ list($insql, $inparams) = $DB->get_in_or_equal(array_keys($popupnotifications));
+ $DB->delete_records_select('message_popup_notifications', "id $insql", $inparams);
+ // Update progress.
+ $i += count($inparams);
+ $pbar->update($i, $total, "Cleaning up orphaned popup notification records - $i/$total.");
+ }
+ } while ($popupnotifications);
// Reportbuilder savepoint reached.
upgrade_plugin_savepoint(true, 2020020600, 'message', 'popup');
$parentposts = [];
if ($parentids) {
$parentposts = $postbuilder->build(
- $user,
+ $USER,
[$forum],
[$discussion],
$postvault->get_from_ids(array_values($parentids))
'timecreated' => $firstpost->get_time_created(),
'authorfullname' => $discussionauthor->get_full_name(),
'posts' => [
- 'userposts' => $postbuilder->build($user, [$forum], [$discussion], $posts),
+ 'userposts' => $postbuilder->build($USER, [$forum], [$discussion], $posts),
'parentposts' => $parentposts,
],
];
* Test get forum posts by user id.
*/
public function test_mod_forum_get_discussion_posts_by_userid() {
+ global $DB;
$this->resetAfterTest(true);
$urlfactory = mod_forum\local\container::get_url_factory();
// Following line enrol and assign default role id to the user.
// So the user automatically gets mod/forum:viewdiscussion on all forums of the course.
- $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
+ $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'teacher');
$this->getDataGenerator()->enrol_user($user2->id, $course1->id);
-
+ // Changed display period for the discussions in past.
+ $time = time();
+ $discussion = new \stdClass();
+ $discussion->id = $discussion1->id;
+ $discussion->timestart = $time - 200;
+ $discussion->timeend = $time - 100;
+ $DB->update_record('forum_discussions', $discussion);
+ $discussion = new \stdClass();
+ $discussion->id = $discussion2->id;
+ $discussion->timestart = $time - 200;
+ $discussion->timeend = $time - 100;
+ $DB->update_record('forum_discussions', $discussion);
// Create what we expect to be returned when querying the discussion.
$expectedposts = array(
'discussions' => array(),
'view' => true,
'edit' => true,
'delete' => true,
- 'split' => false,
+ 'split' => true,
'reply' => true,
'export' => false,
'controlreadstatus' => false,
- 'canreplyprivately' => false,
+ 'canreplyprivately' => true,
'selfenrol' => false
],
'urls' => [
'view' => $urlfactory->get_view_post_url_from_post_id(
- $discussion1reply1->discussion, $discussion1reply1->id)->out(false),
+ $discussion1reply1->discussion, $discussion1reply1->id)->out(false),
'viewisolated' => $isolatedurluser->out(false),
'viewparent' => $urlfactory->get_view_post_url_from_post_id(
- $discussion1reply1->discussion, $discussion1reply1->parent)->out(false),
+ $discussion1reply1->discussion, $discussion1reply1->parent)->out(false),
'edit' => (new moodle_url('/mod/forum/post.php', [
- 'edit' => $discussion1reply1->id
+ 'edit' => $discussion1reply1->id
]))->out(false),
'delete' => (new moodle_url('/mod/forum/post.php', [
- 'delete' => $discussion1reply1->id
+ 'delete' => $discussion1reply1->id
+ ]))->out(false),
+ 'split' => (new moodle_url('/mod/forum/post.php', [
+ 'prune' => $discussion1reply1->id
]))->out(false),
- 'split' => null,
'reply' => (new moodle_url('/mod/forum/post.php#mformforum', [
- 'reply' => $discussion1reply1->id
+ 'reply' => $discussion1reply1->id
]))->out(false),
'export' => null,
'markasread' => null,
'markasunread' => null,
'discuss' => $urlfactory->get_discussion_view_url_from_discussion_id(
- $discussion1reply1->discussion)->out(false),
+ $discussion1reply1->discussion)->out(false),
],
]
],
'charcount' => null,
'capabilities' => [
'view' => true,
- 'edit' => false,
- 'delete' => false,
+ 'edit' => true,
+ 'delete' => true,
'split' => false,
'reply' => true,
'export' => false,
'controlreadstatus' => false,
- 'canreplyprivately' => false,
+ 'canreplyprivately' => true,
'selfenrol' => false
],
'urls' => [
$discussion1firstpostobject->discussion, $discussion1firstpostobject->id)->out(false),
'viewisolated' => $isolatedurlparent->out(false),
'viewparent' => null,
- 'edit' => null,
- 'delete' => null,
+ 'edit' => (new moodle_url('/mod/forum/post.php', [
+ 'edit' => $discussion1firstpostobject->id
+ ]))->out(false),
+ 'delete' => (new moodle_url('/mod/forum/post.php', [
+ 'delete' => $discussion1firstpostobject->id
+ ]))->out(false),
'split' => null,
'reply' => (new moodle_url('/mod/forum/post.php#mformforum', [
'reply' => $discussion1firstpostobject->id
'view' => true,
'edit' => true,
'delete' => true,
- 'split' => false,
+ 'split' => true,
'reply' => true,
'export' => false,
'controlreadstatus' => false,
- 'canreplyprivately' => false,
+ 'canreplyprivately' => true,
'selfenrol' => false
],
'urls' => [
'delete' => (new moodle_url('/mod/forum/post.php', [
'delete' => $discussion2reply1->id
]))->out(false),
- 'split' => null,
+ 'split' => (new moodle_url('/mod/forum/post.php', [
+ 'prune' => $discussion2reply1->id
+ ]))->out(false),
'reply' => (new moodle_url('/mod/forum/post.php#mformforum', [
'reply' => $discussion2reply1->id
]))->out(false),
'charcount' => null,
'capabilities' => [
'view' => true,
- 'edit' => false,
- 'delete' => false,
+ 'edit' => true,
+ 'delete' => true,
'split' => false,
'reply' => true,
'export' => false,
'controlreadstatus' => false,
- 'canreplyprivately' => false,
+ 'canreplyprivately' => true,
'selfenrol' => false
],
'urls' => [
$discussion2firstpostobject->discussion, $discussion2firstpostobject->id)->out(false),
'viewisolated' => $isolatedurlparent->out(false),
'viewparent' => null,
- 'edit' => null,
- 'delete' => null,
+ 'edit' => (new moodle_url('/mod/forum/post.php', [
+ 'edit' => $discussion2firstpostobject->id
+ ]))->out(false),
+ 'delete' => (new moodle_url('/mod/forum/post.php', [
+ 'delete' => $discussion2firstpostobject->id
+ ]))->out(false),
'split' => null,
'reply' => (new moodle_url('/mod/forum/post.php#mformforum', [
'reply' => $discussion2firstpostobject->id
This files describes API changes in /mod/forum/*,
information provided here is intended especially for developers.
+=== 3.10 ===
+
+* Changes in external function mod_forum_external::get_discussion_posts_by_userid
+ Now returns the posts of a given user checking the current user capabilities ($USER, the user who is requesting the posts).
+ Previously, it returned the posts checking the capabilities of the user that created the posts.
+
=== 3.8 ===
* The following functions have been finally deprecated and can not be used anymore:
* @param int $id The glossary ID.
* @return array Contains glossary, context, course and cm.
*/
- protected static function validate_glossary($id) {
+ public static function validate_glossary($id) {
global $DB;
$glossary = $DB->get_record('glossary', array('id' => $id), '*', MUST_EXIST);
list($course, $cm) = get_course_and_cm_from_instance($glossary, 'glossary');
// Get and validate the glossary.
$entry = $DB->get_record('glossary_entries', array('id' => $id), '*', MUST_EXIST);
- list($glossary, $context) = self::validate_glossary($entry->glossaryid);
+ list($glossary, $context, $course, $cm) = self::validate_glossary($entry->glossaryid);
if (empty($entry->approved) && $entry->userid != $USER->id && !has_capability('mod/glossary:approve', $context)) {
throw new invalid_parameter_exception('invalidentry');
$entry = glossary_get_entry_by_id($id);
self::fill_entry_details($entry, $context);
+ // Permissions (for entry edition).
+ $permissions = [
+ 'candelete' => mod_glossary_can_delete_entry($entry, $glossary, $context),
+ 'canupdate' => mod_glossary_can_update_entry($entry, $glossary, $context, $cm),
+ ];
+
return array(
'entry' => $entry,
'ratinginfo' => \core_rating\external\util::get_rating_info($glossary, $context, 'mod_glossary', 'entry',
array($entry)),
+ 'permissions' => $permissions,
'warnings' => $warnings
);
}
return new external_single_structure(array(
'entry' => self::get_entry_return_structure(),
'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
+ 'permissions' => new external_single_structure(
+ [
+ 'candelete' => new external_value(PARAM_BOOL, 'Whether the user can delete the entry.'),
+ 'canupdate' => new external_value(PARAM_BOOL, 'Whether the user can update the entry.'),
+ ],
+ 'User permissions for the managing the entry.', VALUE_OPTIONAL
+ ),
'warnings' => new external_warnings()
));
}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This is the external method for deleting a content.
+ *
+ * @package mod_glossary
+ * @since Moodle 3.10
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace mod_glossary\external;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+require_once($CFG->libdir . '/externallib.php');
+require_once($CFG->dirroot . '/mod/glossary/lib.php');
+
+use external_api;
+use external_function_parameters;
+use external_multiple_structure;
+use external_single_structure;
+use external_value;
+use external_warnings;
+
+/**
+ * This is the external method for deleting a content.
+ *
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class delete_entry extends external_api {
+ /**
+ * Parameters.
+ *
+ * @return external_function_parameters
+ */
+ public static function execute_parameters(): external_function_parameters {
+ return new external_function_parameters([
+ 'entryid' => new external_value(PARAM_INT, 'Glossary entry id to delete'),
+ ]);
+ }
+
+ /**
+ * Delete the indicated entry from the glossary.
+ *
+ * @param int $entryid The entry to delete
+ * @return array with result and warnings
+ * @throws moodle_exception
+ */
+ public static function execute(int $entryid): array {
+ global $DB;
+
+ $params = self::validate_parameters(self::execute_parameters(), compact('entryid'));
+ $id = $params['entryid'];
+
+ // Get and validate the glossary.
+ $entry = $DB->get_record('glossary_entries', ['id' => $id], '*', MUST_EXIST);
+ list($glossary, $context, $course, $cm) = \mod_glossary_external::validate_glossary($entry->glossaryid);
+
+ // Check and delete.
+ mod_glossary_can_delete_entry($entry, $glossary, $context, false);
+ mod_glossary_delete_entry($entry, $glossary, $cm, $context, $course);
+
+ return [
+ 'result' => true,
+ 'warnings' => [],
+ ];
+ }
+
+ /**
+ * Return.
+ *
+ * @return external_single_structure
+ */
+ public static function execute_returns(): external_single_structure {
+ return new external_single_structure([
+ 'result' => new external_value(PARAM_BOOL, 'The processing result'),
+ 'warnings' => new external_warnings()
+ ]);
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This is the external method for preparing a entry for edition.
+ *
+ * @package mod_glossary
+ * @since Moodle 3.10
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace mod_glossary\external;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+require_once($CFG->libdir . '/externallib.php');
+require_once($CFG->dirroot . '/mod/glossary/lib.php');
+
+use external_api;
+use external_function_parameters;
+use external_multiple_structure;
+use external_single_structure;
+use external_value;
+use external_warnings;
+
+/**
+ * This is the external method for preparing a entry for edition.
+ *
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class prepare_entry extends external_api {
+ /**
+ * Parameters.
+ *
+ * @return external_function_parameters
+ */
+ public static function execute_parameters(): external_function_parameters {
+ return new external_function_parameters([
+ 'entryid' => new external_value(PARAM_INT, 'Glossary entry id to update'),
+ ]);
+ }
+
+ /**
+ * Prepare for update the indicated entry from the glossary.
+ *
+ * @param int $entryid The entry to update
+ * @return array with result and warnings
+ * @throws moodle_exception
+ */
+ public static function execute(int $entryid): array {
+ global $DB;
+
+ $params = self::validate_parameters(self::execute_parameters(), compact('entryid'));
+ $id = $params['entryid'];
+
+ // Get and validate the glossary.
+ $entry = $DB->get_record('glossary_entries', ['id' => $id], '*', MUST_EXIST);
+ list($glossary, $context, $course, $cm) = \mod_glossary_external::validate_glossary($entry->glossaryid);
+
+ // Check permissions.
+ mod_glossary_can_update_entry($entry, $glossary, $context, $cm, false);
+
+ list($definitionoptions, $attachmentoptions) = glossary_get_editor_and_attachment_options($course, $context, $entry);
+
+ $entry->aliases = '';
+ $entry->categories = [];
+ $entry = mod_glossary_prepare_entry_for_edition($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);
+
+ // Just get a structure compatible with external API.
+ array_walk($definitionoptions, function(&$item, $key) use (&$definitionoptions) {
+ if (!is_scalar($item)) {
+ unset($definitionoptions[$key]);
+ return;
+ }
+ $item = ['name' => $key, 'value' => $item];
+ });
+
+ array_walk($attachmentoptions, function(&$item, $key) use (&$attachmentoptions) {
+ if (!is_scalar($item)) {
+ unset($attachmentoptions[$key]);
+ return;
+ }
+ $item = ['name' => $key, 'value' => $item];
+ });
+
+ return [
+ 'inlineattachmentsid' => $entry->definition_editor['itemid'],
+ 'attachmentsid' => $entry->attachment_filemanager,
+ 'areas' => [
+ [
+ 'area' => 'definition',
+ 'options' => $definitionoptions,
+ ],
+ [
+ 'area' => 'attachment',
+ 'options' => $attachmentoptions,
+ ],
+ ],
+ 'aliases' => explode("\n", trim($entry->aliases)),
+ 'categories' => $entry->categories,
+ ];
+ }
+
+ /**
+ * Return.
+ *
+ * @return external_single_structure
+ */
+ public static function execute_returns(): external_single_structure {
+ return new external_single_structure([
+ 'inlineattachmentsid' => new external_value(PARAM_INT, 'Draft item id for the text editor.'),
+ 'attachmentsid' => new external_value(PARAM_INT, 'Draft item id for the file manager.'),
+ 'areas' => new external_multiple_structure(
+ new external_single_structure(
+ [
+ 'area' => new external_value(PARAM_ALPHA, 'File area name.'),
+ 'options' => new external_multiple_structure(
+ new external_single_structure(
+ [
+ 'name' => new external_value(PARAM_RAW, 'Name of option.'),
+ 'value' => new external_value(PARAM_RAW, 'Value of option.'),
+ ]
+ ), 'Draft file area options.'
+ )
+ ]
+ ), 'File areas including options'
+ ),
+ 'aliases' => new external_multiple_structure(new external_value(PARAM_RAW, 'Alias name.')),
+ 'categories' => new external_multiple_structure(new external_value(PARAM_INT, 'Category id')),
+ 'warnings' => new external_warnings(),
+ ]);
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This is the external method for updating a glossary entry.
+ *
+ * @package mod_glossary
+ * @since Moodle 3.10
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace mod_glossary\external;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+require_once($CFG->libdir . '/externallib.php');
+require_once($CFG->dirroot . '/mod/glossary/lib.php');
+
+use external_api;
+use external_function_parameters;
+use external_multiple_structure;
+use external_single_structure;
+use external_value;
+use external_format_value;
+use external_warnings;
+use core_text;
+use moodle_exception;
+
+/**
+ * This is the external method for updating a glossary entry.
+ *
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class update_entry extends external_api {
+ /**
+ * Parameters.
+ *
+ * @return external_function_parameters
+ */
+ public static function execute_parameters(): external_function_parameters {
+ return new external_function_parameters([
+ 'entryid' => new external_value(PARAM_INT, 'Glossary entry id to update'),
+ 'concept' => new external_value(PARAM_TEXT, 'Glossary concept'),
+ 'definition' => new external_value(PARAM_RAW, 'Glossary concept definition'),
+ 'definitionformat' => new external_format_value('definition'),
+ 'options' => new external_multiple_structure (
+ new external_single_structure(
+ [
+ '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, []
+ )
+ ]);
+ }
+
+ /**
+ * Update the indicated glossary entry.
+ *
+ * @param int $entryid The entry to update
+ * @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 with result and warnings
+ * @throws moodle_exception
+ */
+ public static function execute(int $entryid, string $concept, string $definition, int $definitionformat,
+ array $options = []): array {
+
+ global $DB;
+
+ $params = self::validate_parameters(self::execute_parameters(), compact('entryid', 'concept', 'definition',
+ 'definitionformat', 'options'));
+ $id = $params['entryid'];
+
+ // Get and validate the glossary entry.
+ $entry = $DB->get_record('glossary_entries', ['id' => $id], '*', MUST_EXIST);
+ list($glossary, $context, $course, $cm) = \mod_glossary_external::validate_glossary($entry->glossaryid);
+
+ // Check if the user can update the entry.
+ mod_glossary_can_update_entry($entry, $glossary, $context, $cm, false);
+
+ // Check for duplicates if the concept changes.
+ if (!$glossary->allowduplicatedentries &&
+ core_text::strtolower($entry->concept) != core_text::strtolower(trim($params['concept']))) {
+
+ if (glossary_concept_exists($glossary, $params['concept'])) {
+ throw new moodle_exception('errconceptalreadyexists', 'glossary');
+ }
+ }
+
+ // Prepare the entry object.
+ $entry->aliases = '';
+ $entry = mod_glossary_prepare_entry_for_edition($entry);
+ $entry->concept = $params['concept'];
+ $entry->definition_editor = [
+ '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 [
+ 'result' => true,
+ 'warnings' => [],
+ ];
+ }
+
+ /**
+ * Return.
+ *
+ * @return external_single_structure
+ */
+ public static function execute_returns(): external_single_structure {
+ return new external_single_structure([
+ 'result' => new external_value(PARAM_BOOL, 'The update result'),
+ 'warnings' => new external_warnings()
+ ]);
+ }
+}
'services' => array(MOODLE_OFFICIAL_MOBILE_SERVICE)
),
+ 'mod_glossary_delete_entry' => [
+ 'classname' => 'mod_glossary\external\delete_entry',
+ 'methodname' => 'execute',
+ 'classpath' => '',
+ 'description' => 'Delete the given entry from the glossary.',
+ 'type' => 'write',
+ 'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE]
+ ],
+
+ 'mod_glossary_update_entry' => [
+ 'classname' => 'mod_glossary\external\update_entry',
+ 'methodname' => 'execute',
+ 'classpath' => '',
+ 'description' => 'Updates the given glossary entry.',
+ 'type' => 'write',
+ 'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE]
+ ],
+
+ 'mod_glossary_prepare_entry_for_edition' => [
+ 'classname' => 'mod_glossary\external\prepare_entry',
+ 'methodname' => 'execute',
+ 'classpath' => '',
+ 'description' => 'Prepares the given entry for edition returning draft item areas and file areas information.',
+ 'type' => 'read',
+ 'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE]
+ ],
);
require_login($course, false, $cm);
$context = context_module::instance($cm->id);
-$manageentries = has_capability('mod/glossary:manageentries', $context);
if (! $glossary = $DB->get_record("glossary", array("id"=>$cm->instance))) {
print_error('invalidid', 'glossary');
}
-
-$strareyousuredelete = get_string("areyousuredelete","glossary");
-
-if (($entry->userid != $USER->id) and !$manageentries) { // guest id is never matched, no need for special check here
- print_error('nopermissiontodelentry');
-}
-$ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
-if (!$ineditperiod and !$manageentries) {
- print_error('errdeltimeexpired', 'glossary');
-}
+// Throws an exception if the user cannot delete the entry.
+mod_glossary_can_delete_entry($entry, $glossary, $context, false);
/// If data submitted, then process and store.
if ($confirm and confirm_sesskey()) { // the operation was confirmed.
- // if it is an imported entry, just delete the relation
-
- $origentry = fullclone($entry);
- if ($entry->sourceglossaryid) {
- if (!$newcm = get_coursemodule_from_instance('glossary', $entry->sourceglossaryid)) {
- print_error('invalidcoursemodule');
- }
- $newcontext = context_module::instance($newcm->id);
-
- $entry->glossaryid = $entry->sourceglossaryid;
- $entry->sourceglossaryid = 0;
- $DB->update_record('glossary_entries', $entry);
-
- // move attachments too
- $fs = get_file_storage();
-
- if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) {
- foreach ($oldfiles as $oldfile) {
- $file_record = new stdClass();
- $file_record->contextid = $newcontext->id;
- $fs->create_file_from_storedfile($file_record, $oldfile);
- }
- $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
- $entry->attachment = '1';
- } else {
- $entry->attachment = '0';
- }
- $DB->update_record('glossary_entries', $entry);
-
- } else {
- $fs = get_file_storage();
- $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
- $DB->delete_records("comments", array('itemid'=>$entry->id, 'commentarea'=>'glossary_entry', 'contextid'=>$context->id));
- $DB->delete_records("glossary_alias", array("entryid"=>$entry->id));
- $DB->delete_records("glossary_entries", array("id"=>$entry->id));
-
- // Update completion state
- $completion = new completion_info($course);
- if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $glossary->completionentries) {
- $completion->update_state($cm, COMPLETION_INCOMPLETE, $entry->userid);
- }
-
- //delete glossary entry ratings
- require_once($CFG->dirroot.'/rating/lib.php');
- $delopt = new stdClass;
- $delopt->contextid = $context->id;
- $delopt->component = 'mod_glossary';
- $delopt->ratingarea = 'entry';
- $delopt->itemid = $entry->id;
- $rm = new rating_manager();
- $rm->delete_ratings($delopt);
- }
-
- // Delete cached RSS feeds.
- if (!empty($CFG->enablerssfeeds)) {
- require_once($CFG->dirroot.'/mod/glossary/rsslib.php');
- glossary_rss_delete_file($glossary);
- }
-
- core_tag_tag::remove_all_item_tags('mod_glossary', 'glossary_entries', $origentry->id);
-
- $event = \mod_glossary\event\entry_deleted::create(array(
- 'context' => $context,
- 'objectid' => $origentry->id,
- 'other' => array(
- 'mode' => $prevmode,
- 'hook' => $hook,
- 'concept' => $origentry->concept
- )
- ));
- $event->add_record_snapshot('glossary_entries', $origentry);
- $event->trigger();
-
- // Reset caches.
- if ($entry->usedynalink and $entry->approved) {
- \mod_glossary\local\concept_cache::reset_glossary($glossary);
- }
+ mod_glossary_delete_entry($entry, $glossary, $cm, $context, $course, $hook, $prevmode);
redirect("view.php?id=$cm->id&mode=$prevmode&hook=$hook");
} else { // the operation has not been confirmed yet so ask the user to do so
+ $strareyousuredelete = get_string("areyousuredelete", "glossary");
$PAGE->navbar->add(get_string('delete'));
$PAGE->set_title($glossary->name);
$PAGE->set_heading($course->fullname);
print_error('invalidentry');
}
- $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
- if (!has_capability('mod/glossary:manageentries', $context) and !($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context)))) {
- if ($USER->id != $entry->userid) {
- print_error('errcannoteditothers', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$id");
- } elseif (!$ineditperiod) {
- print_error('erredittimeexpired', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$id");
- }
- }
-
- //prepare extra data
- if ($aliases = $DB->get_records_menu("glossary_alias", array("entryid"=>$id), '', 'id, alias')) {
- $entry->aliases = implode("\n", $aliases) . "\n";
- }
- if ($categoriesarr = $DB->get_records_menu("glossary_entries_categories", array('entryid'=>$id), '', 'id, categoryid')) {
- // TODO: this fetches cats from both main and secondary glossary :-(
- $entry->categories = array_values($categoriesarr);
- }
+ // Check if the user can update the entry (trigger exception if he can't).
+ mod_glossary_can_update_entry($entry, $glossary, $context, $cm, false);
+ // Prepare extra data.
+ $entry = mod_glossary_prepare_entry_for_edition($entry);
} else { // new entry
require_capability('mod/glossary:write', $context);
}
return $descriptions;
}
+
+/**
+ * Checks if the current user can delete the given glossary entry.
+ *
+ * @since Moodle 3.10
+ * @param stdClass $entry the entry database object
+ * @param stdClass $glossary the glossary database object
+ * @param stdClass $context the glossary context
+ * @param bool $return Whether to return a boolean value or stop the execution (exception)
+ * @return bool if the user can delete the entry
+ * @throws moodle_exception
+ */
+function mod_glossary_can_delete_entry($entry, $glossary, $context, $return = true) {
+ global $USER, $CFG;
+
+ $manageentries = has_capability('mod/glossary:manageentries', $context);
+
+ if ($manageentries) { // Users with the capability will always be able to delete entries.
+ return true;
+ }
+
+ if ($entry->userid != $USER->id) { // Guest id is never matched, no need for special check here.
+ if ($return) {
+ return false;
+ }
+ throw new moodle_exception('nopermissiontodelentry');
+ }
+
+ $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
+
+ if (!$ineditperiod) {
+ if ($return) {
+ return false;
+ }
+ throw new moodle_exception('errdeltimeexpired', 'glossary');
+ }
+
+ return true;
+}
+
+/**
+ * Deletes the given entry, this function does not perform capabilities/permission checks.
+ *
+ * @since Moodle 3.10
+ * @param stdClass $entry the entry database object
+ * @param stdClass $glossary the glossary database object
+ * @param stdClass $cm the glossary course moduule object
+ * @param stdClass $context the glossary context
+ * @param stdClass $course the glossary course
+ * @param string $hook the hook, usually type of filtering, value
+ * @param string $prevmode the previsualisation mode
+ * @throws moodle_exception
+ */
+function mod_glossary_delete_entry($entry, $glossary, $cm, $context, $course, $hook = '', $prevmode = '') {
+ global $CFG, $DB;
+
+ $origentry = fullclone($entry);
+
+ // If it is an imported entry, just delete the relation.
+ if ($entry->sourceglossaryid) {
+ if (!$newcm = get_coursemodule_from_instance('glossary', $entry->sourceglossaryid)) {
+ print_error('invalidcoursemodule');
+ }
+ $newcontext = context_module::instance($newcm->id);
+
+ $entry->glossaryid = $entry->sourceglossaryid;
+ $entry->sourceglossaryid = 0;
+ $DB->update_record('glossary_entries', $entry);
+
+ // Move attachments too.
+ $fs = get_file_storage();
+
+ if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) {
+ foreach ($oldfiles as $oldfile) {
+ $filerecord = new stdClass();
+ $filerecord->contextid = $newcontext->id;
+ $fs->create_file_from_storedfile($filerecord, $oldfile);
+ }
+ $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
+ $entry->attachment = '1';
+ } else {
+ $entry->attachment = '0';
+ }
+ $DB->update_record('glossary_entries', $entry);
+
+ } else {
+ $fs = get_file_storage();
+ $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id);
+ $DB->delete_records("comments",
+ ['itemid' => $entry->id, 'commentarea' => 'glossary_entry', 'contextid' => $context->id]);
+ $DB->delete_records("glossary_alias", ["entryid" => $entry->id]);
+ $DB->delete_records("glossary_entries", ["id" => $entry->id]);
+
+ // Update completion state.
+ $completion = new completion_info($course);
+ if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $glossary->completionentries) {
+ $completion->update_state($cm, COMPLETION_INCOMPLETE, $entry->userid);
+ }
+
+ // Delete glossary entry ratings.
+ require_once($CFG->dirroot.'/rating/lib.php');
+ $delopt = new stdClass;
+ $delopt->contextid = $context->id;
+ $delopt->component = 'mod_glossary';
+ $delopt->ratingarea = 'entry';
+ $delopt->itemid = $entry->id;
+ $rm = new rating_manager();
+ $rm->delete_ratings($delopt);
+ }
+
+ // Delete cached RSS feeds.
+ if (!empty($CFG->enablerssfeeds)) {
+ require_once($CFG->dirroot . '/mod/glossary/rsslib.php');
+ glossary_rss_delete_file($glossary);
+ }
+
+ core_tag_tag::remove_all_item_tags('mod_glossary', 'glossary_entries', $origentry->id);
+
+ $event = \mod_glossary\event\entry_deleted::create(
+ [
+ 'context' => $context,
+ 'objectid' => $origentry->id,
+ 'other' => [
+ 'mode' => $prevmode,
+ 'hook' => $hook,
+ 'concept' => $origentry->concept
+ ]
+ ]
+ );
+ $event->add_record_snapshot('glossary_entries', $origentry);
+ $event->trigger();
+
+ // Reset caches.
+ if ($entry->usedynalink and $entry->approved) {
+ \mod_glossary\local\concept_cache::reset_glossary($glossary);
+ }
+}
+
+/**
+ * Checks if the current user can update the given glossary entry.
+ *
+ * @since Moodle 3.10
+ * @param stdClass $entry the entry database object
+ * @param stdClass $glossary the glossary database object
+ * @param stdClass $context the glossary context
+ * @param object $cm the course module object (cm record or cm_info instance)
+ * @param bool $return Whether to return a boolean value or stop the execution (exception)
+ * @return bool if the user can update the entry
+ * @throws moodle_exception
+ */
+function mod_glossary_can_update_entry(stdClass $entry, stdClass $glossary, stdClass $context, object $cm,
+ bool $return = true): bool {
+
+ global $USER, $CFG;
+
+ $ineditperiod = ((time() - $entry->timecreated < $CFG->maxeditingtime) || $glossary->editalways);
+ if (!has_capability('mod/glossary:manageentries', $context) and
+ !($entry->userid == $USER->id and ($ineditperiod and has_capability('mod/glossary:write', $context)))) {
+
+ if ($USER->id != $entry->userid) {
+ if ($return) {
+ return false;
+ }
+ throw new moodle_exception('errcannoteditothers', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$entry->id");
+ } else if (!$ineditperiod) {
+ if ($return) {
+ return false;
+ }
+ throw new moodle_exception('erredittimeexpired', 'glossary', "view.php?id=$cm->id&mode=entry&hook=$entry->id");
+ }
+ }
+
+ return true;
+}
+
+/**
+ * Prepares an entry for editing, adding aliases and category information.
+ *
+ * @param stdClass $entry the entry being edited
+ * @return stdClass the entry with the additional data
+ */
+function mod_glossary_prepare_entry_for_edition(stdClass $entry): stdClass {
+ global $DB;
+
+ if ($aliases = $DB->get_records_menu("glossary_alias", ["entryid" => $entry->id], '', 'id, alias')) {
+ $entry->aliases = implode("\n", $aliases) . "\n";
+ }
+ if ($categoriesarr = $DB->get_records_menu("glossary_entries_categories", ['entryid' => $entry->id], '', 'id, categoryid')) {
+ // TODO: this fetches cats from both main and secondary glossary :-(
+ $entry->categories = array_values($categoriesarr);
+ }
+
+ return $entry;
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * External function test for delete_entry.
+ *
+ * @package mod_glossary
+ * @category external
+ * @since Moodle 3.10
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace mod_glossary\external;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+require_once($CFG->dirroot . '/webservice/tests/helpers.php');
+
+use external_api;
+use externallib_advanced_testcase;
+
+/**
+ * External function test for delete_entry.
+ *
+ * @package mod_glossary
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class delete_entry_testcase extends externallib_advanced_testcase {
+
+ /**
+ * Test the behaviour of delete_entry().
+ */
+ public function test_delete_entry() {
+ global $DB;
+ $this->resetAfterTest();
+
+ // Create required data.
+ $course = $this->getDataGenerator()->create_course();
+ $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $anotherstudent = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+
+ $this->setUser($student);
+ $entry = $gg->create_content($glossary);
+
+ // Test entry creator can delete.
+ $result = delete_entry::execute($entry->id);
+ $result = external_api::clean_returnvalue(delete_entry::execute_returns(), $result);
+ $this->assertTrue($result['result']);
+ $this->assertEquals(0, $DB->count_records('glossary_entries', ['id' => $entry->id]));
+
+ // Test admin can delete.
+ $this->setAdminUser();
+ $entry = $gg->create_content($glossary);
+ $result = delete_entry::execute($entry->id);
+ $result = external_api::clean_returnvalue(delete_entry::execute_returns(), $result);
+ $this->assertTrue($result['result']);
+ $this->assertEquals(0, $DB->count_records('glossary_entries', ['id' => $entry->id]));
+
+ $entry = $gg->create_content($glossary);
+ // Test a different student is not able to delete.
+ $this->setUser($anotherstudent);
+ $this->expectExceptionMessage(get_string('nopermissiontodelentry', 'error'));
+ delete_entry::execute($entry->id);
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * External function test for prepare_entry.
+ *
+ * @package mod_glossary
+ * @category external
+ * @since Moodle 3.10
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace mod_glossary\external;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+require_once($CFG->dirroot . '/webservice/tests/helpers.php');
+
+use external_api;
+use externallib_advanced_testcase;
+use mod_glossary_external;
+use context_module;
+use context_user;
+use external_util;
+
+/**
+ * External function test for prepare_entry.
+ *
+ * @package mod_glossary
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class prepare_entry_testcase extends externallib_advanced_testcase {
+
+ /**
+ * test_prepare_entry
+ */
+ public function test_prepare_entry() {
+ global $USER;
+ $this->resetAfterTest(true);
+
+ $course = $this->getDataGenerator()->create_course();
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+
+ $this->setAdminUser();
+ $aliases = ['alias1', 'alias2'];
+ $entry = $gg->create_content(
+ $glossary,
+ ['approved' => 1, 'userid' => $USER->id],
+ $aliases
+ );
+
+ $cat1 = $gg->create_category($glossary, [], [$entry]);
+ $gg->create_category($glossary);
+
+ $return = prepare_entry::execute($entry->id);
+ $return = external_api::clean_returnvalue(prepare_entry::execute_returns(), $return);
+
+ $this->assertNotEmpty($return['inlineattachmentsid']);
+ $this->assertNotEmpty($return['attachmentsid']);
+ $this->assertEquals($aliases, $return['aliases']);
+ $this->assertEquals([$cat1->id], $return['categories']);
+ $this->assertCount(2, $return['areas']);
+ $this->assertNotEmpty($return['areas'][0]['options']);
+ $this->assertNotEmpty($return['areas'][1]['options']);
+ }
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * External function test for update_entry.
+ *
+ * @package mod_glossary
+ * @category external
+ * @since Moodle 3.10
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace mod_glossary\external;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+require_once($CFG->dirroot . '/webservice/tests/helpers.php');
+
+use external_api;
+use externallib_advanced_testcase;
+use mod_glossary_external;
+use context_module;
+use context_user;
+use external_util;
+
+/**
+ * External function test for update_entry.
+ *
+ * @package mod_glossary
+ * @copyright 2020 Juan Leyva <juan@moodle.com>
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class update_entry_testcase extends externallib_advanced_testcase {
+
+ /**
+ * test_update_entry_without_optional_settings
+ */
+ public function test_update_entry_without_optional_settings() {
+ global $CFG, $DB;
+ $this->resetAfterTest(true);
+
+ $course = $this->getDataGenerator()->create_course();
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+
+ $this->setAdminUser();
+ $concept = 'A concept';
+ $definition = '<p>A definition</p>';
+ $return = mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML);
+ $return = external_api::clean_returnvalue(mod_glossary_external::add_entry_returns(), $return);
+ $entryid = $return['entryid'];
+
+ // Updates the entry.
+ $concept .= ' Updated!';
+ $definition .= ' <p>Updated!</p>';
+ $return = update_entry::execute($entryid, $concept, $definition, FORMAT_HTML);
+ $return = external_api::clean_returnvalue(update_entry::execute_returns(), $return);
+
+ // Get entry from DB.
+ $entry = $DB->get_record('glossary_entries', ['id' => $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', ['entryid' => $entryid]));
+ $this->assertEmpty($DB->get_records('glossary_entries_categories', ['entryid' => $entryid]));
+ }
+
+ /**
+ * test_update_entry_duplicated
+ */
+ public function test_update_entry_duplicated() {
+ global $CFG, $DB;
+ $this->resetAfterTest(true);
+
+ $course = $this->getDataGenerator()->create_course();
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id, 'allowduplicatedentries' => 1]);
+
+ // Create three entries.
+ $this->setAdminUser();
+ $concept = 'A concept';
+ $definition = '<p>A definition</p>';
+ mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML);
+
+ $concept = 'B concept';
+ $definition = '<p>B definition</p>';
+ mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML);
+
+ $concept = 'Another concept';
+ $definition = '<p>Another definition</p>';
+ $return = mod_glossary_external::add_entry($glossary->id, $concept, $definition, FORMAT_HTML);
+ $return = external_api::clean_returnvalue(mod_glossary_external::add_entry_returns(), $return);
+ $entryid = $return['entryid'];
+
+ // Updates the entry using an existing entry name when duplicateds are allowed.
+ $concept = 'A concept';
+ update_entry::execute($entryid, $concept, $definition, FORMAT_HTML);
+
+ // Updates the entry using an existing entry name when duplicateds are NOT allowed.
+ $DB->set_field('glossary', 'allowduplicatedentries', 0, ['id' => $glossary->id]);
+ $concept = 'B concept';
+ $this->expectExceptionMessage(get_string('errconceptalreadyexists', 'glossary'));
+ update_entry::execute($entryid, $concept, $definition, FORMAT_HTML);
+ }
+
+ /**
+ * test_update_entry_with_aliases
+ */
+ public function test_update_entry_with_aliases() {
+ global $DB;
+ $this->resetAfterTest(true);
+
+ $course = $this->getDataGenerator()->create_course();
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+
+ $this->setAdminUser();
+ $concept = 'A concept';
+ $definition = 'A definition';
+ $paramaliases = 'abc, def, gez';
+ $options = [
+ [
+ '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);
+ $entryid = $return['entryid'];
+
+ // Updates the entry.
+ $newaliases = 'abz, xyz';
+ $options[0]['value'] = $newaliases;
+ $return = update_entry::execute($entryid, $concept, $definition, FORMAT_HTML, $options);
+ $return = external_api::clean_returnvalue(update_entry::execute_returns(), $return);
+
+ $aliases = $DB->get_records('glossary_alias', ['entryid' => $entryid]);
+ $this->assertCount(2, $aliases);
+ foreach ($aliases as $alias) {
+ $this->assertContains($alias->alias, $newaliases);
+ }
+ }
+
+ /**
+ * test_update_entry_in_categories
+ */
+ public function test_update_entry_in_categories() {
+ global $DB;
+ $this->resetAfterTest(true);
+
+ $course = $this->getDataGenerator()->create_course();
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+ $cat1 = $gg->create_category($glossary);
+ $cat2 = $gg->create_category($glossary);
+ $cat3 = $gg->create_category($glossary);
+
+ $this->setAdminUser();
+ $concept = 'A concept';
+ $definition = 'A definition';
+ $paramcategories = "$cat1->id, $cat2->id";
+ $options = [
+ [
+ '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);
+ $entryid = $return['entryid'];
+
+ // Updates the entry.
+ $newcategories = "$cat1->id, $cat3->id";
+ $options[0]['value'] = $newcategories;
+ $return = update_entry::execute($entryid, $concept, $definition, FORMAT_HTML, $options);
+ $return = external_api::clean_returnvalue(update_entry::execute_returns(), $return);
+
+ $categories = $DB->get_records('glossary_entries_categories', ['entryid' => $entryid]);
+ $this->assertCount(2, $categories);
+ foreach ($categories as $category) {
+ $this->assertContains($category->categoryid, $newcategories);
+ }
+ }
+
+ /**
+ * test_update_entry_with_attachments
+ */
+ public function test_update_entry_with_attachments() {
+ global $DB, $USER;
+ $this->resetAfterTest(true);
+
+ $course = $this->getDataGenerator()->create_course();
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['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 = [
+ 'contextid' => $usercontext->id,
+ 'component' => 'user',
+ 'filearea' => 'draft',
+ 'itemid' => $draftidinlineattach,
+ 'filepath' => '/',
+ 'filename' => 'shouldbeanimage.png',
+ ];
+ $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 = [
+ [
+ 'name' => 'inlineattachmentsid',
+ 'value' => $draftidinlineattach,
+ ],
+ [
+ '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);
+ $entryid = $return['entryid'];
+ $entry = $DB->get_record('glossary_entries', ['id' => $entryid]);
+
+ 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);
+
+ $inlineattachmentsid = $entry->definition_editor['itemid'];
+ $attachmentsid = $entry->attachment_filemanager;
+
+ // Change the file areas.
+
+ // Delete one inline editor file.
+ $selectedfile = (object)[
+ 'filename' => $filerecordinline['filename'],
+ 'filepath' => $filerecordinline['filepath'],
+ ];
+ $return = repository_delete_selected_files($usercontext, 'user', 'draft', $inlineattachmentsid, [$selectedfile]);
+
+ // Add more files.
+ $filerecordinline['filename'] = 'newvideo.mp4';
+ $filerecordinline['itemid'] = $inlineattachmentsid;
+
+ $filerecordattach['filename'] = 'newattach.txt';
+ $filerecordattach['itemid'] = $attachmentsid;
+
+ $fs->create_file_from_string($filerecordinline, 'image contents (not really)');
+ $fs->create_file_from_string($filerecordattach, 'simple text attachment');
+
+ // Updates the entry.
+ $options[0]['value'] = $inlineattachmentsid;
+ $options[1]['value'] = $attachmentsid;
+ $return = update_entry::execute($entryid, $concept, $definition, FORMAT_HTML, $options);
+ $return = external_api::clean_returnvalue(update_entry::execute_returns(), $return);
+
+ $editorfiles = external_util::get_area_files($context->id, 'mod_glossary', 'entry', $entryid);
+ $attachmentfiles = external_util::get_area_files($context->id, 'mod_glossary', 'attachment', $entryid);
+
+ $this->assertCount(1, $editorfiles);
+ $this->assertCount(2, $attachmentfiles);
+
+ $this->assertEquals('newvideo.mp4', $editorfiles[0]['filename']);
+ $this->assertEquals('attachment.txt', $attachmentfiles[0]['filename']);
+ $this->assertEquals('newattach.txt', $attachmentfiles[1]['filename']);
+ }
+}
$c1 = $this->getDataGenerator()->create_course();
$c2 = $this->getDataGenerator()->create_course();
$g1 = $this->getDataGenerator()->create_module('glossary', array('course' => $c1->id));
- $g2 = $this->getDataGenerator()->create_module('glossary', array('course' => $c1->id, 'visible' => 0));
+ $g2 = $this->getDataGenerator()->create_module('glossary', array('course' => $c2->id, 'visible' => 0));
$u1 = $this->getDataGenerator()->create_user();
$u2 = $this->getDataGenerator()->create_user();
+ $u3 = $this->getDataGenerator()->create_user();
$ctx = context_module::instance($g1->cmid);
$this->getDataGenerator()->enrol_user($u1->id, $c1->id);
+ $this->getDataGenerator()->enrol_user($u2->id, $c1->id);
+ $this->getDataGenerator()->enrol_user($u3->id, $c1->id);
$e1 = $gg->create_content($g1, array('approved' => 1, 'userid' => $u1->id, 'tags' => array('Cats', 'Dogs')));
// Add a fake inline image to the entry.
$this->assertEquals('Cats', $return['entry']['tags'][0]['rawname']);
$this->assertEquals('Dogs', $return['entry']['tags'][1]['rawname']);
$this->assertEquals($filename, $return['entry']['definitioninlinefiles'][0]['filename']);
+ $this->assertTrue($return['permissions']['candelete']);
$return = mod_glossary_external::get_entry_by_id($e2->id);
$return = external_api::clean_returnvalue(mod_glossary_external::get_entry_by_id_returns(), $return);
$this->assertEquals($e2->id, $return['entry']['id']);
+ $this->assertTrue($return['permissions']['candelete']);
try {
$return = mod_glossary_external::get_entry_by_id($e3->id);
// All good.
}
- // An admin can be other's entries to be approved.
+ // An admin can see other's entries to be approved.
$this->setAdminUser();
$return = mod_glossary_external::get_entry_by_id($e3->id);
$return = external_api::clean_returnvalue(mod_glossary_external::get_entry_by_id_returns(), $return);
$this->assertEquals($e3->id, $return['entry']['id']);
+ $this->assertTrue($return['permissions']['candelete']);
+
+ // Students can see other students approved entries but they will not be able to delete them.
+ $this->setUser($u3);
+ $return = mod_glossary_external::get_entry_by_id($e1->id);
+ $return = external_api::clean_returnvalue(mod_glossary_external::get_entry_by_id_returns(), $return);
+ $this->assertEquals($e1->id, $return['entry']['id']);
+ $this->assertFalse($return['permissions']['candelete']);
}
public function test_add_entry_without_optional_settings() {
$search = glossary_get_entries_search($concept, $course->id);
$this->assertCount(0, $search);
}
+
+ public function test_mod_glossary_can_delete_entry_users() {
+ $this->resetAfterTest();
+
+ // Create required data.
+ $course = $this->getDataGenerator()->create_course();
+ $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $anotherstudent = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $teacher = $this->getDataGenerator()->create_and_enrol($course, 'editingteacher');
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+ $this->setUser($student);
+ $entry = $gg->create_content($glossary);
+ $context = context_module::instance($glossary->cmid);
+
+ // Test student can delete.
+ $this->assertTrue(mod_glossary_can_delete_entry($entry, $glossary, $context));
+
+ // Test teacher can delete.
+ $this->setUser($teacher);
+ $this->assertTrue(mod_glossary_can_delete_entry($entry, $glossary, $context));
+
+ // Test admin can delete.
+ $this->setAdminUser();
+ $this->assertTrue(mod_glossary_can_delete_entry($entry, $glossary, $context));
+
+ // Test a different student is not able to delete.
+ $this->setUser($anotherstudent);
+ $this->assertFalse(mod_glossary_can_delete_entry($entry, $glossary, $context));
+
+ // Test exception.
+ $this->expectExceptionMessage(get_string('nopermissiontodelentry', 'error'));
+ mod_glossary_can_delete_entry($entry, $glossary, $context, false);
+ }
+
+ public function test_mod_glossary_can_delete_entry_edit_period() {
+ global $CFG;
+ $this->resetAfterTest();
+
+ // Create required data.
+ $course = $this->getDataGenerator()->create_course();
+ $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id, 'editalways' => 1]);
+
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+ $this->setUser($student);
+ $entry = $gg->create_content($glossary);
+ $context = context_module::instance($glossary->cmid);
+
+ // Test student can always delete when edit always is set to 1.
+ $entry->timecreated = time() - 2 * $CFG->maxeditingtime;
+ $this->assertTrue(mod_glossary_can_delete_entry($entry, $glossary, $context));
+
+ // Test student cannot delete old entries when edit always is set to 0.
+ $glossary->editalways = 0;
+ $this->assertFalse(mod_glossary_can_delete_entry($entry, $glossary, $context));
+
+ // Test student can delete recent entries when edit always is set to 0.
+ $entry->timecreated = time();
+ $this->assertTrue(mod_glossary_can_delete_entry($entry, $glossary, $context));
+
+ // Check exception.
+ $entry->timecreated = time() - 2 * $CFG->maxeditingtime;
+ $this->expectExceptionMessage(get_string('errdeltimeexpired', 'glossary'));
+ mod_glossary_can_delete_entry($entry, $glossary, $context, false);
+ }
+
+ public function test_mod_glossary_delete_entry() {
+ global $DB, $CFG;
+ $this->resetAfterTest();
+ require_once($CFG->dirroot . '/rating/lib.php');
+
+ // Create required data.
+ $course = $this->getDataGenerator()->create_course();
+ $student1 = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $student2 = $this->getDataGenerator()->create_and_enrol($course, 'student');
+
+ $record = new stdClass();
+ $record->course = $course->id;
+ $record->assessed = RATING_AGGREGATE_AVERAGE;
+ $scale = $this->getDataGenerator()->create_scale(['scale' => 'A,B,C,D']);
+ $record->scale = "-$scale->id";
+ $glossary = $this->getDataGenerator()->create_module('glossary', $record);
+ $context = context_module::instance($glossary->cmid);
+ $cm = get_coursemodule_from_instance('glossary', $glossary->id);
+
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+ $this->setUser($student1);
+
+ // Create entry with tags and rating.
+ $entry = $gg->create_content(
+ $glossary,
+ ['approved' => 1, 'userid' => $student1->id, 'tags' => ['Cats', 'Dogs']],
+ ['alias1', 'alias2']
+ );
+
+ // Rate the entry as user2.
+ $rating1 = new stdClass();
+ $rating1->contextid = $context->id;
+ $rating1->component = 'mod_glossary';
+ $rating1->ratingarea = 'entry';
+ $rating1->itemid = $entry->id;
+ $rating1->rating = 1; // 1 is A.
+ $rating1->scaleid = "-$scale->id";
+ $rating1->userid = $student2->id;
+ $rating1->timecreated = time();
+ $rating1->timemodified = time();
+ $rating1->id = $DB->insert_record('rating', $rating1);
+
+ $sink = $this->redirectEvents();
+ mod_glossary_delete_entry(fullclone($entry), $glossary, $cm, $context, $course);
+ $events = $sink->get_events();
+ $event = array_pop($events);
+
+ // Check events.
+ $this->assertEquals('\mod_glossary\event\entry_deleted', $event->eventname);
+ $this->assertEquals($entry->id, $event->objectid);
+ $sink->close();
+
+ // No entry, no alias, no ratings, no tags.
+ $this->assertEquals(0, $DB->count_records('glossary_entries', ['id' => $entry->id]));
+ $this->assertEquals(0, $DB->count_records('glossary_alias', ['entryid' => $entry->id]));
+ $this->assertEquals(0, $DB->count_records('rating', ['component' => 'mod_glossary', 'itemid' => $entry->id]));
+ $this->assertEmpty(core_tag_tag::get_by_name(0, 'Cats'));
+ }
+
+ public function test_mod_glossary_delete_entry_imported() {
+ global $DB;
+ $this->resetAfterTest();
+
+ // Create required data.
+ $course = $this->getDataGenerator()->create_course();
+ $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+
+ $glossary1 = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+ $glossary2 = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+
+ $context = context_module::instance($glossary2->cmid);
+ $cm = get_coursemodule_from_instance('glossary', $glossary2->id);
+
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+ $this->setUser($student);
+
+ $entry1 = $gg->create_content($glossary1);
+ $entry2 = $gg->create_content(
+ $glossary2,
+ ['approved' => 1, 'userid' => $student->id, 'sourceglossaryid' => $glossary1->id, 'tags' => ['Cats', 'Dogs']]
+ );
+
+ $sink = $this->redirectEvents();
+ mod_glossary_delete_entry(fullclone($entry2), $glossary2, $cm, $context, $course);
+ $events = $sink->get_events();
+ $event = array_pop($events);
+
+ // Check events.
+ $this->assertEquals('\mod_glossary\event\entry_deleted', $event->eventname);
+ $this->assertEquals($entry2->id, $event->objectid);
+ $sink->close();
+
+ // Check source.
+ $this->assertEquals(0, $DB->get_field('glossary_entries', 'sourceglossaryid', ['id' => $entry2->id]));
+ $this->assertEquals($glossary1->id, $DB->get_field('glossary_entries', 'glossaryid', ['id' => $entry2->id]));
+
+ // Tags.
+ $this->assertEmpty(core_tag_tag::get_by_name(0, 'Cats'));
+ }
+
+ public function test_mod_glossary_can_update_entry_users() {
+ $this->resetAfterTest();
+
+ // Create required data.
+ $course = $this->getDataGenerator()->create_course();
+ $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $anotherstudent = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $teacher = $this->getDataGenerator()->create_and_enrol($course, 'editingteacher');
+ $glossary = $this->getDataGenerator()->create_module('glossary', array('course' => $course->id));
+
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+ $this->setUser($student);
+ $entry = $gg->create_content($glossary);
+ $context = context_module::instance($glossary->cmid);
+ $cm = get_coursemodule_from_instance('glossary', $glossary->id);
+
+ // Test student can update.
+ $this->assertTrue(mod_glossary_can_update_entry($entry, $glossary, $context, $cm));
+
+ // Test teacher can update.
+ $this->setUser($teacher);
+ $this->assertTrue(mod_glossary_can_update_entry($entry, $glossary, $context, $cm));
+
+ // Test admin can update.
+ $this->setAdminUser();
+ $this->assertTrue(mod_glossary_can_update_entry($entry, $glossary, $context, $cm));
+
+ // Test a different student is not able to update.
+ $this->setUser($anotherstudent);
+ $this->assertFalse(mod_glossary_can_update_entry($entry, $glossary, $context, $cm));
+
+ // Test exception.
+ $this->expectExceptionMessage(get_string('errcannoteditothers', 'glossary'));
+ mod_glossary_can_update_entry($entry, $glossary, $context, $cm, false);
+ }
+
+ public function test_mod_glossary_can_update_entry_edit_period() {
+ global $CFG;
+ $this->resetAfterTest();
+
+ // Create required data.
+ $course = $this->getDataGenerator()->create_course();
+ $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+ $glossary = $this->getDataGenerator()->create_module('glossary', array('course' => $course->id, 'editalways' => 1));
+
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+ $this->setUser($student);
+ $entry = $gg->create_content($glossary);
+ $context = context_module::instance($glossary->cmid);
+ $cm = get_coursemodule_from_instance('glossary', $glossary->id);
+
+ // Test student can always update when edit always is set to 1.
+ $entry->timecreated = time() - 2 * $CFG->maxeditingtime;
+ $this->assertTrue(mod_glossary_can_update_entry($entry, $glossary, $context, $cm));
+
+ // Test student cannot update old entries when edit always is set to 0.
+ $glossary->editalways = 0;
+ $this->assertFalse(mod_glossary_can_update_entry($entry, $glossary, $context, $cm));
+
+ // Test student can update recent entries when edit always is set to 0.
+ $entry->timecreated = time();
+ $this->assertTrue(mod_glossary_can_update_entry($entry, $glossary, $context, $cm));
+
+ // Check exception.
+ $entry->timecreated = time() - 2 * $CFG->maxeditingtime;
+ $this->expectExceptionMessage(get_string('erredittimeexpired', 'glossary'));
+ mod_glossary_can_update_entry($entry, $glossary, $context, $cm, false);
+ }
+
+ public function test_prepare_entry_for_edition() {
+ global $USER;
+ $this->resetAfterTest(true);
+
+ $course = $this->getDataGenerator()->create_course();
+ $glossary = $this->getDataGenerator()->create_module('glossary', ['course' => $course->id]);
+ $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
+
+ $this->setAdminUser();
+ $aliases = ['alias1', 'alias2'];
+ $entry = $gg->create_content(
+ $glossary,
+ ['approved' => 1, 'userid' => $USER->id],
+ $aliases
+ );
+
+ $cat1 = $gg->create_category($glossary, [], [$entry]);
+ $gg->create_category($glossary);
+
+ $entry = mod_glossary_prepare_entry_for_edition($entry);
+ $this->assertCount(1, $entry->categories);
+ $this->assertEquals($cat1->id, $entry->categories[0]);
+ $returnedaliases = array_values(explode("\n", trim($entry->aliases)));
+ sort($returnedaliases);
+ $this->assertEquals($aliases, $returnedaliases);
+ }
}
This files describes API changes in /mod/glossary/*,
information provided here is intended especially for developers.
+=== 3.10 ===
+* External function get_entries_by_id now returns and additional "permissions" field indicating the user permissions for managing
+ the entry.
+
=== 3.8 ===
* The following functions have been finally deprecated and can not be used anymore:
* glossary_scale_used()
defined('MOODLE_INTERNAL') || die();
-$plugin->version = 2020061500; // The current module version (Date: YYYYMMDDXX)
+$plugin->version = 2020061502; // The current module version (Date: YYYYMMDDXX)
$plugin->requires = 2020060900; // Requires this Moodle version
$plugin->component = 'mod_glossary'; // Full name of the plugin (used for diagnostics)
$plugin->cron = 0;
defined('MOODLE_INTERNAL') || die();
-$version = 2020101300.00; // YYYYMMDD = weekly release date of this DEV branch.
+$version = 2020101300.01; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
$release = '3.10dev+ (Build: 20201013)';// Human-friendly version name