first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
define("tool_langimport/search",["exports","core/pending","core/utils"],(function(_exports,_pending,_utils){var obj;
/**
* Add search filtering of available language packs
*
* @module tool_langimport/search
* @copyright 2021 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_pending=(obj=_pending)&&obj.__esModule?obj:{default:obj};const SELECTORS_AVAILABLE_LANG_SELECT="select",SELECTORS_AVAILABLE_LANG_SEARCH='[data-action="search"]';_exports.init=form=>{const availableLangsElement=form.querySelector(SELECTORS_AVAILABLE_LANG_SELECT),availableLanguages={};availableLangsElement.querySelectorAll("option").forEach((option=>{availableLanguages[option.value]=option.text})),availableLangsElement.dataset.availableLanguages=JSON.stringify(availableLanguages);const availableLangsSearch=form.querySelector(SELECTORS_AVAILABLE_LANG_SEARCH);availableLangsSearch.addEventListener("keydown",(event=>{"Enter"===event.key&&event.preventDefault()}));const availableLangsSearchDebounce=(0,_utils.debounce)((event=>{const pendingPromise=new _pending.default("tool_langimport/search:filter");availableLangsElement.querySelectorAll("option").forEach((option=>{option.remove()}));const searchTerm=event.target.value.toLowerCase(),availableLanguages=JSON.parse(availableLangsElement.dataset.availableLanguages),filteredLanguages=Object.keys(availableLanguages).reduce(((matches,langcode)=>(availableLanguages[langcode].toLowerCase().includes(searchTerm)&&(matches[langcode]=availableLanguages[langcode]),matches)),[]);Object.entries(filteredLanguages).forEach((_ref=>{let[langcode,langname]=_ref;const option=document.createElement("option");option.value=langcode,option.innerText=langname,availableLangsElement.append(option)})),pendingPromise.resolve()}),250);availableLangsSearch.addEventListener("keyup",(event=>{const pendingPromise=new _pending.default("tool_langimport/search:keyup");availableLangsSearchDebounce(event),setTimeout((()=>{pendingPromise.resolve()}),250)}))}}));
//# sourceMappingURL=search.min.js.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
define("tool_langimport/uninstall",["exports","core/str","core/notification","core/config"],(function(_exports,_str,_notification,_config){var obj;Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0,_config=(obj=_config)&&obj.__esModule?obj:{default:obj};_exports.init=form=>{null==form||form.addEventListener("submit",(async e=>{var _form$querySelector;e.preventDefault();const selectedOptions=null===(_form$querySelector=form.querySelector("#menuuninstalllang"))||void 0===_form$querySelector?void 0:_form$querySelector.selectedOptions;if(null==selectedOptions||!selectedOptions.length){const alertStrings=await(0,_str.getStrings)(["noenglishuninstalltitle","selectlangs"].map((key=>({key:key,component:"tool_langimport"}))));return void(0,_notification.alert)(...alertStrings)}if(-1!==[...selectedOptions].map((node=>node.value)).indexOf("en")){const alertStrings=await(0,_str.getStrings)(["noenglishuninstalltitle","noenglishuninstall"].map((key=>({key:key,component:"tool_langimport"}))));return void(0,_notification.alert)(...alertStrings)}const confirmationStrings=await(0,_str.getStrings)([{key:"uninstall",component:"tool_langimport"},{key:"uninstallconfirm",component:"tool_langimport",param:[...selectedOptions].map((node=>node.textContent)).join(", ")},{key:"yes",component:"core"}]);(0,_notification.saveCancelPromise)(...confirmationStrings).then((()=>{const url=new URL(form.action);return url.searchParams.append("sesskey",_config.default.sesskey),url.searchParams.append("confirmtouninstall",[...selectedOptions].map((node=>node.value)).join("/")),form.action=url.toString(),form.submit(),!0})).catch((()=>!1))}))}}));
//# sourceMappingURL=uninstall.min.js.map
@@ -0,0 +1 @@
{"version":3,"file":"uninstall.min.js","sources":["../src/uninstall.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle. If not, see <http://www.gnu.org/licenses/>.\n\nimport {getStrings} from 'core/str';\nimport {saveCancelPromise, alert as displayAlert} from \"core/notification\";\nimport MoodleConfig from 'core/config';\n\nexport const init = (form) => {\n form?.addEventListener('submit', async(e) => {\n e.preventDefault();\n const selectedOptions = form.querySelector('#menuuninstalllang')?.selectedOptions;\n if (!selectedOptions?.length) {\n const alertStrings = await getStrings(\n ['noenglishuninstalltitle', 'selectlangs'].map((key) => ({key, component: 'tool_langimport'})\n ));\n displayAlert(...alertStrings);\n return;\n }\n\n if ([...selectedOptions].map((node) => node.value).indexOf('en') !== -1) {\n const alertStrings = await getStrings(\n ['noenglishuninstalltitle', 'noenglishuninstall'].map((key) => ({key, component: 'tool_langimport'})\n ));\n displayAlert(...alertStrings);\n return;\n }\n\n const confirmationStrings = await getStrings([\n {\n key: 'uninstall',\n component: 'tool_langimport',\n },\n {\n key: 'uninstallconfirm',\n component: 'tool_langimport',\n param: [...selectedOptions].map((node) => node.textContent).join(', '),\n },\n {\n key: 'yes',\n component: 'core',\n },\n ]);\n\n saveCancelPromise(...confirmationStrings).then(() => {\n const url = new URL(form.action);\n url.searchParams.append('sesskey', MoodleConfig.sesskey);\n url.searchParams.append('confirmtouninstall', [...selectedOptions].map((node) => node.value).join('/'));\n form.action = url.toString();\n form.submit();\n return true;\n })\n .catch(() => {\n return false;\n });\n });\n};\n"],"names":["form","addEventListener","async","e","preventDefault","selectedOptions","querySelector","_form$querySelector","length","alertStrings","map","key","component","node","value","indexOf","confirmationStrings","param","textContent","join","then","url","URL","action","searchParams","append","MoodleConfig","sesskey","toString","submit","catch"],"mappings":"sSAmBqBA,OACjBA,MAAAA,MAAAA,KAAMC,iBAAiB,UAAUC,MAAAA,4BAC7BC,EAAEC,uBACIC,4CAAkBL,KAAKM,cAAc,4DAAnBC,oBAA0CF,mBAC7DA,MAAAA,kBAAAA,gBAAiBG,OAAQ,OACpBC,mBAAqB,mBACvB,CAAC,0BAA2B,eAAeC,KAAKC,OAAUA,IAAAA,IAAKC,UAAW,6DAE9DH,kBAIkD,IAAlE,IAAIJ,iBAAiBK,KAAKG,MAASA,KAAKC,QAAOC,QAAQ,MAAc,OAC/DN,mBAAqB,mBACvB,CAAC,0BAA2B,sBAAsBC,KAAKC,OAAUA,IAAAA,IAAKC,UAAW,6DAErEH,oBAIdO,0BAA4B,mBAAW,CACzC,CACIL,IAAK,YACLC,UAAW,mBAEf,CACID,IAAK,mBACLC,UAAW,kBACXK,MAAO,IAAIZ,iBAAiBK,KAAKG,MAASA,KAAKK,cAAaC,KAAK,OAErE,CACIR,IAAK,MACLC,UAAW,iDAIEI,qBAAqBI,MAAK,WACrCC,IAAM,IAAIC,IAAItB,KAAKuB,eACzBF,IAAIG,aAAaC,OAAO,UAAWC,gBAAaC,SAChDN,IAAIG,aAAaC,OAAO,qBAAsB,IAAIpB,iBAAiBK,KAAKG,MAASA,KAAKC,QAAOK,KAAK,MAClGnB,KAAKuB,OAASF,IAAIO,WAClB5B,KAAK6B,UACE,KAEVC,OAAM,KACI"}
+96
View File
@@ -0,0 +1,96 @@
// 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/>.
/**
* Add search filtering of available language packs
*
* @module tool_langimport/search
* @copyright 2021 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
import Pending from 'core/pending';
import {debounce} from 'core/utils';
const SELECTORS = {
AVAILABLE_LANG_SELECT: 'select',
AVAILABLE_LANG_SEARCH: '[data-action="search"]',
};
const DEBOUNCE_TIMER = 250;
/**
* Initialize module
*
* @param {Element} form
*/
export const init = form => {
const availableLangsElement = form.querySelector(SELECTORS.AVAILABLE_LANG_SELECT);
const availableLangsFilter = (event) => {
const pendingPromise = new Pending('tool_langimport/search:filter');
// Remove existing options.
availableLangsElement.querySelectorAll('option').forEach((option) => {
option.remove();
});
// Filter for matching languages.
const searchTerm = event.target.value.toLowerCase();
const availableLanguages = JSON.parse(availableLangsElement.dataset.availableLanguages);
const filteredLanguages = Object.keys(availableLanguages).reduce((matches, langcode) => {
if (availableLanguages[langcode].toLowerCase().includes(searchTerm)) {
matches[langcode] = availableLanguages[langcode];
}
return matches;
}, []);
// Re-create filtered options.
Object.entries(filteredLanguages).forEach(([langcode, langname]) => {
const option = document.createElement('option');
option.value = langcode;
option.innerText = langname;
availableLangsElement.append(option);
});
pendingPromise.resolve();
};
// Cache initial available language options.
const availableLanguages = {};
availableLangsElement.querySelectorAll('option').forEach((option) => {
availableLanguages[option.value] = option.text;
});
availableLangsElement.dataset.availableLanguages = JSON.stringify(availableLanguages);
// Register event listeners on the search element.
const availableLangsSearch = form.querySelector(SELECTORS.AVAILABLE_LANG_SEARCH);
availableLangsSearch.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
}
});
// Debounce the event listener to allow the user to finish typing.
const availableLangsSearchDebounce = debounce(availableLangsFilter, DEBOUNCE_TIMER);
availableLangsSearch.addEventListener('keyup', (event) => {
const pendingPromise = new Pending('tool_langimport/search:keyup');
availableLangsSearchDebounce(event);
setTimeout(() => {
pendingPromise.resolve();
}, DEBOUNCE_TIMER);
});
};
@@ -0,0 +1,68 @@
// 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 {getStrings} from 'core/str';
import {saveCancelPromise, alert as displayAlert} from "core/notification";
import MoodleConfig from 'core/config';
export const init = (form) => {
form?.addEventListener('submit', async(e) => {
e.preventDefault();
const selectedOptions = form.querySelector('#menuuninstalllang')?.selectedOptions;
if (!selectedOptions?.length) {
const alertStrings = await getStrings(
['noenglishuninstalltitle', 'selectlangs'].map((key) => ({key, component: 'tool_langimport'})
));
displayAlert(...alertStrings);
return;
}
if ([...selectedOptions].map((node) => node.value).indexOf('en') !== -1) {
const alertStrings = await getStrings(
['noenglishuninstalltitle', 'noenglishuninstall'].map((key) => ({key, component: 'tool_langimport'})
));
displayAlert(...alertStrings);
return;
}
const confirmationStrings = await getStrings([
{
key: 'uninstall',
component: 'tool_langimport',
},
{
key: 'uninstallconfirm',
component: 'tool_langimport',
param: [...selectedOptions].map((node) => node.textContent).join(', '),
},
{
key: 'yes',
component: 'core',
},
]);
saveCancelPromise(...confirmationStrings).then(() => {
const url = new URL(form.action);
url.searchParams.append('sesskey', MoodleConfig.sesskey);
url.searchParams.append('confirmtouninstall', [...selectedOptions].map((node) => node.value).join('/'));
form.action = url.toString();
form.submit();
return true;
})
.catch(() => {
return false;
});
});
};
@@ -0,0 +1,282 @@
<?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/>.
/**
* Lang import controller
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport;
use moodle_url;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/filelib.php');
require_once($CFG->libdir.'/componentlib.class.php');
/**
* Lang import controller
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class controller {
/** @var array list of informational messages */
public $info;
/** @var array list of error messages */
public $errors;
/** @var \lang_installer */
private $installer;
/** @var array languages available on the remote server */
public $availablelangs;
/**
* Constructor.
*/
public function __construct() {
make_temp_directory('');
make_upload_directory('lang');
$this->info = array();
$this->errors = array();
$this->installer = new \lang_installer();
$this->availablelangs = $this->installer->get_remote_list_of_languages();
}
/**
* Redirect to the specified url, outputting any required messages.
*
* @param moodle_url $url
*/
public function redirect(moodle_url $url): void {
if ($this->info) {
$info = implode('<br />', $this->info);
\core\notification::success($info);
}
if ($this->errors) {
$info = implode('<br />', $this->errors);
\core\notification::error($info);
}
redirect($url);
}
/**
* Install language packs provided
*
* @param string|array $langs array of langcodes or individual langcodes
* @param bool $updating true if updating the langpacks
* @return int false if an error encountered or
* @throws \moodle_exception when error is encountered installing langpack
*/
public function install_languagepacks($langs, $updating = false) {
global $CFG;
$this->installer->set_queue($langs);
$results = $this->installer->run();
$updatedpacks = 0;
foreach ($results as $langcode => $langstatus) {
switch ($langstatus) {
case \lang_installer::RESULT_DOWNLOADERROR:
$a = new \stdClass();
$a->url = $this->installer->lang_pack_url($langcode);
$a->dest = $CFG->dataroot.'/lang';
$this->errors[] = get_string('remotedownloaderror', 'error', $a);
throw new \moodle_exception('remotedownloaderror', 'error', '', $a);
break;
case \lang_installer::RESULT_INSTALLED:
$updatedpacks++;
if ($updating) {
event\langpack_updated::event_with_langcode($langcode)->trigger();
$this->info[] = get_string('langpackupdated', 'tool_langimport', $langcode);
} else {
$this->info[] = get_string('langpackinstalled', 'tool_langimport', $langcode);
event\langpack_imported::event_with_langcode($langcode)->trigger();
}
break;
case \lang_installer::RESULT_UPTODATE:
$this->info[] = get_string('langpackuptodate', 'tool_langimport', $langcode);
break;
}
}
return $updatedpacks;
}
/**
* Uninstall language pack
*
* @param string $lang language code
* @return bool true if language succesfull installed
*/
public function uninstall_language($lang) {
global $CFG;
$lang = clean_param($lang, PARAM_LANG);
if ($lang === '') {
// Do not allow uninstallation of invalid languages.
// Note: PARAM_LANG returns an empty string for invalid validation.
return false;
}
if ($lang === 'en') {
// Never allow removal of the default langauge.
return false;
}
$dest1 = $CFG->dataroot.'/lang/'.$lang;
$dest2 = $CFG->dirroot.'/lang/'.$lang;
$rm1 = false;
$rm2 = false;
if (file_exists($dest1)) {
$rm1 = remove_dir($dest1);
}
if (file_exists($dest2)) {
$rm2 = remove_dir($dest2);
}
if ($rm1 or $rm2) {
// Set the default site language to en if the deleted language pack is the default site language.
if ($CFG->lang === $lang) {
set_config('lang', 'en');
// Fix the user's current language to the default site language.
fix_current_language($CFG->lang);
}
$this->info[] = get_string('langpackremoved', 'tool_langimport', $lang);
event\langpack_removed::event_with_langcode($lang)->trigger();
return true;
} else { // Nothing deleted, possibly due to permission error.
$this->errors[] = get_string('langpacknotremoved', 'tool_langimport', $lang);
return false;
}
}
/**
* Updated all install language packs with the latest found on servre
*
* @return bool true if languages succesfully updated.
*/
public function update_all_installed_languages() {
global $CFG;
if (!$availablelangs = $this->installer->get_remote_list_of_languages()) {
$this->errors[] = get_string('cannotdownloadlanguageupdatelist', 'error');
return false;
}
$md5array = array(); // Convert to (string)langcode => (string)md5.
foreach ($availablelangs as $alang) {
$md5array[$alang[0]] = $alang[1];
}
// Filter out unofficial packs.
$currentlangs = array_keys(get_string_manager()->get_list_of_translations(true));
$updateablelangs = array();
foreach ($currentlangs as $clang) {
if (!array_key_exists($clang, $md5array)) {
$this->info[] = get_string('langpackupdateskipped', 'tool_langimport', $clang);
continue;
}
$dest1 = $CFG->dataroot.'/lang/'.$clang;
$dest2 = $CFG->dirroot.'/lang/'.$clang;
if (file_exists($dest1.'/langconfig.php') || file_exists($dest2.'/langconfig.php')) {
$updateablelangs[] = $clang;
}
}
// Filter out packs that have the same md5 key.
$neededlangs = array();
foreach ($updateablelangs as $ulang) {
if (!$this->is_installed_lang($ulang, $md5array[$ulang])) {
$neededlangs[] = $ulang;
}
}
try {
$updated = $this->install_languagepacks($neededlangs, true);
} catch (\moodle_exception $e) {
$this->errors[] = 'An exception occurred while installing language packs: ' . $e->getMessage();
return false;
}
if ($updated) {
$this->info[] = get_string('langupdatecomplete', 'tool_langimport');
// The strings have been changed so we need to purge their cache to ensure users see the changes.
get_string_manager()->reset_caches();
} else {
$this->info[] = get_string('nolangupdateneeded', 'tool_langimport');
}
return true;
}
/**
* checks the md5 of the zip file, grabbed from download.moodle.org,
* against the md5 of the local language file from last update
* @param string $lang language code
* @param string $md5check md5 to check
* @return bool true if installed
*/
public function is_installed_lang($lang, $md5check) {
global $CFG;
$md5file = $CFG->dataroot.'/lang/'.$lang.'/'.$lang.'.md5';
if (file_exists($md5file)) {
return (file_get_contents($md5file) == $md5check);
}
return false;
}
/**
* Returns the URL where a given language pack can be downloaded
*
* Alternatively, if the parameter is empty, returns URL of the page with the
* list of all available language packs.
*
* @param string $langcode language code like 'cs' or empty for unknown
* @return string URL
*/
public function lang_pack_url($langcode = '') {
return $this->installer->lang_pack_url($langcode);
}
/**
* Schedule installation of the given language packs asynchronously via ad hoc task.
*
* @param string|array $langs array of langcodes or individual langcodes
*/
public function schedule_languagepacks_installation($langs): void {
global $USER;
$task = new \tool_langimport\task\install_langpacks();
$task->set_userid($USER->id);
$task->set_custom_data([
'langs' => $langs,
]);
\core\task\manager::queue_adhoc_task($task, true);
$this->info[] = get_string('installscheduled', 'tool_langimport');
}
}
@@ -0,0 +1,120 @@
<?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/>.
/**
* The langimport langpack imported event.
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport\event;
defined('MOODLE_INTERNAL') || die();
/**
* The tool_langimport langpack imported event class.
*
* @property-read array $other {
* Extra information about event.
*
* - string langcode: the langpage pack code.
* }
*
* @package tool_langimport
* @since Moodle 2.8
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class langpack_imported extends \core\event\base {
/**
* Create instance of event.
*
* @param string $langcode
* @return langpack_updated
*/
public static function event_with_langcode($langcode) {
$data = array(
'context' => \context_system::instance(),
'other' => array(
'langcode' => $langcode,
)
);
return self::create($data);
}
/**
* Init method.
*
* @return void
*/
protected function init() {
$this->data['crud'] = 'c';
$this->data['edulevel'] = self::LEVEL_OTHER;
}
/**
* Returns description of what happened.
*
* @return string
*/
public function get_description() {
return "The language pack '{$this->other['langcode']}' was installed.";
}
/**
* Return localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('langpackinstalledevent', 'tool_langimport');
}
/**
* Returns relevant URL.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/admin/tool/langimport/');
}
/**
* Custom validation.
*
* @throws \coding_exception
*/
protected function validate_data() {
parent::validate_data();
if (!isset($this->other['langcode'])) {
throw new \coding_exception('The \'langcode\' value must be set');
}
// We can't use PARAM_LANG here as the string manager might not be aware of langpack yet.
$cleanedlang = clean_param($this->other['langcode'], PARAM_SAFEDIR);
if ($cleanedlang !== $this->other['langcode']) {
throw new \coding_exception('The \'langcode\' value must be set to a valid language code');
}
}
public static function get_other_mapping() {
// No mapping required for this event because this event is not backed up.
return false;
}
}
@@ -0,0 +1,121 @@
<?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/>.
/**
* The langimport langpack removed event.
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport\event;
defined('MOODLE_INTERNAL') || die();
/**
* The tool_langimport langpack removed event class.
*
* @property-read array $other {
* Extra information about event.
*
* - string langcode: the langpage pack code.
* }
*
* @package tool_langimport
* @since Moodle 2.8
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class langpack_removed extends \core\event\base {
/**
* Create instance of event.
*
* @param string $langcode
* @return langpack_updated
*/
public static function event_with_langcode($langcode) {
$data = array(
'context' => \context_system::instance(),
'other' => array(
'langcode' => $langcode,
)
);
return self::create($data);
}
/**
* Init method.
*
* @return void
*/
protected function init() {
$this->data['crud'] = 'd';
$this->data['edulevel'] = self::LEVEL_OTHER;
}
/**
* Returns description of what happened.
*
* @return string
*/
public function get_description() {
return "The language pack '{$this->other['langcode']}' was removed.";
}
/**
* Returns relevant URL.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/admin/tool/langimport/');
}
/**
* Return localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('langpackremovedevent', 'tool_langimport');
}
/**
* Custom validation.
*
* @throws \coding_exception
*/
protected function validate_data() {
parent::validate_data();
if (!isset($this->other['langcode'])) {
throw new \coding_exception('The \'langcode\' value must be set');
}
// We can't use PARAM_LANG here as it queries installed strings.
$cleanedlang = clean_param($this->other['langcode'], PARAM_SAFEDIR);
if ($cleanedlang !== $this->other['langcode']) {
throw new \coding_exception('The \'langcode\' value must be set to a valid language code');
}
}
public static function get_other_mapping() {
// No mapping required for this event because this event is not backed up.
return false;
}
}
@@ -0,0 +1,120 @@
<?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/>.
/**
* The langimport langpack updated event.
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport\event;
defined('MOODLE_INTERNAL') || die();
/**
* The tool_langimport langpack updated event class.
*
* @property-read array $other {
* Extra information about event.
*
* - string langcode: the langpage pack code.
* }
*
* @package tool_langimport
* @since Moodle 2.8
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class langpack_updated extends \core\event\base {
/**
* Create instance of event.
*
* @param string $langcode
* @return langpack_updated
*/
public static function event_with_langcode($langcode) {
$data = array(
'context' => \context_system::instance(),
'other' => array(
'langcode' => $langcode,
)
);
return self::create($data);
}
/**
* Init method.
*
* @return void
*/
protected function init() {
$this->data['crud'] = 'u';
$this->data['edulevel'] = self::LEVEL_OTHER;
}
/**
* Returns description of what happened.
*
* @return string
*/
public function get_description() {
return "The language pack '{$this->other['langcode']}' was updated.";
}
/**
* Return localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('langpackupdatedevent', 'tool_langimport');
}
/**
* Returns relevant URL.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/admin/tool/langimport/');
}
/**
* Custom validation.
*
* @throws \coding_exception
*/
protected function validate_data() {
parent::validate_data();
if (!isset($this->other['langcode'])) {
throw new \coding_exception('The \'langcode\' value must be set');
}
$cleanedlang = clean_param($this->other['langcode'], PARAM_LANG);
if ($cleanedlang !== $this->other['langcode']) {
throw new \coding_exception('The \'langcode\' value must be set to a valid language code');
}
}
public static function get_other_mapping() {
// No mapping required for this event because this event is not backed up.
return false;
}
}
+94
View File
@@ -0,0 +1,94 @@
<?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/>.
/**
* Helper class for the language import tool.
*
* @package tool_langimport
* @copyright 2018 Université Rennes 2 {@link https://www.univ-rennes2.fr}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport;
use coding_exception;
defined('MOODLE_INTERNAL') || die;
/**
* Helper class for the language import tool.
*
* @copyright 2018 Université Rennes 2 {@link https://www.univ-rennes2.fr}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class locale {
/**
* Checks availability of locale on current operating system.
*
* @param string $langpackcode E.g.: en, es, fr, de.
* @return bool TRUE if the locale is available on OS.
* @throws coding_exception when $langpackcode parameter is a non-empty string.
*/
public function check_locale_availability(string $langpackcode): bool {
global $CFG;
if (empty($langpackcode)) {
throw new coding_exception('Invalid language pack code in \\'.__METHOD__.'() call, only non-empty string is allowed');
}
// Fetch the correct locale based on ostype.
if ($CFG->ostype === 'WINDOWS') {
$stringtofetch = 'localewin';
} else {
$stringtofetch = 'locale';
}
// Store current locale.
$currentlocale = $this->get_locale();
$locale = get_string_manager()->get_string($stringtofetch, 'langconfig', $a = null, $langpackcode);
// Try to set new locale.
$return = $this->set_locale(LC_ALL, $locale);
// Restore current locale.
$this->set_locale(LC_ALL, $currentlocale);
// If $return is not equal to false, it means that setlocale() succeed to change locale.
return $return !== false;
}
/**
* Wrap for the native PHP function setlocale().
*
* @param int $category Specifying the category of the functions affected by the locale setting.
* @param string $locale E.g.: en_AU.utf8, en_GB.utf8, es_ES.utf8, fr_FR.utf8, de_DE.utf8.
* @return string|false Returns the new current locale, or FALSE on error.
*/
protected function set_locale(int $category = LC_ALL, string $locale = '0') {
return \core\locale::set_locale($category, $locale);
}
/**
* Get the current locale.
*
* @param int $category
* @return string|false
*/
protected function get_locale(int $category = LC_ALL): string|false {
return \core\locale::get_locale($category);
}
}
@@ -0,0 +1,117 @@
<?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 import page.
*
* @package tool_langimport
* @copyright 2016 Jun Pataleta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport\output;
use core_collator;
use moodle_url;
use renderable;
use renderer_base;
use stdClass;
use templatable;
/**
* Language import page class.
*
* @package tool_langimport
* @copyright 2016 Jun Pataleta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class langimport_page implements renderable, templatable {
/** @var array Array of currently installed languages. */
protected $installedlanguages;
/** @var array Array of languages that can be installed. */
protected $availablelanguages;
/** @var moodle_url The URL to be used for uninstalling the selected existing language packs. */
protected $uninstallurl;
/** @var moodle_url The URL to be used for updating the installed language packs. */
protected $updateurl;
/** @var moodle_url The URL to be used for installing the selected language packs to be installed. */
protected $installurl;
/**
* langimport_page constructor.
*
* @param array $installedlanguages Array of currently installed languages.
* @param array $availablelanguages Array of languages that can be installed.
* @param moodle_url $uninstallurl The URL to be used for uninstalling the selected existing language packs.
* @param moodle_url $updateurl The URL to be used for updating the installed language packs.
* @param moodle_url $installurl The URL to be used for installing the selected language packs to be installed.
*/
public function __construct($installedlanguages, $availablelanguages, $uninstallurl, $updateurl, $installurl) {
$this->installedlanguages = $installedlanguages;
$this->availablelanguages = $availablelanguages;
$this->uninstallurl = $uninstallurl;
$this->updateurl = $updateurl;
$this->installurl = $installurl;
}
/**
* Export the data.
*
* @param renderer_base $output
* @return stdClass
*/
public function export_for_template(renderer_base $output) {
$data = new stdClass();
$data->uninstallurl = $this->uninstallurl;
$data->sesskey = sesskey();
$data->installedoptions = [];
foreach ($this->installedlanguages as $code => $language) {
$option = new stdClass();
$option->value = $code;
$option->text = $language;
$data->installedoptions[] = $option;
}
$data->updateurl = $this->updateurl;
if (!empty($this->availablelanguages)) {
$data->toinstalloptions = [];
core_collator::asort($this->availablelanguages);
foreach ($this->availablelanguages as $code => $language) {
$option = new stdClass();
$option->value = $code;
$option->text = $language;
$data->toinstalloptions[] = $option;
}
$data->installurl = $this->installurl;
$data->caninstall = true;
}
if (count($this->installedlanguages) > 3) {
$data->hasmanyinstalledlanguages = true;
$data->updatelangstaskname = get_string('updatelangs', 'tool_langimport');
}
return $data;
}
}
@@ -0,0 +1,50 @@
<?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/>.
/**
* Renderers.
*
* @package tool_langimport
* @copyright 2016 Jun Pataleta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport\output;
defined('MOODLE_INTERNAL') || die();
use plugin_renderer_base;
/**
* Renderer class.
*
* @package tool_langimport
* @copyright 2016 Jun Pataleta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class renderer extends plugin_renderer_base {
/**
* Defer to template.
*
* @param langimport_page $page
* @return string
*/
public function render_langimport_page(langimport_page $page) {
$data = $page->export_for_template($this);
return parent::render_from_template('tool_langimport/langimport', $data);
}
}
@@ -0,0 +1,46 @@
<?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/>.
/**
* Privacy Subsystem implementation for tool_langimport.
*
* @package tool_langimport
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for tool_langimport implementing null_provider.
*
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
}
@@ -0,0 +1,109 @@
<?php
// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
namespace tool_langimport\task;
/**
* Ad hoc task to install one or more language packs.
*
* @package tool_langimport
* @category task
* @copyright 2021 David Mudrák <david@moodle.com>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class install_langpacks extends \core\task\adhoc_task {
/**
* Execute the ad hoc task.
*/
public function execute(): void {
$data = $this->get_custom_data();
if (empty($data->langs)) {
mtrace('No language packs to install');
}
get_string_manager()->reset_caches();
$controller = new \tool_langimport\controller();
\core_php_time_limit::raise();
try {
$controller->install_languagepacks($data->langs);
$this->notify_user_success($controller);
} catch (\Throwable $e) {
$this->notify_user_error($e->getMessage());
} finally {
get_string_manager()->reset_caches();
}
}
/**
* Notify user that the task finished successfully.
*
* @param \tool_langimport\controller $controller
*/
protected function notify_user_success(\tool_langimport\controller $controller): void {
$message = new \core\message\message();
$message->component = 'moodle';
$message->name = 'notices';
$message->userfrom = \core_user::get_noreply_user();
$message->userto = $this->get_userid();
$message->notification = 1;
$message->contexturl = (new \moodle_url('/admin/tool/langimport/index.php'))->out(false);
$message->contexturlname = get_string('pluginname', 'tool_langimport');
$message->subject = get_string('installfinished', 'tool_langimport');
$message->fullmessage = '* ' . implode(PHP_EOL . '* ', $controller->info);
$message->fullmessageformat = FORMAT_MARKDOWN;
$message->fullmessagehtml = markdown_to_html($message->fullmessage);
$message->smallmessage = get_string('installfinished', 'tool_langimport');
message_send($message);
}
/**
* Notify user that the task failed.
*
* @param string $error The error text
*/
protected function notify_user_error(string $error): void {
$message = new \core\message\message();
$message->component = 'moodle';
$message->name = 'notices';
$message->userfrom = \core_user::get_noreply_user();
$message->userto = $this->get_userid();
$message->notification = 1;
$message->contexturl = (new \moodle_url('/admin/tool/langimport/index.php'))->out(false);
$message->contexturlname = get_string('pluginname', 'tool_langimport');
$message->subject = get_string('installfailed', 'tool_langimport');
$message->fullmessage = $error;
$message->fullmessageformat = FORMAT_PLAIN;
$message->fullmessagehtml = text_to_html($message->fullmessage);
$message->smallmessage = get_string('installfailed', 'tool_langimport');
message_send($message);
}
}
@@ -0,0 +1,71 @@
<?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/>.
/**
* A scheduled task for updating langpacks.
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace tool_langimport\task;
/**
* A scheduled task for updating langpacks.
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class update_langpacks_task extends \core\task\scheduled_task {
/**
* Get a descriptive name for this task (shown to admins).
*
* @return string
*/
public function get_name() {
return get_string('updatelangs', 'tool_langimport');
}
/**
* Run langpack update
*/
public function execute() {
global $CFG;
if (!empty($CFG->skiplangupgrade)) {
mtrace('Langpack update skipped. ($CFG->skiplangupgrade set)');
return;
}
$controller = new \tool_langimport\controller();
if ($controller->update_all_installed_languages()) {
foreach ($controller->info as $message) {
mtrace($message);
}
return true;
} else {
foreach ($controller->errors as $message) {
mtrace($message);
}
return false;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
<?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/>.
/**
* Definition of langimport tasks
*
* @package tool_langimport
* @category task
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$tasks = array(
array(
'classname' => 'tool_langimport\task\update_langpacks_task',
'blocking' => 0,
'minute' => 'R',
'hour' => '4',
'day' => '*',
'month' => '*',
'dayofweek' => '*'
)
);
+233
View File
@@ -0,0 +1,233 @@
<?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/>.
/**
* Fetches language packages from download.moodle.org server
*
* Language packages are available at https://download.moodle.org/langpack/
* in ZIP format together with a file languages.md5 containing their hashes
* and meta info.
* Locally, language packs are saved into $CFG->dataroot/lang/
*
* @package tool
* @subpackage langimport
* @copyright 2005 Yu Zhang
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require(__DIR__.'/../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
admin_externalpage_setup('toollangimport');
if (empty($CFG->langotherroot)) {
throw new moodle_exception('missingcfglangotherroot', 'tool_langimport');
}
$mode = optional_param('mode', 0, PARAM_INT); // action
$pack = optional_param_array('pack', array(), PARAM_SAFEDIR); // pack to install
$uninstalllang = optional_param_array('uninstalllang', array(), PARAM_LANG);// installed pack to uninstall
$confirmtounistall = optional_param('confirmtouninstall', '', PARAM_SAFEPATH); // uninstallation confirmation
$purgecaches = optional_param('purgecaches', false, PARAM_BOOL); // explicit caches reset
// Filter the uninstall language list.
// If the list contains a language which is not installed, it is replaced with an empty string.
// When we try to uninstall an empty string, we uninstall every language.
$uninstalllang = array_filter($uninstalllang, function($lang) {
return !empty($lang);
});
if ($purgecaches) {
require_sesskey();
get_string_manager()->reset_caches();
redirect($PAGE->url);
}
if (!empty($CFG->skiplangupgrade)) {
echo $OUTPUT->header();
echo $OUTPUT->box(get_string('langimportdisabled', 'tool_langimport'));
echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('purgecaches' => 1)), get_string('purgestringcaches', 'tool_langimport'));
echo $OUTPUT->footer();
die;
}
define('INSTALLATION_OF_SELECTED_LANG', 2);
define('DELETION_OF_SELECTED_LANG', 4);
define('UPDATE_ALL_LANG', 5);
get_string_manager()->reset_caches();
$controller = new tool_langimport\controller();
if (($mode == INSTALLATION_OF_SELECTED_LANG) and confirm_sesskey() and !empty($pack)) {
if (is_array($pack) && count($pack) > 1) {
// Installing multiple languages can take a while - perform it asynchronously in the background.
$controller->schedule_languagepacks_installation($pack);
$controller->redirect($PAGE->url);
} else {
// Single language pack to be installed synchronously. It should be reasonably quick and can be used for debugging, too.
core_php_time_limit::raise();
$controller->install_languagepacks($pack);
$controller->redirect($PAGE->url);
}
}
if ($mode == DELETION_OF_SELECTED_LANG and (!empty($uninstalllang) or !empty($confirmtounistall))) {
// Actually deleting languages, languages to delete are passed as GET parameter as string
// ...need to populate them to array.
if (empty($uninstalllang)) {
$uninstalllang = explode('/', $confirmtounistall);
}
if (in_array('en', $uninstalllang)) {
// TODO.
$controller->errors[] = get_string('noenglishuninstall', 'tool_langimport');
} else if (empty($confirmtounistall) and confirm_sesskey()) { // User chose langs to be deleted, show confirmation.
echo $OUTPUT->header();
echo $OUTPUT->confirm(get_string('uninstallconfirm', 'tool_langimport', implode(', ', $uninstalllang)),
new moodle_url($PAGE->url, array(
'mode' => DELETION_OF_SELECTED_LANG,
'confirmtouninstall' => implode('/', $uninstalllang),
)), $PAGE->url);
echo $OUTPUT->footer();
die;
} else if (confirm_sesskey()) { // Deleting languages.
foreach ($uninstalllang as $ulang) {
$controller->uninstall_language($ulang);
}
$controller->redirect($PAGE->url);
}
}
if ($mode == UPDATE_ALL_LANG && confirm_sesskey()) {
core_php_time_limit::raise();
$controller->update_all_installed_languages();
}
get_string_manager()->reset_caches();
$PAGE->set_primary_active_tab('siteadminnode');
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('langimport', 'tool_langimport'));
$installedlangs = get_string_manager()->get_list_of_translations(true);
$locale = new \tool_langimport\locale();
if ($availablelangs = $controller->availablelangs) {
$remote = true;
} else {
$remote = false;
$availablelangs = array();
$a = [
'src' => $controller->lang_pack_url(),
'dest' => $CFG->dataroot.'/lang/',
];
$errormessage = get_string('downloadnotavailable', 'tool_langimport', $a);
\core\notification::error($errormessage);
}
$missinglocales = '';
$missingparents = array();
foreach ($installedlangs as $installedlang => $langpackname) {
// Check locale availability.
if (!$locale->check_locale_availability($installedlang)) {
$missinglocales .= '<li>'.$langpackname.'</li>';
}
// This aligns the name of the language to match the available languages using
// both the name for the language and the localized name for the language.
$alang = array_filter($availablelangs, function($k) use ($installedlang) {
return $k[0] == $installedlang;
});
$alang = array_pop($alang);
if (!empty($alang[0]) and trim($alang[0]) !== 'en') {
$installedlangs[$installedlang] = $alang[2] . ' &lrm;(' . $alang[0] . ')&lrm;';
}
$parent = get_parent_language($installedlang);
if (empty($parent)) {
continue;
}
if (!isset($installedlangs[$parent])) {
$missingparents[$installedlang] = $parent;
}
}
if (!empty($missinglocales)) {
// There is at least one missing locale.
$a = new stdClass();
$a->globallocale = moodle_getlocale();
$a->missinglocales = $missinglocales;
$controller->errors[] = get_string('langunsupported', 'tool_langimport', $a);
}
if ($controller->info) {
$info = implode('<br />', $controller->info);
\core\notification::success($info);
}
if ($controller->errors) {
$info = implode('<br />', $controller->errors);
\core\notification::error($info);
}
// Inform about pending language packs installations.
foreach (\core\task\manager::get_adhoc_tasks('\tool_langimport\task\install_langpacks') as $installtask) {
$installtaskdata = $installtask->get_custom_data();
if (!empty($installtaskdata->langs)) {
\core\notification::info(get_string('installpending', 'tool_langimport', implode(', ', $installtaskdata->langs)));
}
}
if ($missingparents) {
foreach ($missingparents as $l => $parent) {
$a = new stdClass();
$a->lang = $installedlangs[$l];
$a->parent = $parent;
foreach ($availablelangs as $alang) {
if ($alang[0] == $parent) {
$shortlang = $alang[0];
$a->parent = $alang[2].' ('.$shortlang.')';
}
}
$info = get_string('missinglangparent', 'tool_langimport', $a);
\core\notification::error($info);
}
}
$uninstallurl = new moodle_url('/admin/tool/langimport/index.php', array('mode' => DELETION_OF_SELECTED_LANG));
$updateurl = null;
if ($remote) {
$updateurl = new moodle_url('/admin/tool/langimport/index.php', array('mode' => UPDATE_ALL_LANG));
}
$installurl = new moodle_url('/admin/tool/langimport/index.php', array('mode' => INSTALLATION_OF_SELECTED_LANG));
// List of available languages.
$options = array();
foreach ($availablelangs as $alang) {
if (!empty($alang[0]) and trim($alang[0]) !== 'en' and !$controller->is_installed_lang($alang[0], $alang[1])) {
$options[$alang[0]] = $alang[2].' &lrm;('.$alang[0].')&lrm;';
}
}
$renderable = new \tool_langimport\output\langimport_page($installedlangs, $options, $uninstallurl, $updateurl, $installurl);
$output = $PAGE->get_renderer('tool_langimport');
echo $output->render($renderable);
echo $OUTPUT->footer();
@@ -0,0 +1,59 @@
<?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/>.
/**
* Strings for component 'tool_langimport', language 'en', branch 'MOODLE_22_STABLE'
*
* @package tool
* @subpackage langimport
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['downloadnotavailable'] = 'Unable to connect to the download server. It is not possible to install or update the language packs automatically. Please download the appropriate ZIP file(s) from <a href="{$a->src}">{$a->src}</a> and unzip them manually to your data directory <code>{$a->dest}</code>';
$string['install'] = 'Install selected language pack(s)';
$string['installfailed'] = 'Language packs installation failed!';
$string['installfinished'] = 'Language packs installation finished.';
$string['installpending'] = 'The following language packs will be installed soon: {$a}.';
$string['installscheduled'] = 'Language packs scheduled for installation.';
$string['installedlangs'] = 'Installed language packs';
$string['langimport'] = 'Language import utility';
$string['langimportdisabled'] = 'Language import feature has been disabled. You have to update your language packs manually at the file-system level. Do not forget to purge string caches after you do so.';
$string['langpackinstalled'] = 'Language pack \'{$a}\' was successfully installed';
$string['langpackinstalledevent'] = 'Language pack installed';
$string['langpackremoved'] = 'Language pack \'{$a}\' was uninstalled';
$string['langpacknotremoved'] = 'An error has occurred; language pack \'{$a}\' is not completely uninstalled. Please check file permissions.';
$string['langpackremovedevent'] = 'Language pack uninstalled';
$string['langpackupdateskipped'] = 'Update of \'{$a}\' language pack skipped';
$string['langpackuptodate'] = 'Language pack \'{$a}\' is up-to-date';
$string['langpackupdated'] = 'Language pack \'{$a}\' was successfully updated';
$string['langpackupdatedevent'] = 'Language pack updated';
$string['langunsupported'] = '<p>Your server does not seem to fully support the following languages:</p><ul>{$a->missinglocales}</ul><p>Instead, the global locale ({$a->globallocale}) will be used to format certain strings such as dates or numbers.</p>';
$string['langupdatecomplete'] = 'Language pack update completed';
$string['missingcfglangotherroot'] = 'Missing configuration value $CFG->langotherroot';
$string['missinglangparent'] = 'Missing parent language <em>{$a->parent}</em> of <em>{$a->lang}</em>.';
$string['noenglishuninstalltitle'] = 'Unable to uninstall';
$string['noenglishuninstall'] = 'The English language pack cannot be uninstalled.';
$string['nolangupdateneeded'] = 'All your language packs are up to date, no update is needed';
$string['pluginname'] = 'Language packs';
$string['purgestringcaches'] = 'Purge string caches';
$string['search'] = 'Search available language packs';
$string['selectlangs'] = 'Select languages to uninstall';
$string['uninstall'] = 'Uninstall selected language pack(s)';
$string['uninstallconfirm'] = 'You are about to completely uninstall these language packs: <strong>{$a}</strong>. Are you sure?';
$string['updatelangs'] = 'Update all installed language packs';
$string['updatelangsnote'] = 'Updating all installed language packs by clicking the button can take a long time and lead to timeouts. It is recommended instead to make use of the scheduled task \'{$a->taskname}\' (which runs by default every day).';
$string['privacy:metadata'] = 'The Language packs plugin does not store any personal data.';
+59
View File
@@ -0,0 +1,59 @@
<?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/>.
/**
* Utility lang import functions.
*
* @package tool
* @subpackage langimport
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Called during upgrade, we need up-to-date lang pack
* because it may be used during upgrade...
*
* @param string $lang
* @return void
*/
function tool_langimport_preupgrade_update($lang) {
global $CFG, $OUTPUT;
require_once($CFG->libdir.'/componentlib.class.php');
echo $OUTPUT->heading(get_string('langimport', 'tool_langimport').': '.$lang);
@mkdir ($CFG->tempdir.'/'); //make it in case it's a fresh install, it might not be there
@mkdir ($CFG->dataroot.'/lang/');
$installer = new lang_installer($lang);
$results = $installer->run();
foreach ($results as $langcode => $langstatus) {
switch ($langstatus) {
case lang_installer::RESULT_DOWNLOADERROR:
echo $OUTPUT->notification($langcode . '.zip');
break;
case lang_installer::RESULT_INSTALLED:
echo $OUTPUT->notification(get_string('langpackinstalled', 'tool_langimport', $langcode), 'notifysuccess');
break;
case lang_installer::RESULT_UPTODATE:
echo $OUTPUT->notification(get_string('langpackuptodate', 'tool_langimport', $langcode), 'notifysuccess');
break;
}
}
}
+31
View File
@@ -0,0 +1,31 @@
<?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/>.
/**
* Lang import
*
* @package tool
* @subpackage langimport
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
if ($hassiteconfig) {
$ADMIN->add('language', new admin_externalpage('toollangimport', get_string('pluginname', 'tool_langimport'), "$CFG->wwwroot/$CFG->admin/tool/langimport/index.php"));
}
+10
View File
@@ -0,0 +1,10 @@
#page-admin-tool-langimport-index .langimport {
margin: auto;
float: none;
width: 100%;
}
#page-admin-tool-langimport-index #menuuninstalllang,
#page-admin-tool-langimport-index #menupack {
height: 300px;
}
@@ -0,0 +1,134 @@
{{!
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/>.
}}
{{!
@template tool_langimport/langimport
Template for the language import page.
Classes required for JS:
* none
Data attributes required for JS:
* none
Context variables required for this template:
* sesskey string The session key.
* uninstallurl string The URL for the uninstall action.
* updateurl string The URL for the update-language-packs action.
* installurl string The URL for the install action.
* installedoptions array The list of languages installed.
* toinstalloptions array The list of languages to be installed.
* caninstall boolean Flag to indicate if there are language packs that can be installed.
Example context (json):
{
"sesskey": "sesskey",
"uninstallurl": "#",
"updateurl": "#",
"installurl": "#",
"installedoptions": [
{
"value": "en",
"text": "English",
"selected": true
}
],
"toinstalloptions": [
{
"value": "ja",
"text": "Japanese"
},
{
"value": "fr",
"text": "French"
},
{
"value": "es",
"text": "Spanish"
}
],
"caninstall": true
}
}}
<div class="container-fluid langimport">
<div class="row rtl-compatible">
<div class="col-md-{{#caninstall}}6{{/caninstall}}{{^caninstall}}12{{/caninstall}} span{{#caninstall}}6{{/caninstall}}{{^caninstall}}12{{/caninstall}} mb-1">
<form id="uninstallform" action="{{uninstallurl}}" method="post">
<fieldset>
<div class="mb-3">
<label for="menuuninstalllang">{{#str}}installedlangs, tool_langimport{{/str}}</label>
<select size="15" multiple="multiple" id="menuuninstalllang" class="form-control input-block-level" name="uninstalllang[]">
{{#installedoptions}}
<option value="{{value}}" {{#selected}}selected="selected"{{/selected}}>{{{text}}}</option>
{{/installedoptions}}
</select>
</div>
<div class="mb-3">
<input type="hidden" name="sesskey" value="{{sesskey}}">
<input id="languninstallbutton" type="submit" value="{{#str}}uninstall, tool_langimport{{/str}}" class="btn btn-secondary">
</div>
</fieldset>
</form>
{{#updateurl}}
<div>
<form id="updateform" action="{{updateurl}}" method="post">
<fieldset>
<input type="hidden" name="sesskey" value="{{sesskey}}">
<input type="submit" value="{{#str}}updatelangs, tool_langimport{{/str}}" class="btn btn-secondary">
{{#hasmanyinstalledlanguages}}
<p class="mt-2 small">{{#str}} updatelangsnote, tool_langimport, {"taskname": {{#quote}}{{updatelangstaskname}}{{/quote}} }{{/str}}</p>
{{/hasmanyinstalledlanguages}}
</fieldset>
</form>
</div>
{{/updateurl}}
</div>
{{#caninstall}}
<div class="col-md-6 mb-1">
<form id="installform" action="{{installurl}}" method="post">
<fieldset>
<div class="mb-3">
<label for="menupack">{{#str}}availablelangs, install{{/str}}</label>
<select size="15" multiple="multiple" class="form-control input-block-level" id="menupack" name="pack[]">
{{#toinstalloptions}}
<option value="{{value}}" {{#selected}}selected="selected"{{/selected}}>{{{text}}}</option>
{{/toinstalloptions}}
</select>
</div>
<div class="mb-3">
{{< core/search_input_auto }}
{{$label}}
{{#str}} search, tool_langimport {{/str}}
{{/label}}
{{/ core/search_input_auto }}
</div>
<div class="mb-3">
<input type="hidden" name="sesskey" value="{{sesskey}}">
<input type="submit" value="{{#str}}install, tool_langimport{{/str}}" class="btn btn-secondary">
</div>
</fieldset>
</form>
</div>
{{/caninstall}}
</div>
</div>
{{#js}}
require(['tool_langimport/search', 'tool_langimport/uninstall'], function(search, uninstall) {
search.init(document.querySelector('#installform'));
uninstall.init(document.querySelector('#uninstallform'));
});
{{/js}}
@@ -0,0 +1,81 @@
<?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/>.
/**
* Behat steps definitions for Language import tool
*
* @package tool_langimport
* @category test
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
require_once(__DIR__ . '/../../../../../lib/behat/behat_base.php');
use Moodle\BehatExtension\Exception\SkippedException;
/**
* Steps definitions related with the Language import tool
*
* @package tool_langimport
* @category test
* @copyright 2014 Dan Poltawski <dan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class behat_tool_langimport extends behat_base {
/**
* This step looks to see if the remote language import tests should be run (indicated by
* setting TOOL_LANGIMPORT_REMOTE_TESTS in config.php.
*
* @Given /^remote langimport tests are enabled$/
*/
public function remote_langimport_tests_are_enabled() {
if (!defined('TOOL_LANGIMPORT_REMOTE_TESTS')) {
throw new SkippedException('To run the remote langimport tests you must '.
'define TOOL_LANGIMPORT_REMOTE_TESTS in config.php');
}
}
/**
* Downloads a langpack and fakes it being outdated
*
* @param string $langcode The language code (e.g. en)
* @Given /^outdated langpack \'([^\']*)\' is installed$/
*/
public function outdated_langpack_is_installed($langcode) {
global $CFG;
require_once($CFG->libdir.'/componentlib.class.php');
// Download the langpack.
$dir = make_upload_directory('lang');
$installer = new lang_installer($langcode);
$result = $installer->run();
if ($result[$langcode] !== lang_installer::RESULT_INSTALLED) {
throw new coding_exception("Failed to install langpack '$langcode'");
}
$path = "$dir/$langcode/$langcode.md5";
if (!file_exists($path)) {
throw new coding_exception("Failed to find '$langcode' checksum");
}
file_put_contents($path, '000000');
}
}
@@ -0,0 +1,88 @@
@tool @tool_langimport
Feature: Manage language packs
In order to support different languages
As an administrator
I need to be able to add, update and remove language packs
Background:
Given remote langimport tests are enabled
# The pirate language pack is used for testing because its small to download.
Scenario: Install language pack
Given I log in as "admin"
And I navigate to "Language > Language packs" in site administration
When I set the field "Available language packs" to "en_ar"
And I press "Install selected language pack(s)"
Then I should see "Language pack 'en_ar' was successfully installed"
And the "Installed language packs" select box should contain "en_ar"
And I navigate to "Reports > Live logs" in site administration
And I should see "The language pack 'en_ar' was installed."
Scenario: Install multiple language packs asynchronously in the background
Given I log in as "admin"
And I navigate to "Language > Language packs" in site administration
And I set the field "Available language packs" to "en_us,en_us_k12"
When I press "Install selected language pack(s)"
Then I should see "Language packs scheduled for installation."
And I should see "The following language packs will be installed soon: en_us, en_us_k12."
And I trigger cron
And I am on homepage
And I navigate to "Language > Language packs" in site administration
And the "Installed language packs" select box should contain "en_us"
And the "Installed language packs" select box should contain "en_us_k12"
And I navigate to "Reports > Live logs" in site administration
And I should see "The language pack 'en_us' was installed."
And I should see "The language pack 'en_us_k12' was installed."
@javascript
Scenario: Search for available language pack
Given I log in as "admin"
And I navigate to "Language > Language packs" in site administration
When I set the field "Search available language packs" to "pirate"
Then the "Available language packs" select box should not contain "es"
And I set the field "Available language packs" to "en_ar"
And I press "Install selected language pack(s)"
And I should see "Language pack 'en_ar' was successfully installed"
Scenario: Update language pack
Given outdated langpack 'en_ar' is installed
And I log in as "admin"
And I navigate to "Language > Language packs" in site administration
When I press "Update all installed language packs"
Then I should see "Language pack 'en_ar' was successfully updated"
And I should see "Language pack update completed"
And I navigate to "Reports > Live logs" in site administration
And I should see "The language pack 'en_ar' was updated."
Scenario: Inform admin that there are multiple installed languages and updating them all can take too long
Given outdated langpack 'en_ar' is installed
And outdated langpack 'en_us' is installed
And outdated langpack 'en_us_k12' is installed
When I log in as "admin"
And I navigate to "Language > Language packs" in site administration
Then I should see "Updating all installed language packs by clicking the button can take a long time and lead to timeouts."
Scenario: Try to uninstall language pack
Given I log in as "admin"
And I navigate to "Language > Language packs" in site administration
And I set the field "Available language packs" to "en_ar"
And I press "Install selected language pack(s)"
When I set the field "Installed language packs" to "en_ar"
And I press "Uninstall selected language pack(s)"
And I press "Continue"
Then I should see "Language pack 'en_ar' was uninstalled"
And the "Installed language packs" select box should not contain "en_ar"
And the "Available language packs" select box should contain "en_ar"
And I navigate to "Reports > Live logs" in site administration
And I should see "The language pack 'en_ar' was removed."
And I should see "Language pack uninstalled"
Scenario: Try to uninstall English language pack
Given I log in as "admin"
And I navigate to "Language > Language packs" in site administration
When I set the field "Installed language packs" to "en"
And I press "Uninstall selected language pack(s)"
Then I should see "The English language pack cannot be uninstalled."
And I navigate to "Reports > Live logs" in site administration
And I should not see "Language pack uninstalled"
@@ -0,0 +1,59 @@
<?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/>.
namespace tool_langimport;
/**
* Tests for \tool_langimport\locale class.
*
* @package tool_langimport
* @category test
* @coversDefaultClass \tool_langimport\controller
* @copyright 2023 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class controller_test extends \advanced_testcase {
/**
* Test uninstall of language with invalid values.
*
* @covers ::uninstall_lang
* @dataProvider uninstall_lang_invalid_provider
* @params string $lang
*/
public function test_uninstall_lang_invalid(string $lang): void {
global $CFG;
$controller = new controller();
$this->assertFalse($controller->uninstall_language($lang));
$this->assertFileExists("{$CFG->dataroot}/lang");
$this->assertFileExists("{$CFG->dirroot}/lang/en");
}
/**
* Data provider for uninstall_lang tests with invalid values.
*
* @return array
*/
public function uninstall_lang_invalid_provider(): array {
return [
'Empty string' => [''],
'Meaningless empty string' => [' '],
'Default language' => ['en'],
'Invalid language string' => ['swedish'],
];
}
}
@@ -0,0 +1,105 @@
<?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/>.
/**
* Tests for langimport events.
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
*/
namespace tool_langimport\event;
/**
* Test class for langimport events.
*
* @package tool_langimport
* @copyright 2014 Dan Poltawski
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
*/
class events_test extends \advanced_testcase {
/**
* Setup testcase.
*/
public function setUp(): void {
$this->setAdminUser();
$this->resetAfterTest();
}
public function test_langpack_updated(): void {
global $CFG;
$event = \tool_langimport\event\langpack_updated::event_with_langcode($CFG->lang);
// Trigger and capture the event.
$sink = $this->redirectEvents();
$event->trigger();
$events = $sink->get_events();
$event = reset($events);
$this->assertInstanceOf('\tool_langimport\event\langpack_updated', $event);
$this->assertEquals(\context_system::instance(), $event->get_context());
}
public function test_langpack_updated_validation(): void {
$this->expectException('coding_exception');
$this->expectExceptionMessage("The 'langcode' value must be set to a valid language code");
\tool_langimport\event\langpack_updated::event_with_langcode('broken langcode');
}
public function test_langpack_installed(): void {
$event = \tool_langimport\event\langpack_imported::event_with_langcode('fr');
// Trigger and capture the event.
$sink = $this->redirectEvents();
$event->trigger();
$events = $sink->get_events();
$event = reset($events);
$this->assertInstanceOf('\tool_langimport\event\langpack_imported', $event);
$this->assertEquals(\context_system::instance(), $event->get_context());
}
public function test_langpack_installed_validation(): void {
$this->expectException('coding_exception');
$this->expectExceptionMessage("The 'langcode' value must be set to a valid language code");
\tool_langimport\event\langpack_imported::event_with_langcode('broken langcode');
}
public function test_langpack_removed(): void {
$event = \tool_langimport\event\langpack_removed::event_with_langcode('fr');
// Trigger and capture the event.
$sink = $this->redirectEvents();
$event->trigger();
$events = $sink->get_events();
$event = reset($events);
$this->assertInstanceOf('\tool_langimport\event\langpack_removed', $event);
$this->assertEquals(\context_system::instance(), $event->get_context());
}
public function test_langpack_removed_validation(): void {
$this->expectException('coding_exception');
$this->expectExceptionMessage("The 'langcode' value must be set to a valid language code");
\tool_langimport\event\langpack_removed::event_with_langcode('broken langcode');
}
}
@@ -0,0 +1,87 @@
<?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/>.
namespace tool_langimport;
/**
* Tests for \tool_langimport\locale class.
*
* @package tool_langimport
* @category test
* @covers \tool_langimport\locale
* @copyright 2018 Université Rennes 2 {@link https://www.univ-rennes2.fr}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class locale_test extends \advanced_testcase {
/** @var string Locale */
protected string $locale;
#[\Override]
public function setUp(): void {
parent::setUp();
$this->locale = \core\locale::get_locale();
}
#[\Override]
public function tearDown(): void {
parent::tearDown();
\core\locale::set_locale(LC_ALL, $this->locale);
}
/**
* Test that \tool_langimport\locale::check_locale_availability() works as expected.
*/
public function test_check_locale_availability(): void {
// Create a mock of set_locale() method to simulate:
// - get_locale() call which backup current locale
// - first set_locale() call which try to set new 'es' locale
// - second set_locale() call which restore locale.
$mock = $this->getMockBuilder(locale::class)
->onlyMethods([
'get_locale',
'set_locale',
])
->getMock();
$mock->method('get_locale')->will($this->onConsecutiveCalls('en'));
$mock->method('set_locale')->will($this->onConsecutiveCalls('es', 'en'));
// Test what happen when locale is available on system.
$result = $mock->check_locale_availability('en');
$this->assertTrue($result);
// Create a mock of set_locale() method to simulate:
// - get_locale() call which backup current locale
// - first set_locale() call which fail to set new locale
// - second set_locale() call which restore locale.
$mock = $this->getMockBuilder(locale::class)
->onlyMethods([
'get_locale',
'set_locale',
])
->getMock();
$mock->method('get_locale')->will($this->onConsecutiveCalls('en'));
$mock->method('set_locale')->will($this->onConsecutiveCalls(false, 'en'));
// Test what happen when locale is not available on system.
$result = $mock->check_locale_availability('en');
$this->assertFalse($result);
// Test an invalid parameter.
$locale = new locale();
$this->expectException(\coding_exception::class);
$locale->check_locale_availability('');
}
}
+30
View File
@@ -0,0 +1,30 @@
<?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/>.
/**
* Version details.
*
* @package tool
* @subpackage langimport
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'tool_langimport'; // Full name of the plugin (used for diagnostics)