Fixed language settings. Changed wol link to ajax request for bible quotes

This commit is contained in:
PMKuipers 2023-11-20 10:53:48 +01:00
parent 5fe3baeb96
commit f1a994880d
11 changed files with 438 additions and 9 deletions

View File

@ -0,0 +1,3 @@
define("filter_bibleversesnwt/filter_bibleversesnwt",["exports","core/ajax","core/modal","core/modal_factory","core/modal_events","core/notification"],(function(_exports,_ajax,_modal,_modal_factory,_modal_events,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function bible_link(event){const target=event.target,info=JSON.parse(target.getAttribute("data-verseinfo")),bibleblock_heading=document.querySelector("#block_bibleblock_heading"),bibleblock_quote=document.querySelector("#block_bibleblock_content");return bibleblock_quote&&(bibleblock_heading&&(bibleblock_heading.innerHTML=""),bibleblock_quote.innerHTML='<div class="spinner-border text-info"></div>'),(0,_ajax.call)([{methodname:"filter_bibleversesnwt_get_biblequote",args:{lang:info.lang,book:info.book,ch:info.ch,verse:info.verse,book_end:info.book,ch_end:info.ch,verse_end:info.verse_end}}])[0].then((quote=>{var modalconfig;console.info("Got bible quote",quote),bibleblock_quote?(console.info("Attempting to place in verses block",bibleblock_heading,bibleblock_quote),bibleblock_heading&&(bibleblock_heading.innerHTML=quote.heading),bibleblock_quote.innerHTML=quote.quote):(console.info("Attempting to place in new modal"),(modalconfig={title:quote.heading,body:quote.quote},_modal.default.create?_modal.default.create(modalconfig):_modal_factory.default.create(modalconfig)).then((modal=>(modal.getRoot().on(_modal_events.default.hidden,(()=>{modal.destroy()})),modal.show(),modal))).catch(_notification.default.exception))})).catch((error=>{console.error("Error retrieving bible quote:",error),window.open(target.getAttribute("href"),"_bible_","width=500,height=800")})),event.preventDefault(),!1}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=function(){if(!initialized){initialized=!0;const elements=document.querySelectorAll("a.bible-link[data-verseinfo]");console.info("Found elements",elements),elements.forEach((el=>{console.info("Handling element",el),el.addEventListener("click",bible_link)}))}},_modal=_interopRequireDefault(_modal),_modal_factory=_interopRequireDefault(_modal_factory),_modal_events=_interopRequireDefault(_modal_events),_notification=_interopRequireDefault(_notification);let initialized=!1}));
//# sourceMappingURL=filter_bibleversesnwt.min.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,148 @@
/*eslint no-var: "error" */
/*eslint no-unused-vars: "off" */
/*eslint no-console: "off" */
/*eslint linebreak-style: "off" */
/*eslint no-trailing-spaces: "off" */
/*eslint-env es6*/
// Put this file in path/to/plugin/amd/src
// You can call it anything you like
import {call} from 'core/ajax';
import Modal from 'core/modal';
import ModalFactory from 'core/modal_factory';
import ModalEvents from 'core/modal_events';
import Notification from 'core/notification';
/**
*
* @param {*} modalconfig
* @returns Promise of modal
*/
function modalcreate(modalconfig) {
if(Modal.create) {
return Modal.create(modalconfig);
} else {
return ModalFactory.create(modalconfig);
}
}
/**
*
* @param {*} lang
* @param {*} book
* @param {*} ch
* @param {*} verse
* @param {*} book_end
* @param {*} ch_end
* @param {*} verse_end
*/
function getBibleQuote(lang,book,ch,verse,book_end, ch_end, verse_end) {
return new Promise((resolve, reject) => {
let range = "00000000";
let url = "";
range = book.toString() + ch.toString().padStart(3,'0') + verse.toString().padStart(3,'0');
if(book_end && ch_end && verse_end) {
range = range + "-" + book_end.toString() + ch_end.toString().padStart(3,'0') + verse_end.toString().padStart(3,'0');
}
if (lang == "nl") {
url = `https://www.jw.org/nl/bibliotheek/bijbel/nwt/boeken/json/html/${range}`;
} else { // if $lang == 'en'
url = `https://www.jw.org/en/library/bible/nwt/books/json/html/${range}`;
}
window.fetch(url).then((response) => {
try {
const o = JSON.parse();
resolve(o.ranges[range]);
} catch (error) {
reject("Error parsing json response",error, response);
}
}).catch((error) => {
reject("Error retrieving url",error);
});
});
}
/**
*
* @param {*} event
*/
function bible_link(event) {
const target = event.target;
const info = JSON.parse(target.getAttribute("data-verseinfo"));
const bibleblock_heading = document.querySelector("#block_bibleblock_heading");
const bibleblock_quote = document.querySelector("#block_bibleblock_content");
if( bibleblock_quote ) {
if(bibleblock_heading) {
bibleblock_heading.innerHTML = "";
}
bibleblock_quote.innerHTML = `<div class="spinner-border text-info"></div>`;
}
call([{
methodname: 'filter_bibleversesnwt_get_biblequote',
args: {
lang: info.lang,
book: info.book,
ch: info.ch,
verse: info.verse,
book_end: info.book,
ch_end: info.ch,
verse_end: info.verse_end}
}])[0].then((quote) => {
console.info("Got bible quote",quote);
if( bibleblock_quote ) {
console.info("Attempting to place in verses block",bibleblock_heading,bibleblock_quote);
if(bibleblock_heading) {
bibleblock_heading.innerHTML = quote.heading;
}
bibleblock_quote.innerHTML = quote.quote;
} else {
console.info("Attempting to place in new modal",);
modalcreate({
title: quote.heading,
body: quote.quote,
}).then(modal => {
// Handle hidden event.
modal.getRoot().on(ModalEvents.hidden, () => {
// Destroy when hidden.
modal.destroy();
});
// Show the modal.
modal.show();
return modal;
})
.catch(Notification.exception);
}
}).catch((error) => {
console.error("Error retrieving bible quote:", error);
window.open(target.getAttribute("href"),"_bible_","width=500,height=800");
});
event.preventDefault();
return false;
}
/**
*
*/
let initialized = false;
/**
* Initialize the Page
*/
export function init() {
// Make sure this function is only called once on the page. May be called multiple times because of filter weirdness
if (!initialized) {
initialized = true;
const elements = document.querySelectorAll("a.bible-link[data-verseinfo]");
console.info("Found elements",elements);
elements.forEach((el) => {
console.info("Handling element",el);
el.addEventListener("click", bible_link);
});
}
}

76
build.php Normal file
View File

@ -0,0 +1,76 @@
<?php
// This file is part of the Studyplan plugin for Moodle
//
// 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/>.
/**
* Build script to properly create a distribution zip
* @package block_mytreestudyplan
* @copyright 2023 P.M. Kuipers
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('CLI_SCRIPT', true);
require_once("../../config.php");
$plugin = new stdClass;
require_once('version.php');
$a = explode("_", $plugin->component, 2);
$plugin->type = $a[0];
$plugin->name = $a[1];
$excludepaths = [
"build", // Dir for build zip files.
"build/*",
"build.*",
"vuemode.sh",
"amd/src",
"amd/src/*",
".git",
".git/*",
".gitignore",
"*.zip",
];
// Determine some paths.
$wd = realpath(dirname(__FILE__));
$parent = dirname($wd);
$plugindirname = basename($wd);
$builddir = $wd."/"."build";
$zipname = $builddir."/"."{$plugin->name}-{$plugin->version}.zip";
// Create the exclude line.
$exclude = "-x ";
foreach ($excludepaths as $x) {
$exclude .= "'{$plugindirname}/{$x}' ";
}
if (!is_dir($builddir)) {
mkdir($builddir);
if (!is_dir($builddir)) {
print("Cannot access dir '{$builddir}' to store zip files\n");
exit(1);
}
}
if (file_exists($zipfile)) {
print("Zip file '{$zipfile}' already exists. Exiting...\n");
exit(1);
}
$cwd = getcwd();
chdir($parent);
$cmd = "zip -r '{$zipname}' '{$plugindirname}' {$exclude}";
system($cmd);
chdir($cwd);

14
build.sh Executable file
View File

@ -0,0 +1,14 @@
#!/bin/bash
SCRIPTDIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
WD=`pwd`
# run the grunt script in the scripts working directory
cd $SCRIPTDIR
grunt amd
# run the build php script
php ${SCRIPTDIR}/build.php $@
# return to the working directory
cd $WD

View File

@ -23,10 +23,10 @@ class bible {
$verse_end = ($verse_end > $verse)?$verse_end:$verse;
if($this->lang == "nl"){
return "https://wol.jw.org/nl/wol/b/r18/lp-o/nwtsty/${book}/${chapter}#v=${book}:${chapter}:${verse}-${book}:${chapter}:${verse_end}";
return "https://wol.jw.org/nl/wol/b/r18/lp-o/nwtsty/{$book}/{$chapter}#v={$book}:{$chapter}:{$verse}-{$book}:{$chapter}:{$verse_end}";
}
else { // if $this->lang == 'en'
return "https://wol.jw.org/nl/wol/b/r1/lp-e/nwtsty/${book}/${chapter}#v=${book}:${chapter}:${verse}-${book}:${chapter}:${verse_end}";
return "https://wol.jw.org/nl/wol/b/r1/lp-e/nwtsty/{$book}/{$chapter}#v={$book}:{$chapter}:{$verse}-{$book}:{$chapter}:{$verse_end}";
}
}
@ -190,15 +190,17 @@ class bible {
// First check the presence of the bookname before
if( ($ix = stripos($content,$bookname)) !== false){
$matches = [];
$content = preg_replace_callback($re,function ($m) use ($booknum, $bookname){
$lang = $this->lang;
$content = preg_replace_callback($re,function ($m) use ($lang,$booknum, $bookname){
$book = strtolower(trim($m[1]));
$ch = $m[2];
$verse = $m[3];
$verse_to = (count($m)>4)?$m[4]:0;
if($book == $bookname){ // Check if name matches
$href = $this->wolhref($booknum,$ch,$verse,$verse_to);
return "<a href='{$href}' onclick='window.open(\"{$href}\",\"_bible_\",\"width=500,height=800\"); return false;' target='_bible_' class='bible-link'>".$m[0]."</a>";
$href = $this->wolhref($lang, $booknum, $ch, $verse, $verse_to);
$versedata = json_encode(["lang" => $lang, "book" => $booknum, "ch" => $ch, "verse" => $verse, "verse_end" => $verse_to, "wolhref" => $href]);
return "<a href='{$href}' data-verseinfo='{$versedata}' target='_bible_' class='bible-link'>".$m[0]."</a>";
} else {
return $m[0];
}

97
classes/bibleservice.php Normal file
View File

@ -0,0 +1,97 @@
<?php
// This file is part of the Studyplan plugin for Moodle
//
// 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/>.
/**
* Webservice class for handling associations of cohorts and users to a studyplan
* @package filter_bibleversesnwt
* @copyright 2023 P.M. Kuipers
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace filter_bibleversesnwt;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/externallib.php');
/**
* Webservice class for handling associations of cohorts and users to a studyplan
*/
class bibleservice extends \external_api {
/**
* Parameter description for webservice function list_cohort
*/
public static function get_biblequote_parameters() : \external_function_parameters {
return new \external_function_parameters( [
'lang' => new \external_value(PARAM_TEXT, 'language code'),
'book' => new \external_value(PARAM_INT, 'bible book nr'),
'ch' => new \external_value(PARAM_INT, 'chapter number'),
'verse' => new \external_value(PARAM_INT, 'verse number'),
'book_end' => new \external_value(PARAM_INT, 'end bible book nr', VALUE_OPTIONAL),
'ch_end' => new \external_value(PARAM_INT, 'end chapter number', VALUE_OPTIONAL),
'verse_end' => new \external_value(PARAM_INT, 'end verse number', VALUE_OPTIONAL),
] );
}
/**
* Return value description for webservice function list_cohort
*/
public static function get_biblequote_returns() : \external_description {
return new \external_single_structure([
"heading" => new \external_value(PARAM_RAW, 'heading'),
"quote" => new \external_value(PARAM_RAW, 'quote'),
]);
}
/**
* Search cohorts for matching string
* @param string $like String to match cohorts with
* @param null $excludeid Do not include these cohorts
* @param int $contextid Context to search (default system)
* @return array
*/
public static function get_biblequote($lang,$book,$ch,$verse,$book_end = null,$ch_end = null,$verse_end = null) {
$range = $book .str_pad($ch,3,'0',STR_PAD_LEFT) . str_pad($verse,3,'0',STR_PAD_LEFT);
if(!empty($book_end) && !empty($ch_end) && !empty($verse_end)) {
$range .= "-" . $book_end .str_pad($ch_end,3,'0',STR_PAD_LEFT) . str_pad($verse_end,3,'0',STR_PAD_LEFT);
}
if ($lang == "nl") {
$url = "https://www.jw.org/nl/bibliotheek/bijbel/nwt/boeken/json/html/{$range}";
} else { // if $lang == 'en'
$url = "https://www.jw.org/en/library/bible/nwt/books/json/html/{$range}";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
$result = curl_exec($ch);
$o = json_decode($result,true);
if(isset($o["ranges"]) && isset($o["ranges"][$range])) {
$r = $o["ranges"][$range];
return [
"heading" => $r["citation"],
"quote" => preg_replace('#<a.*?>(.*?)</a>#i', '\1', $r["html"]),
];
} else {
throw new \moodle_exception("Unexpected JSON code",'','',null,$result);
}
}
}

43
db/services.php Normal file
View File

@ -0,0 +1,43 @@
<?php
// This file is part of the Studyplan plugin for Moodle
//
// 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/>.
/**
* Webservice function register
* @package local_treestudyplan
* @copyright 2023 P.M. Kuipers
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$services = [
];
$functions = [
/***************************
* Studyplan functions
***************************/
'filter_bibleversesnwt_get_biblequote' => [ // Web service function name.
'classname' => '\filter_bibleversesnwt\bibleservice', // Class containing the external function.
'methodname' => 'get_biblequote', // External function name.
'description' => 'Get bible quote',
'type' => 'read', // Database rights of the web service function (read, write).
'ajax' => true,
'capabilities' => '',
'loginrequired' => true,
],
];

View File

@ -25,10 +25,37 @@
use filter_bibleversesnwt\bible;
class filter_bibleversesnwt extends moodle_text_filter {
private $courseconfig;
private $adminconfig;
public function setup($page, $context) {
$page->requires->js_call_amd('filter_bibleversesnwt/filter_bibleversesnwt','init', []);
}
private function fetch_prop($prop,$default){
global $COURSE;
if ($this->localconfig && !empty($this->localconfig)) {
$this->courseconfig = $this->localconfig;
}
if (!$this->courseconfig) {
$this->courseconfig = filter_get_local_config('bibleversesnwt', context_course::instance($COURSE->id)->id);
}
if ($this->courseconfig && isset($this->courseconfig[$prop])) {
return $this->courseconfig[$prop];
} else {
if(!$this->adminconfig) {
$this->adminconfig =get_config('filter_bibleversesnwt');
}
return isset($this->adminconfig->{$prop}) ? $this->adminconfig->{$prop} : $default;
}
}
function filter($text, array $options = []) {
// Return the modified text.
// return print_r($options,true).$text; // Debug to check content of options
$bible = new bible("nl");
$lang = $this->fetch_prop('biblelang','nl');
$bible = new bible($lang);
return $bible->parse($text);
}

View File

@ -2,10 +2,28 @@
use filter_bibleversesnwt\bible;
class bibleversesnwt_filter_local_settings_form extends filter_local_settings_form {
protected function definition_inner($mform) {
$mform->addElement('select', 'biblelang', get_string('biblelang', 'filter_bibleversesnwt'), bible::languages());
$mform->setType('biblelang', PARAM_NOTAGS);
}
/**
* Override this method to save the settings to the database. The default
* implementation will probably be sufficient for most simple cases.
* @param object $data the form data that was submitted.
*/
public function save_changes($data) {
$data = (array) $data;
unset($data['filter']);
unset($data['contextid']);
unset($data['submitbutton']);
foreach ($data as $name => $value) {
if ($value !== '') {
filter_set_local_config($this->filter, $this->context->id, $name, $value);
} else {
filter_unset_local_config($this->filter, $this->context->id, $name);
}
}
}
}

View File

@ -24,7 +24,7 @@
defined('MOODLE_INTERNAL') || die();
$plugin->version = 20230525;
$plugin->version = 2023112000;
$plugin->requires = 2021051700; // YYYYMMDDHH (This is the release version for Moodle 3.11)
$plugin->component = 'filter_bibleversesnwt';
$plugin->maturity = MATURITY_STABLE;