From 4ec659dd0d98137884e4e26357333795f64c0223 Mon Sep 17 00:00:00 2001 From: justinhunt Date: Thu, 18 Jul 2019 13:55:05 +0900 Subject: [PATCH] fixed issue with cloudpoodlltoken and a general code tidy up --- CHANGES.txt | 4 + amd/src/generico_amd.js | 177 ++--- amd/src/generico_presets_amd.js | 352 ++++----- classes/constants.php | 6 +- classes/generico_utils.php | 181 +++-- classes/presets_control.php | 152 ++-- classes/privacy/provider.php | 2 +- classes/settingstools.php | 406 +++++----- classes/template_script_generator.php | 137 ++-- classes/templateadmintools.php | 90 ++- db/install.php | 22 +- db/upgrade.php | 47 +- filter.php | 1040 +++++++++++++------------ genericocss.php | 8 +- genericojs.php | 7 +- genericotemplatesadmin.php | 27 +- lang/en/filter_generico.php | 59 +- lib.php | 21 +- module.js | 116 +-- poodllloader.html | 31 +- refreshtoken.php | 13 +- settings.php | 60 +- styles.css | 14 +- version.php | 8 +- 24 files changed, 1499 insertions(+), 1481 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 99075b4..a0fd334 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,5 +1,9 @@ Change List ========= + +Version 1.4.10(Build 2019071300) +-Fixed cloud poodll token fetch [again] + Version 1.4.09(Build 2019061400) -Fixed cloud poodll token fetch (had been requiring Poodll) -Added cloud poodll refresh diff --git a/amd/src/generico_amd.js b/amd/src/generico_amd.js index 8127615..6ea61ff 100644 --- a/amd/src/generico_amd.js +++ b/amd/src/generico_amd.js @@ -1,91 +1,92 @@ /* jshint ignore:start */ -define(['jquery','core/log'], function($, log) { - - "use strict"; // jshint ;_; - - log.debug('Filter Generico initialising'); - - return { - - allopts: {}, - - extscripts: {}, - - csslinks: Array(), - - jslinks: Array(), - - appendjspath: function(jslink, theprefix){ - require.config({ - paths: { - theprefix: jslink - }}); - }, - - injectcss: function(csslink){ - var link = document.createElement("link"); - link.href = csslink; - if(csslink.toLowerCase().lastIndexOf('.html')==csslink.length-5){ - link.rel = 'import'; - }else{ - link.type = "text/css"; - link.rel = "stylesheet"; - } - document.getElementsByTagName("head")[0].appendChild(link); - }, - - // load all generico stuff and stash all our variables - loadgenerico: function(opts) { - - - //pick up opts from html - var theid = '#filter_generico_amdopts_' + opts['AUTOID']; - var optscontrol = $(theid).get(0); - if(optscontrol){ - opts = JSON.parse(optscontrol.value); - //remove the hidden form element, in case it is really part of a form - $(theid).remove(); - } - log.debug(opts); - - //load our css in head if required - //only do it once per extension though - if(opts['CSSLINK']){ - if (this.csslinks.indexOf(opts['CSSLINK'])<0){ - this.csslinks.push(opts['CSSLINK']); - this.injectcss(opts['CSSLINK']); - } - } - //load our css in head if required - //only do it once per extension though - if(opts['CSSUPLOAD']){ - if (this.csslinks.indexOf(opts['CSSUPLOAD'])<0){ - this.csslinks.push(opts['CSSUPLOAD']); - this.injectcss(opts['CSSUPLOAD']); - } - } - - //load our css in head if required - //only do it once per extension though - if(opts['CSSCUSTOM']){ - if (this.csslinks.indexOf(opts['CSSCUSTOM'])<0){ - this.csslinks.push(opts['CSSCUSTOM']); - this.injectcss(opts['CSSCUSTOM']); - } - } - - //if we did get a template id then proceed - //we might not get one if the html was generated, but never sent to - //the page. Sometimes this happens in the assignment and probably - //elsewhere - if(typeof opts['TEMPLATEID'] != 'undefined'){ - //here require, then load the template scripts and js - require(['filter_generico_d' + opts['TEMPLATEID']],function(d){ - d(opts); - }); - } - }//end of function - - } +define(['jquery', 'core/log'], function ($, log) { + + "use strict"; // jshint ;_; + + log.debug('Filter Generico initialising'); + + return { + + allopts: {}, + + extscripts: {}, + + csslinks: Array(), + + jslinks: Array(), + + appendjspath: function (jslink, theprefix) { + require.config({ + paths: { + theprefix: jslink + } + }); + }, + + injectcss: function (csslink) { + var link = document.createElement("link"); + link.href = csslink; + if (csslink.toLowerCase().lastIndexOf('.html') == csslink.length - 5) { + link.rel = 'import'; + } else { + link.type = "text/css"; + link.rel = "stylesheet"; + } + document.getElementsByTagName("head")[0].appendChild(link); + }, + + // load all generico stuff and stash all our variables + loadgenerico: function (opts) { + + + //pick up opts from html + var theid = '#filter_generico_amdopts_' + opts['AUTOID']; + var optscontrol = $(theid).get(0); + if (optscontrol) { + opts = JSON.parse(optscontrol.value); + //remove the hidden form element, in case it is really part of a form + $(theid).remove(); + } + log.debug(opts); + + //load our css in head if required + //only do it once per extension though + if (opts['CSSLINK']) { + if (this.csslinks.indexOf(opts['CSSLINK']) < 0) { + this.csslinks.push(opts['CSSLINK']); + this.injectcss(opts['CSSLINK']); + } + } + //load our css in head if required + //only do it once per extension though + if (opts['CSSUPLOAD']) { + if (this.csslinks.indexOf(opts['CSSUPLOAD']) < 0) { + this.csslinks.push(opts['CSSUPLOAD']); + this.injectcss(opts['CSSUPLOAD']); + } + } + + //load our css in head if required + //only do it once per extension though + if (opts['CSSCUSTOM']) { + if (this.csslinks.indexOf(opts['CSSCUSTOM']) < 0) { + this.csslinks.push(opts['CSSCUSTOM']); + this.injectcss(opts['CSSCUSTOM']); + } + } + + //if we did get a template id then proceed + //we might not get one if the html was generated, but never sent to + //the page. Sometimes this happens in the assignment and probably + //elsewhere + if (typeof opts['TEMPLATEID'] != 'undefined') { + //here require, then load the template scripts and js + require(['filter_generico_d' + opts['TEMPLATEID']], function (d) { + d(opts); + }); + } + }//end of function + + } }); /* jshint ignore:end */ \ No newline at end of file diff --git a/amd/src/generico_presets_amd.js b/amd/src/generico_presets_amd.js index d46ce24..226e680 100644 --- a/amd/src/generico_presets_amd.js +++ b/amd/src/generico_presets_amd.js @@ -1,177 +1,181 @@ /* jshint ignore:start */ -define(['jquery','core/log'], function($, log) { - - "use strict"; // jshint ;_; - - log.debug('Filter Generico Presets initialising'); - - return { - - presetdata: false, - - dataitems: ['key','name', 'instructions','requirecss', 'requirejs','shim', 'defaults', - 'amd', 'body', 'bodyend', 'script', 'style','dataset','datasetvars','alternate','alternateend','version'], - - fetchcontrols: function(templateindex) { - var controls = {}; - controls.key = document.getElementById('id_s_filter_generico_templatekey_' + templateindex); - controls.name = document.getElementById('id_s_filter_generico_templatename_' + templateindex); - controls.instructions = document.getElementById('id_s_filter_generico_templateinstructions_' + templateindex); - controls.requirecss = document.getElementById('id_s_filter_generico_templaterequire_css_' + templateindex); - controls.requirejs = document.getElementById('id_s_filter_generico_templaterequire_js_' + templateindex); - controls.shim = document.getElementById('id_s_filter_generico_templaterequire_js_shim_' + templateindex); - controls.defaults = document.getElementById('id_s_filter_generico_templatedefaults_' + templateindex); - controls.amd = document.getElementById('id_s_filter_generico_template_amd_' + templateindex); - controls.body = document.getElementById('id_s_filter_generico_template_' + templateindex); - controls.bodyend = document.getElementById('id_s_filter_generico_templateend_' + templateindex); - controls.script = document.getElementById('id_s_filter_generico_templatescript_' + templateindex); - controls.style = document.getElementById('id_s_filter_generico_templatestyle_' + templateindex); - controls.dataset = document.getElementById('id_s_filter_generico_dataset_' + templateindex); - controls.datasetvars = document.getElementById('id_s_filter_generico_datasetvars_' + templateindex); - controls.alternate = document.getElementById('id_s_filter_generico_templatealternate_' + templateindex); - controls.alternateend = document.getElementById('id_s_filter_generico_templatealternate_end_' + templateindex); - controls.presetdata = document.getElementById('id_s_filter_generico_presetdata_' + templateindex); - controls.version = document.getElementById('id_s_filter_generico_templateversion_' + templateindex); - return controls; - }, - - fetchjsonbundle: function(templateindex, controls){ - var bundle={}; - $.each(this.dataitems, - function (index, item) { - bundle[item] =controls[item].value; - } - ); - var jsonbundle = JSON.stringify(bundle); - return jsonbundle; - window.open("data:text/json;charset=utf-8," + encodeURIComponent(bundlejson)); - }, - - exportbundle: function(templateindex){ - var controls = this.fetchcontrols(templateindex); - if(controls.key.value==''){return;} - var jsonbundle = this.fetchjsonbundle(templateindex,controls); - - var pom = document.createElement('a'); - pom.setAttribute('href', "data:text/json;charset=utf-8," + encodeURIComponent(jsonbundle)); - pom.setAttribute('download', controls['key'].value + '.txt'); - - if (document.createEvent) { - var event = document.createEvent('MouseEvents'); - event.initEvent('click', true, true); - pom.dispatchEvent(event); - } - else { - pom.click(); - } - }, - - populateform: function (templateindex, presetindex, presetdata) { - //get all our html controls - var controls = this.fetchcontrols(templateindex); - - //what a rip off there was no selection!!! - if(!presetindex && !presetdata){return;} - if(presetindex==0 && presetdata){ - //this is good, we have something from dopopulate - }else{ - //this is a normal selection - presetdata =this.presetdata; - } - - $.each(this.dataitems, - function (index, item) { - // log.debug(item + ':' + presetindex + ':' + presetdata[presetindex][item]); - //first check we have a data item for this control(old bundles don't have instructions or new fields etc) - //then set the data - if (presetdata[presetindex].hasOwnProperty(item)) { - controls[item].value = presetdata[presetindex][item]; - }else{ - switch(item){ - case 'amd': - controls[item].value =0; - break; - default: - controls[item].value =''; - } - } - } - ); - - }, - - dopopulate: function(templateindex, templatedata){ - this.populateform(templateindex,0,new Array(templatedata)); - }, - - // load all generico stuff and stash all our variables - init: function(opts) { - if (!this.presetdata) { - var controlid='#id_s_filter_generico_presetdata_' + opts['templateindex']; - var presetcontrol=$(controlid).get(0); - this.presetdata = JSON.parse(presetcontrol.value); - $(controlid).remove(); - } - - var amdpresets = this; - //handle the select box change event - $("select[name='filter_generico/presets']").change(function(){ - amdpresets.populateform(opts['templateindex'],$(this).val()); - }); - - //drag drop square events - var ddsquareid='#id_s_filter_generico_dragdropsquare_' + opts['templateindex'] - - //export the current bundle - $(ddsquareid).on("click", function(event) { - amdpresets.exportbundle(opts['templateindex']); - }); - - - //handle the drop event. First cancel dragevents which prevent drop firing - $(ddsquareid).on("dragover", function(event) { - event.preventDefault(); - event.stopPropagation(); - $(this).addClass('filter_generico_dragging'); - }); - - $(ddsquareid).on("dragleave", function(event) { - event.preventDefault(); - event.stopPropagation(); - $(this).removeClass('filter_generico_dragging'); - }); - - $(ddsquareid).on('drop', function(event) { - - //stop the browser from opening the file - event.preventDefault(); - //Now we need to get the files that were dropped - //The normal method would be to use event.dataTransfer.files - //but as jquery creates its own event object you ave to access - //the browser even through originalEvent. which looks like this - var files = event.originalEvent.dataTransfer.files; - - //if we have files, read and process them - if(files.length){ - var f = files[0]; - if (f) { - var r = new FileReader(); - r.onload = function(e) { - var contents = e.target.result; - var templatedata = JSON.parse(contents); - if(templatedata.key){ - amdpresets.dopopulate(opts['templateindex'],templatedata); - } - } - r.readAsText(f); - } else { - alert("Failed to load file"); - }//end of if f - }//end of if files - $(this).removeClass('filter_generico_dragging'); - }); - }//end of function - - } +define(['jquery', 'core/log'], function ($, log) { + + "use strict"; // jshint ;_; + + log.debug('Filter Generico Presets initialising'); + + return { + + presetdata: false, + + dataitems: ['key', 'name', 'instructions', 'requirecss', 'requirejs', 'shim', 'defaults', + 'amd', 'body', 'bodyend', 'script', 'style', 'dataset', 'datasetvars', 'alternate', 'alternateend', 'version'], + + fetchcontrols: function (templateindex) { + var controls = {}; + controls.key = document.getElementById('id_s_filter_generico_templatekey_' + templateindex); + controls.name = document.getElementById('id_s_filter_generico_templatename_' + templateindex); + controls.instructions = document.getElementById('id_s_filter_generico_templateinstructions_' + templateindex); + controls.requirecss = document.getElementById('id_s_filter_generico_templaterequire_css_' + templateindex); + controls.requirejs = document.getElementById('id_s_filter_generico_templaterequire_js_' + templateindex); + controls.shim = document.getElementById('id_s_filter_generico_templaterequire_js_shim_' + templateindex); + controls.defaults = document.getElementById('id_s_filter_generico_templatedefaults_' + templateindex); + controls.amd = document.getElementById('id_s_filter_generico_template_amd_' + templateindex); + controls.body = document.getElementById('id_s_filter_generico_template_' + templateindex); + controls.bodyend = document.getElementById('id_s_filter_generico_templateend_' + templateindex); + controls.script = document.getElementById('id_s_filter_generico_templatescript_' + templateindex); + controls.style = document.getElementById('id_s_filter_generico_templatestyle_' + templateindex); + controls.dataset = document.getElementById('id_s_filter_generico_dataset_' + templateindex); + controls.datasetvars = document.getElementById('id_s_filter_generico_datasetvars_' + templateindex); + controls.alternate = document.getElementById('id_s_filter_generico_templatealternate_' + templateindex); + controls.alternateend = document.getElementById('id_s_filter_generico_templatealternate_end_' + templateindex); + controls.presetdata = document.getElementById('id_s_filter_generico_presetdata_' + templateindex); + controls.version = document.getElementById('id_s_filter_generico_templateversion_' + templateindex); + return controls; + }, + + fetchjsonbundle: function (templateindex, controls) { + var bundle = {}; + $.each(this.dataitems, + function (index, item) { + bundle[item] = controls[item].value; + } + ); + var jsonbundle = JSON.stringify(bundle); + return jsonbundle; + window.open("data:text/json;charset=utf-8," + encodeURIComponent(bundlejson)); + }, + + exportbundle: function (templateindex) { + var controls = this.fetchcontrols(templateindex); + if (controls.key.value == '') { + return; + } + var jsonbundle = this.fetchjsonbundle(templateindex, controls); + + var pom = document.createElement('a'); + pom.setAttribute('href', "data:text/json;charset=utf-8," + encodeURIComponent(jsonbundle)); + pom.setAttribute('download', controls['key'].value + '.txt'); + + if (document.createEvent) { + var event = document.createEvent('MouseEvents'); + event.initEvent('click', true, true); + pom.dispatchEvent(event); + } + else { + pom.click(); + } + }, + + populateform: function (templateindex, presetindex, presetdata) { + //get all our html controls + var controls = this.fetchcontrols(templateindex); + + //what a rip off there was no selection!!! + if (!presetindex && !presetdata) { + return; + } + if (presetindex == 0 && presetdata) { + //this is good, we have something from dopopulate + } else { + //this is a normal selection + presetdata = this.presetdata; + } + + $.each(this.dataitems, + function (index, item) { + // log.debug(item + ':' + presetindex + ':' + presetdata[presetindex][item]); + //first check we have a data item for this control(old bundles don't have instructions or new fields etc) + //then set the data + if (presetdata[presetindex].hasOwnProperty(item)) { + controls[item].value = presetdata[presetindex][item]; + } else { + switch (item) { + case 'amd': + controls[item].value = 0; + break; + default: + controls[item].value = ''; + } + } + } + ); + + }, + + dopopulate: function (templateindex, templatedata) { + this.populateform(templateindex, 0, new Array(templatedata)); + }, + + // load all generico stuff and stash all our variables + init: function (opts) { + if (!this.presetdata) { + var controlid = '#id_s_filter_generico_presetdata_' + opts['templateindex']; + var presetcontrol = $(controlid).get(0); + this.presetdata = JSON.parse(presetcontrol.value); + $(controlid).remove(); + } + + var amdpresets = this; + //handle the select box change event + $("select[name='filter_generico/presets']").change(function () { + amdpresets.populateform(opts['templateindex'], $(this).val()); + }); + + //drag drop square events + var ddsquareid = '#id_s_filter_generico_dragdropsquare_' + opts['templateindex'] + + //export the current bundle + $(ddsquareid).on("click", function (event) { + amdpresets.exportbundle(opts['templateindex']); + }); + + + //handle the drop event. First cancel dragevents which prevent drop firing + $(ddsquareid).on("dragover", function (event) { + event.preventDefault(); + event.stopPropagation(); + $(this).addClass('filter_generico_dragging'); + }); + + $(ddsquareid).on("dragleave", function (event) { + event.preventDefault(); + event.stopPropagation(); + $(this).removeClass('filter_generico_dragging'); + }); + + $(ddsquareid).on('drop', function (event) { + + //stop the browser from opening the file + event.preventDefault(); + //Now we need to get the files that were dropped + //The normal method would be to use event.dataTransfer.files + //but as jquery creates its own event object you ave to access + //the browser even through originalEvent. which looks like this + var files = event.originalEvent.dataTransfer.files; + + //if we have files, read and process them + if (files.length) { + var f = files[0]; + if (f) { + var r = new FileReader(); + r.onload = function (e) { + var contents = e.target.result; + var templatedata = JSON.parse(contents); + if (templatedata.key) { + amdpresets.dopopulate(opts['templateindex'], templatedata); + } + } + r.readAsText(f); + } else { + alert("Failed to load file"); + }//end of if f + }//end of if files + $(this).removeClass('filter_generico_dragging'); + }); + }//end of function + + } }); /* jshint ignore:end */ \ No newline at end of file diff --git a/classes/constants.php b/classes/constants.php index 96d6516..e506917 100644 --- a/classes/constants.php +++ b/classes/constants.php @@ -8,8 +8,6 @@ namespace filter_generico; - -class constants -{ - const MOD_FRANKY='filter_generico'; +class constants { + const MOD_FRANKY = 'filter_generico'; } \ No newline at end of file diff --git a/classes/generico_utils.php b/classes/generico_utils.php index 091e332..30244f2 100644 --- a/classes/generico_utils.php +++ b/classes/generico_utils.php @@ -21,14 +21,12 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - namespace filter_generico; defined('MOODLE_INTERNAL') || die; -class generico_utils -{ - const FILTER_GENERICO_TEMPLATE_COUNT = 20; +class generico_utils { + const FILTER_GENERICO_TEMPLATE_COUNT = 20; const CLOUDPOODLL_VAL_BY_REGCODE = 1; const CLOUDPOODLL_VAL_BY_APICREDS = 2; @@ -36,9 +34,8 @@ class generico_utils const CLOUDPOODLL_IS_UNREGISTERED = 0; const CLOUDPOODLL_IS_EXPIRED = 2; - - public static function fetch_emptyproparray(){ - $proparray=array(); + public static function fetch_emptyproparray() { + $proparray = array(); $proparray['AUTOID'] = ''; $proparray['CSSLINK'] = ''; return $proparray; @@ -46,29 +43,30 @@ public static function fetch_emptyproparray(){ /** * Return an array of variable names + * * @param string template containing @@variable@@ variables * @return array of variable names parsed from template string */ - public static function fetch_variables($template){ + public static function fetch_variables($template) { $matches = array(); $t = preg_match_all('/@@(.*?)@@/s', $template, $matches); - if(count($matches)>1){ - return($matches[1]); - }else{ + if (count($matches) > 1) { + return ($matches[1]); + } else { return array(); } } - public static function fetch_filter_properties($filterstring){ + public static function fetch_filter_properties($filterstring) { //lets do a general clean of all input here //see: https://github.com/justinhunt/moodle-filter_generico/issues/7 - $filterstring=clean_param($filterstring,PARAM_TEXT); + $filterstring = clean_param($filterstring, PARAM_TEXT); //this just removes the {GENERICO: .. } - $rawproperties = explode ("{GENERICO:", $filterstring); + $rawproperties = explode("{GENERICO:", $filterstring); //here we remove any html tags we find. They should not be in here $rawproperties = $rawproperties[1]; - $rawproperties = explode ("}", $rawproperties); + $rawproperties = explode("}", $rawproperties); //here we remove any html tags we find. They should not be in here //and we return the guts of the filter string for parsing $rawproperties = strip_tags($rawproperties[0]); @@ -77,27 +75,26 @@ public static function fetch_filter_properties($filterstring){ //Lets run our regular expression over them //string should be property=value,property=value //got this regexp from http://stackoverflow.com/questions/168171/regular-expression-for-parsing-name-value-pairs - $regexpression='/([^=,]*)=("[^"]*"|[^,"]*)/'; - $matches=array(); + $regexpression = '/([^=,]*)=("[^"]*"|[^,"]*)/'; + $matches = array(); //here we match the filter string and split into name array (matches[1]) and value array (matches[2]) //we then add those to a name value array. $itemprops = array(); - if (preg_match_all($regexpression, $rawproperties,$matches,PREG_PATTERN_ORDER)){ + if (preg_match_all($regexpression, $rawproperties, $matches, PREG_PATTERN_ORDER)) { $propscount = count($matches[1]); - for ($cnt =0; $cnt < $propscount; $cnt++){ + for ($cnt = 0; $cnt < $propscount; $cnt++) { // echo $matches[1][$cnt] . "=" . $matches[2][$cnt] . " "; $newvalue = $matches[2][$cnt]; //this could be done better, I am sure. WE are removing the quotes from start and end //this wil however remove multiple quotes id they exist at start and end. NG really - $newvalue = trim($newvalue,'"'); - $itemprops[trim($matches[1][$cnt])]=$newvalue; + $newvalue = trim($newvalue, '"'); + $itemprops[trim($matches[1][$cnt])] = $newvalue; } } return $itemprops; } - /** * Returns URL to the stored file via pluginfile.php. * @@ -110,12 +107,12 @@ public static function fetch_filter_properties($filterstring){ public static function setting_file_url($filepath, $filearea) { global $CFG; - $component = 'filter_generico'; $itemid = 0; $syscontext = \context_system::instance(); - $url = \moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath); + $url = \moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", + "/$syscontext->id/$component/$filearea/$itemid" . $filepath); // Now this is tricky because the we can not hardcode http or https here, lets use the relative link. // Note: unfortunately moodle_url does not support //urls yet. @@ -123,7 +120,6 @@ public static function setting_file_url($filepath, $filearea) { return $url; } - public static function setting_file_serve($filearea, $args, $forcedownload, $options) { global $CFG; require_once("$CFG->libdir/filelib.php"); @@ -135,7 +131,7 @@ public static function setting_file_serve($filearea, $args, $forcedownload, $opt if ($revision < 0) { $lifetime = 0; } else { - $lifetime = 60*60*24*60; + $lifetime = 60 * 60 * 24 * 60; } $fs = get_file_storage(); @@ -155,53 +151,52 @@ public static function update_revision() { set_config('revision', time(), 'filter_generico'); } - protected function check_registered_url($theurl,$wildcardok=true){ + protected function check_registered_url($theurl, $wildcardok = true) { global $CFG; //get arrays of the wwwroot and registered url //just in case, lowercase'ify them - $thewwwroot = strtolower($CFG->wwwroot); - $theregisteredurl = strtolower($theurl); - $theregisteredurl =trim($theregisteredurl); + $thewwwroot = strtolower($CFG->wwwroot); + $theregisteredurl = strtolower($theurl); + $theregisteredurl = trim($theregisteredurl); //add http:// or https:// to URLs that do not have it - if(strpos($theregisteredurl,'https://')!==0 && - strpos($theregisteredurl,'http://')!==0){ - $theregisteredurl= 'https://' . $theregisteredurl; + if (strpos($theregisteredurl, 'https://') !== 0 && + strpos($theregisteredurl, 'http://') !== 0) { + $theregisteredurl = 'https://' . $theregisteredurl; } //if neither parsed successfully, thats a no straight up $wwwroot_bits = parse_url($thewwwroot); $registered_bits = parse_url($theregisteredurl); - if(!$wwwroot_bits || ! $registered_bits){ + if (!$wwwroot_bits || !$registered_bits) { return self::CLOUDPOODLL_IS_UNREGISTERED; } //get the subdomain widlcard address, ie *.a.b.c.d.com - $wildcard_subdomain_wwwroot=''; - if(array_key_exists('host',$wwwroot_bits)){ - $wildcardparts = explode('.',$wwwroot_bits['host']); - $wildcardparts[0]='*'; - $wildcard_subdomain_wwwroot = implode('.',$wildcardparts); - }else{ + $wildcard_subdomain_wwwroot = ''; + if (array_key_exists('host', $wwwroot_bits)) { + $wildcardparts = explode('.', $wwwroot_bits['host']); + $wildcardparts[0] = '*'; + $wildcard_subdomain_wwwroot = implode('.', $wildcardparts); + } else { return self::CLOUDPOODLL_IS_UNREGISTERED; } //match either the exact domain or the wildcard domain or fail - if(array_key_exists('host', $registered_bits)){ + if (array_key_exists('host', $registered_bits)) { //this will cover exact matches and path matches - if($registered_bits['host'] === $wwwroot_bits['host']){ + if ($registered_bits['host'] === $wwwroot_bits['host']) { $this->validated = true; return self::CLOUDPOODLL_IS_REGISTERED; //this will cover subdomain matches but only for institution bigdog and enterprise license - }elseif(($registered_bits['host']=== $wildcard_subdomain_wwwroot) && $wildcardok) - { + } else if (($registered_bits['host'] === $wildcard_subdomain_wwwroot) && $wildcardok) { //yay we are registered!!!! return self::CLOUDPOODLL_IS_REGISTERED; - }else{ + } else { return self::CLOUDPOODLL_IS_UNREGISTERED; } - }else{ + } else { return self::CLOUDPOODLL_IS_UNREGISTERED; } } @@ -209,26 +204,25 @@ protected function check_registered_url($theurl,$wildcardok=true){ //This is called from the settings page and we do not want to make calls out to cloud.poodll.com on settings //page load, for performance and stability issues. So if the cache is empty and/or no token, we just show a //"refresh token" link - public function fetch_token_for_display($apiuser,$apisecret){ + public function fetch_token_for_display($apiuser, $apisecret) { global $CFG; //First check that we have an API id and secret //refresh token $refresh = \html_writer::link($CFG->wwwroot . '/filter/generico/refreshtoken.php', - get_string('refreshtoken',constants::MOD_FRANKY)) . '
'; - + get_string('refreshtoken', constants::MOD_FRANKY)) . '
'; $message = ''; $apiuser = trim($apiuser); $apisecret = trim($apisecret); - if(empty($apiuser)){ - $message .= get_string('noapiuser',constants::MOD_FRANKY) . '
'; + if (empty($apiuser)) { + $message .= get_string('noapiuser', constants::MOD_FRANKY) . '
'; } - if(empty($apisecret)){ - $message .= get_string('noapisecret',constants::MOD_FRANKY); + if (empty($apisecret)) { + $message .= get_string('noapisecret', constants::MOD_FRANKY); } - if(!empty($message)){ + if (!empty($message)) { return $refresh . $message; } @@ -237,35 +231,35 @@ public function fetch_token_for_display($apiuser,$apisecret){ $tokenobject = $cache->get('recentpoodlltoken'); //if we have no token object the creds were wrong ... or something - if(!($tokenobject)){ - $message = get_string('notokenincache',constants::MOD_FRANKY); + if (!($tokenobject)) { + $message = get_string('notokenincache', constants::MOD_FRANKY); //if we have an object but its no good, creds werer wrong ..or something - }elseif(!property_exists($tokenobject,'token') || empty($tokenobject->token)){ - $message = get_string('credentialsinvalid',constants::MOD_FRANKY); + } else if (!property_exists($tokenobject, 'token') || empty($tokenobject->token)) { + $message = get_string('credentialsinvalid', constants::MOD_FRANKY); //if we do not have subs, then we are on a very old token or something is wrong, just get out of here. - }elseif(!property_exists($tokenobject,'subs')){ + } else if (!property_exists($tokenobject, 'subs')) { $message = 'No subscriptions found at all'; } - if(!empty($message)){ + if (!empty($message)) { return $refresh . $message; } //we have enough info to display a report. Lets go. - foreach ($tokenobject->subs as $sub){ - $sub->expiredate = date('d/m/Y',$sub->expiredate); - $message .= get_string('displaysubs',constants::MOD_FRANKY, $sub) . '
'; + foreach ($tokenobject->subs as $sub) { + $sub->expiredate = date('d/m/Y', $sub->expiredate); + $message .= get_string('displaysubs', constants::MOD_FRANKY, $sub) . '
'; } //Is site authorised - $haveauthsite=false; + $haveauthsite = false; foreach ($tokenobject->sites as $site) { - if($this->check_registered_url($site)==self::CLOUDPOODLL_IS_REGISTERED){ - $haveauthsite=true; + if ($this->check_registered_url($site) == self::CLOUDPOODLL_IS_REGISTERED) { + $haveauthsite = true; break; } } - if(!$haveauthsite){ - $message .= get_string('appnotauthorised',constants::MOD_FRANKY) . '
'; - }else { + if (!$haveauthsite) { + $message .= get_string('appnotauthorised', constants::MOD_FRANKY) . '
'; + } else { //Is app authorised if (in_array(constants::MOD_FRANKY, $tokenobject->apps)) { @@ -278,8 +272,7 @@ public function fetch_token_for_display($apiuser,$apisecret){ } //We need a Poodll token to make cloudpoodll happen - public static function fetch_token($apiuser, $apisecret,$force=false) - { + public static function fetch_token($apiuser, $apisecret, $force = false) { $cache = \cache::make_from_params(\cache_store::MODE_APPLICATION, constants::MOD_FRANKY, 'token'); $tokenobject = $cache->get('recentpoodlltoken'); $tokenuser = $cache->get('recentpoodlluser'); @@ -288,64 +281,64 @@ public static function fetch_token($apiuser, $apisecret,$force=false) //if we got a token and its less than expiry time // use the cached one - if($tokenobject && $tokenuser && $tokenuser==$apiuser && !$force){ - if($tokenobject->validuntil == 0 || $tokenobject->validuntil > time()){ - return $tokenobject; + if ($tokenobject && $tokenuser && $tokenuser == $apiuser && !$force) { + if ($tokenobject->validuntil == 0 || $tokenobject->validuntil > time()) { + return $tokenobject->token; } } // Send the request & save response to $resp - $token_url ="https://cloud.poodll.com/local/cpapi/poodlltoken.php"; - $postdata=array( - 'username'=>$apiuser, - 'password'=>$apisecret, - 'service'=>'cloud_poodll'); - $token_response = self::curl_fetch($token_url,$postdata); + $token_url = "https://cloud.poodll.com/local/cpapi/poodlltoken.php"; + $postdata = array( + 'username' => $apiuser, + 'password' => $apisecret, + 'service' => 'cloud_poodll'); + $token_response = self::curl_fetch($token_url, $postdata); if ($token_response) { $resp_object = json_decode($token_response); - if($resp_object && property_exists($resp_object,'token')) { + if ($resp_object && property_exists($resp_object, 'token')) { $token = $resp_object->token; //store the expiry timestamp and adjust it for diffs between our server times - if($resp_object->validuntil) { + if ($resp_object->validuntil) { $validuntil = $resp_object->validuntil - ($resp_object->poodlltime - time()); //we refresh one hour out, to prevent any overlap $validuntil = $validuntil - (1 * HOURSECS); - }else{ + } else { $validuntil = 0; } //make sure the token has all the bits in it we expect before caching it $tokenobject = $resp_object;//new \stdClass(); $tokenobject->validuntil = $validuntil; - if(!property_exists($tokenobject,'subs')){ + if (!property_exists($tokenobject, 'subs')) { $tokenobject->subs = false; } - if(!property_exists($tokenobject,'apps')){ + if (!property_exists($tokenobject, 'apps')) { $tokenobject->apps = false; } - if(!property_exists($tokenobject,'sites')){ + if (!property_exists($tokenobject, 'sites')) { $tokenobject->sites = false; } $cache->set('recentpoodlltoken', $tokenobject); $cache->set('recentpoodlluser', $apiuser); - }else{ - $tokenobject = false; - if($resp_object && property_exists($resp_object,'error')) { + } else { + $token = false; + if ($resp_object && property_exists($resp_object, 'error')) { //ERROR = $resp_object->error } } - }else{ - $tokenobject=false; + } else { + $token = false; } - return $tokenobject; + return $token; } //we use curl to fetch transcripts from AWS and Tokens from cloudpoodll //this is our helper - public static function curl_fetch($url,$postdata){ + public static function curl_fetch($url, $postdata) { global $CFG; - require_once($CFG->libdir.'/filelib.php'); + require_once($CFG->libdir . '/filelib.php'); $curl = new \curl(); $result = $curl->get($url, $postdata); diff --git a/classes/presets_control.php b/classes/presets_control.php index 15ab698..835554c 100644 --- a/classes/presets_control.php +++ b/classes/presets_control.php @@ -27,10 +27,9 @@ require_once($CFG->libdir . '/adminlib.php'); -class presets_control extends \admin_setting -{ +class presets_control extends \admin_setting { - /** @var mixed int index of template*/ + /** @var mixed int index of template */ public $templateindex; /** @var array template data for spec index */ public $presetdata; @@ -39,21 +38,24 @@ class presets_control extends \admin_setting /** * not a setting, just text - * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. + * + * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in + * config_plugins. * @param string $heading heading * @param string $information text in box */ - public function __construct($name, $visiblename, $information,$templateindex) { + public function __construct($name, $visiblename, $information, $templateindex) { $this->nosave = true; $this->templateindex = $templateindex; $this->presetdata = $this->fetch_presets(); - $this->visiblename=$visiblename; - $this->information=$information; - parent::__construct($name, $visiblename, $information,$templateindex); + $this->visiblename = $visiblename; + $this->information = $information; + parent::__construct($name, $visiblename, $information, $templateindex); } /** * Always returns true + * * @return bool Always returns true */ public function get_setting() { @@ -62,6 +64,7 @@ public function get_setting() { /** * Always returns true + * * @return bool Always returns true */ public function get_defaultsetting() { @@ -70,6 +73,7 @@ public function get_defaultsetting() { /** * Never write settings + * * @return string Always returns an empty string */ public function write_setting($data) { @@ -79,73 +83,75 @@ public function write_setting($data) { /** * Returns an HTML string + * * @return string Returns an HTML string */ - public function output_html($data, $query='') { + public function output_html($data, $query = '') { global $PAGE; //build our select form $keys = array_keys($this->presetdata); $usearray = array(); - foreach($keys as $key){ + foreach ($keys as $key) { $name = $this->presetdata[$key]['name']; - if(empty($name)){$name=$key;} - $usearray[$key]=$name; + if (empty($name)) { + $name = $key; + } + $usearray[$key] = $name; } $presetsjson = json_encode($this->presetdata); - $presetscontrol = \html_writer::tag('input', '', array('id' => 'id_s_filter_generico_presetdata_' . $this->templateindex, 'type' => 'hidden', 'value' => $presetsjson)); - + $presetscontrol = \html_writer::tag('input', '', + array('id' => 'id_s_filter_generico_presetdata_' . $this->templateindex, 'type' => 'hidden', + 'value' => $presetsjson)); //Add javascript handler for presets $PAGE->requires->js_call_amd('filter_generico/generico_presets_amd', - 'init',array(array('templateindex'=>$this->templateindex))); + 'init', array(array('templateindex' => $this->templateindex))); - $select = \html_writer::select($usearray,'filter_generico/presets','','--custom--'); + $select = \html_writer::select($usearray, 'filter_generico/presets', '', '--custom--'); - $dragdropsquare = \html_writer::tag('div',get_string('bundle','filter_generico'),array('id' => 'id_s_filter_generico_dragdropsquare_' . $this->templateindex, - 'class' => 'filter_generico_dragdropsquare')); + $dragdropsquare = \html_writer::tag('div', get_string('bundle', 'filter_generico'), + array('id' => 'id_s_filter_generico_dragdropsquare_' . $this->templateindex, + 'class' => 'filter_generico_dragdropsquare')); return format_admin_setting($this, $this->visiblename, - $dragdropsquare . '
'. $presetscontrol . $select . '
', - $this->information, true, '','', $query); - - + $dragdropsquare . '
' . $presetscontrol . $select . '
', + $this->information, true, '', '', $query); } - protected static function parse_preset_template(\SplFileInfo $fileinfo){ - $file=$fileinfo->openFile("r"); + protected static function parse_preset_template(\SplFileInfo $fileinfo) { + $file = $fileinfo->openFile("r"); $content = ""; - while(!$file->eof()){ + while (!$file->eof()) { $content .= $file->fgets(); } $preset_object = json_decode($content); - if($preset_object && is_object($preset_object)){ + if ($preset_object && is_object($preset_object)) { return get_object_vars($preset_object); - }else{ + } else { return false; } }//end of parse preset template - - public static function fetch_presets(){ - global $CFG,$PAGE; + public static function fetch_presets() { + global $CFG, $PAGE; //init return array $ret = array(); - $dirs=array(); + $dirs = array(); //we search the Generico "presets" and the themes "generico" folders for presets - $generico_presets_dir=$CFG->dirroot . '/filter/generico/presets'; - $theme_generico_dir=$PAGE->theme->dir . '/generico'; - if(file_exists($generico_presets_dir)) { + $generico_presets_dir = $CFG->dirroot . '/filter/generico/presets'; + $theme_generico_dir = $PAGE->theme->dir . '/generico'; + if (file_exists($generico_presets_dir)) { $dirs[] = new \DirectoryIterator($generico_presets_dir); } - if(file_exists($theme_generico_dir)) { + if (file_exists($theme_generico_dir)) { $dirs[] = new \DirectoryIterator($theme_generico_dir); } - foreach($dirs as $dir) { + foreach ($dirs as $dir) { foreach ($dir as $fileinfo) { if (!$fileinfo->isDot() && !$fileinfo->isDir()) { $preset = self::parse_preset_template($fileinfo); @@ -158,38 +164,38 @@ public static function fetch_presets(){ return $ret; }//end of fetch presets function - public static function set_preset_to_config($preset, $templateindex){ + public static function set_preset_to_config($preset, $templateindex) { $fields = array(); - $fields['name']='templatename'; - $fields['key']='templatekey'; - $fields['instructions']='templateinstructions'; - $fields['body']='template'; - $fields['bodyend']='templateend'; - $fields['requirecss']='templaterequire_css'; - $fields['requirejs']='templaterequire_js'; - $fields['shim']='templaterequire_js_shim'; - $fields['version']='templateversion'; - $fields['defaults']='templatedefaults'; - $fields['amd']='template_amd'; - $fields['script']='templatescript'; - $fields['style']='templatestyle'; - $fields['dataset']='dataset'; - $fields['datavars']='datavars'; - - foreach($fields as $fieldkey=>$fieldname){ - if(array_key_exists($fieldkey,$preset)){ - $fieldvalue=$preset[$fieldkey]; - }else{ - $fieldvalue=''; + $fields['name'] = 'templatename'; + $fields['key'] = 'templatekey'; + $fields['instructions'] = 'templateinstructions'; + $fields['body'] = 'template'; + $fields['bodyend'] = 'templateend'; + $fields['requirecss'] = 'templaterequire_css'; + $fields['requirejs'] = 'templaterequire_js'; + $fields['shim'] = 'templaterequire_js_shim'; + $fields['version'] = 'templateversion'; + $fields['defaults'] = 'templatedefaults'; + $fields['amd'] = 'template_amd'; + $fields['script'] = 'templatescript'; + $fields['style'] = 'templatestyle'; + $fields['dataset'] = 'dataset'; + $fields['datavars'] = 'datavars'; + + foreach ($fields as $fieldkey => $fieldname) { + if (array_key_exists($fieldkey, $preset)) { + $fieldvalue = $preset[$fieldkey]; + } else { + $fieldvalue = ''; } set_config($fieldname . '_' . $templateindex, $fieldvalue, 'filter_generico'); } }//End of set_preset_to_config - public static function template_has_update($templateindex){ + public static function template_has_update($templateindex) { $presets = self::fetch_presets(); - foreach($presets as $preset) { - if(get_config('filter_generico', 'templatekey_' . $templateindex)==$preset['key']) { + foreach ($presets as $preset) { + if (get_config('filter_generico', 'templatekey_' . $templateindex) == $preset['key']) { $template_version = get_config('filter_generico', 'templateversion_' . $templateindex); $preset_version = $preset['version']; if (version_compare($preset_version, $template_version) > 0) { @@ -200,26 +206,28 @@ public static function template_has_update($templateindex){ return false; } - public static function update_all_templates(){ - $templatecount = get_config('filter_generico','templatecount'); - $updatecount=0; - for($x=1;$x<$templatecount+1;$x++){ - $updated=self::update_template($x); - if($updated){$updatecount++;} + public static function update_all_templates() { + $templatecount = get_config('filter_generico', 'templatecount'); + $updatecount = 0; + for ($x = 1; $x < $templatecount + 1; $x++) { + $updated = self::update_template($x); + if ($updated) { + $updatecount++; + } }//end of templatecount loop return $updatecount; }//end of function - public static function update_template($templateindex){ - $updated=false; + public static function update_template($templateindex) { + $updated = false; $presets = self::fetch_presets(); - foreach($presets as $preset) { - if(get_config('filter_generico', 'templatekey_' . $templateindex)==$preset['key']) { + foreach ($presets as $preset) { + if (get_config('filter_generico', 'templatekey_' . $templateindex) == $preset['key']) { $template_version = get_config('filter_generico', 'templateversion_' . $templateindex); $preset_version = $preset['version']; if (version_compare($preset_version, $template_version) > 0) { self::set_preset_to_config($preset, $templateindex); - $updated =true; + $updated = true; }//end of version compare return $updated; }//end of if keys match diff --git a/classes/privacy/provider.php b/classes/privacy/provider.php index 18abb6b..6be7095 100644 --- a/classes/privacy/provider.php +++ b/classes/privacy/provider.php @@ -33,7 +33,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class provider implements - \core_privacy\local\metadata\null_provider { + \core_privacy\local\metadata\null_provider { use \core_privacy\local\legacy_polyfill; diff --git a/classes/settingstools.php b/classes/settingstools.php index 41ebdb1..e8dba61 100644 --- a/classes/settingstools.php +++ b/classes/settingstools.php @@ -22,7 +22,6 @@ require_once($CFG->libdir . '/filelib.php'); - /** * * This is a class containing static functions for general PoodLL filter things @@ -33,220 +32,223 @@ * @copyright 2016 Justin Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -class settingstools -{ +class settingstools { //make a readable template name for menus and lists etc -public static function fetch_template_title($conf,$tindex,$typeprefix=true){ - //template display name - $tname=''; - if($conf && property_exists($conf,'templatename_' . $tindex)){ - $tname = $conf->{'templatename_' . $tindex}; - } - if(empty($tname) && $conf && property_exists($conf,'templatekey_' . $tindex)){ - $tname = $conf->{'templatekey_' . $tindex}; - } - if(empty($tname)){$tname=$tindex;} + public static function fetch_template_title($conf, $tindex, $typeprefix = true) { + //template display name + $tname = ''; + if ($conf && property_exists($conf, 'templatename_' . $tindex)) { + $tname = $conf->{'templatename_' . $tindex}; + } + if (empty($tname) && $conf && property_exists($conf, 'templatekey_' . $tindex)) { + $tname = $conf->{'templatekey_' . $tindex}; + } + if (empty($tname)) { + $tname = $tindex; + } - if(!$typeprefix){ - return $tname; - } + if (!$typeprefix) { + return $tname; + } - if($conf && property_exists($conf,'templatekey_' . $tindex) && property_exists($conf,'template_showatto_' . $tindex) && $conf->{'template_showatto_' . $tindex} > 0){ - $templatetitle = get_string('templatepagewidgetheading', 'filter_poodll',$tname); - }elseif($conf && property_exists($conf,'templatekey_' . $tindex) && property_exists($conf,'template_showplayers_' . $tindex) && $conf->{'template_showplayers_' . $tindex} > 0){ - $templatetitle = get_string('templatepageplayerheading', 'filter_poodll',$tname); - }else{ - $templatetitle = get_string('templatepageheading', 'filter_poodll',$tname); + if ($conf && property_exists($conf, 'templatekey_' . $tindex) && property_exists($conf, 'template_showatto_' . $tindex) && + $conf->{'template_showatto_' . $tindex} > 0) { + $templatetitle = get_string('templatepagewidgetheading', 'filter_poodll', $tname); + } else if ($conf && property_exists($conf, 'templatekey_' . $tindex) && + property_exists($conf, 'template_showplayers_' . $tindex) && $conf->{'template_showplayers_' . $tindex} > 0) { + $templatetitle = get_string('templatepageplayerheading', 'filter_poodll', $tname); + } else { + $templatetitle = get_string('templatepageheading', 'filter_poodll', $tname); + } + return $templatetitle; } - return $templatetitle; -} - -/* -public static function fetch_template_table(){ - - $items=array(); - $items[] =new \filter_poodll\poodlltemplatetable('filter_poodll/templatetable', - get_string('templates', 'filter_poodll'), ''); - return $items; -} -*/ + /* + public static function fetch_template_table(){ -public static function fetch_template_pages($conf){ - $pages = array(); + $items=array(); + $items[] =new \filter_poodll\poodlltemplatetable('filter_poodll/templatetable', + get_string('templates', 'filter_poodll'), ''); + return $items; - //Add the template pages - if($conf && property_exists($conf,'templatecount')){ - $templatecount = $conf->templatecount; - }else{ - $templatecount = \filter_generico\generico_utils::FILTER_GENERICO_TEMPLATE_COUNT; } + */ - //fetch preset data, just once so we do nto need to repeat the call a zillion times - $presetdata = presets_control::fetch_presets(); + public static function fetch_template_pages($conf) { + $pages = array(); - for($tindex=1;$tindex<=$templatecount;$tindex++){ - - //template display name - if($conf && property_exists($conf,'templatekey_' . $tindex)){ - $tname = $conf->{'templatekey_' . $tindex}; - if(empty($tname)){$tname=$tindex;} - }else{ - $tname = $tindex; + //Add the template pages + if ($conf && property_exists($conf, 'templatecount')) { + $templatecount = $conf->templatecount; + } else { + $templatecount = \filter_generico\generico_utils::FILTER_GENERICO_TEMPLATE_COUNT; } - //template settings Page Settings (we append hidden=true as 4th param to keep out of site menu) - $settings_page = new \admin_settingpage('filter_generico_templatepage_' . $tindex,get_string('templatepageheading', 'filter_generico',$tname),'moodle/site:config',true); - - //template page heading - $settings_page->add(new \admin_setting_heading('filter_generico/templateheading_' . $tindex, - get_string('templateheading', 'filter_generico',$tname), '')); - - //presets - $settings_page->add(new \filter_generico\presets_control('filter_generico/templatepresets_' . $tindex, - get_string('presets', 'filter_generico'), get_string('presets_desc', 'filter_generico'),$tindex, $presetdata)); - - //template key - $settings_page->add(new \admin_setting_configtext('filter_generico/templatekey_' . $tindex , - get_string('templatekey', 'filter_generico',$tindex), - get_string('templatekey_desc', 'filter_generico'), - '', PARAM_ALPHANUMEXT)); - - //template name - $settings_page->add(new \admin_setting_configtext('filter_generico/templatename_' . $tindex , - get_string('templatename', 'filter_generico',$tindex), - get_string('templatename_desc', 'filter_generico'), - '', PARAM_RAW)); - - //template version - $settings_page->add(new \admin_setting_configtext('filter_generico/templateversion_' . $tindex , - get_string('templateversion', 'filter_generico',$tindex), - get_string('templateversion_desc', 'filter_generico'), - '', PARAM_TEXT)); - - //template instructions - $settings_page->add(new \admin_setting_configtextarea('filter_generico/templateinstructions_' . $tindex, - get_string('templateinstructions', 'filter_generico',$tindex), - get_string('templateinstructions_desc', 'filter_generico'), - '',PARAM_RAW)); - - //template body - $settings_page->add(new \admin_setting_configtextarea('filter_generico/template_' . $tindex, - get_string('template', 'filter_generico',$tindex), - get_string('template_desc', 'filter_generico'),'')); - - //template body end - $settings_page->add(new \admin_setting_configtextarea('filter_generico/templateend_' . $tindex, - get_string('templateend', 'filter_generico',$tindex), - get_string('templateend_desc', 'filter_generico'),'')); - - //template defaults - $settings_page->add(new \admin_setting_configtextarea('filter_generico/templatedefaults_' . $tindex, - get_string('templatedefaults', 'filter_generico', $tindex), - get_string('templatedefaults_desc', 'filter_generico'),'')); - - //template page JS heading - $settings_page->add(new \admin_setting_heading('filter_generico/templateheading_js' . $tindex, - get_string('templateheadingjs', 'filter_generico',$tname), '')); - - //additional JS (external link) - $settings_page->add(new \admin_setting_configtext('filter_generico/templaterequire_js_' . $tindex , - get_string('templaterequire_js', 'filter_generico',$tindex), - get_string('templaterequire_js_desc', 'filter_generico'), - '', PARAM_RAW,50)); - - //template requiredjs_shim - $defvalue= ''; - $settings_page->add(new \admin_setting_configtext('filter_generico/templaterequire_js_shim_' . $tindex , - get_string('templaterequirejsshim', 'filter_generico',$tindex), - get_string('templaterequirejsshim_desc', 'filter_generico'), - $defvalue, PARAM_RAW)); - - //template amd - $yesno = array('0'=>get_string('no'),'1'=>get_string('yes')); - $settings_page->add(new \admin_setting_configselect('filter_generico/template_amd_' . $tindex, - get_string('templaterequire_amd', 'filter_generico',$tindex), - get_string('templaterequire_amd_desc', 'filter_generico'), - 1,$yesno)); - - //template body script - $setting = new \admin_setting_configtextarea('filter_generico/templatescript_' . $tindex, - get_string('templatescript', 'filter_generico',$tindex), - get_string('templatescript_desc', 'filter_generico'), - '',PARAM_RAW); - $setting->set_updatedcallback('filter_generico_update_revision'); - $settings_page->add($setting); - - //additional JS (upload) - //see here: for integrating this https://moodle.org/mod/forum/discuss.php?d=227249 - $name = 'filter_generico/uploadjs' . $tindex; - $title =get_string('uploadjs', 'filter_generico',$tindex); - $description = get_string('uploadjs_desc', 'filter_generico'); - $settings_page->add(new \admin_setting_configstoredfile($name, $title, $description, 'uploadjs' . $tindex)); - - //template uploadjs_shim - $defvalue= ''; - $settings_page->add(new \admin_setting_configtext('filter_generico/uploadjs_shim_' . $tindex , - get_string('templateuploadjsshim', 'filter_generico',$tindex), - get_string('templateuploadjsshim_desc', 'filter_generico'), - $defvalue, PARAM_RAW)); - - //template page CSS heading - $settings_page->add(new \admin_setting_heading('filter_generico/templateheading_css_' . $tindex, - get_string('templateheadingcss', 'filter_generico',$tname), '')); - - //additional CSS (external link) - $settings_page->add(new \admin_setting_configtext('filter_generico/templaterequire_css_' . $tindex , - get_string('templaterequire_css', 'filter_generico',$tindex), - get_string('templaterequire_css_desc', 'filter_generico'), - '', PARAM_RAW,50)); - - //template body css - $setting = new \admin_setting_configtextarea('filter_generico/templatestyle_' . $tindex, - get_string('templatestyle', 'filter_generico',$tindex), - get_string('templatestyle_desc', 'filter_generico'), - '',PARAM_RAW); - $setting->set_updatedcallback('filter_generico_update_revision'); - $settings_page->add($setting); - - //additional CSS (upload) - $name = 'filter_generico/uploadcss' . $tindex; - $title =get_string('uploadcss', 'filter_generico',$tindex); - $description = get_string('uploadcss_desc', 'filter_generico'); - $settings_page->add(new \admin_setting_configstoredfile($name, $title, $description, 'uploadcss' . $tindex)); - - //dataset - $settings_page->add(new \admin_setting_configtextarea('filter_generico/dataset_' . $tindex, - get_string('dataset', 'filter_generico',$tindex), - get_string('dataset_desc', 'filter_generico'), - '',PARAM_RAW)); - - //dataset vars - $settings_page->add(new \admin_setting_configtext('filter_generico/datasetvars_' . $tindex , - get_string('datasetvars', 'filter_generico',$tindex), - get_string('datasetvars_desc', 'filter_generico'), - '', PARAM_RAW,50)); - - //alternative content - $settings_page->add(new \admin_setting_configtextarea('filter_generico/templatealternate_' . $tindex, - get_string('templatealternate', 'filter_generico',$tindex), - get_string('templatealternate_desc', 'filter_generico'), - '',PARAM_RAW)); - - //alternative content end - $settings_page->add(new \admin_setting_configtextarea('filter_generico/templatealternate_end_' . $tindex, - get_string('templatealternate_end', 'filter_generico',$tindex), - get_string('templatealternate_end_desc', 'filter_generico'), - '',PARAM_RAW)); - - - $pages[] = $settings_page; - } - + //fetch preset data, just once so we do nto need to repeat the call a zillion times + $presetdata = presets_control::fetch_presets(); + + for ($tindex = 1; $tindex <= $templatecount; $tindex++) { + + //template display name + if ($conf && property_exists($conf, 'templatekey_' . $tindex)) { + $tname = $conf->{'templatekey_' . $tindex}; + if (empty($tname)) { + $tname = $tindex; + } + } else { + $tname = $tindex; + } + + //template settings Page Settings (we append hidden=true as 4th param to keep out of site menu) + $settings_page = new \admin_settingpage('filter_generico_templatepage_' . $tindex, + get_string('templatepageheading', 'filter_generico', $tname), 'moodle/site:config', true); + + //template page heading + $settings_page->add(new \admin_setting_heading('filter_generico/templateheading_' . $tindex, + get_string('templateheading', 'filter_generico', $tname), '')); + + //presets + $settings_page->add(new \filter_generico\presets_control('filter_generico/templatepresets_' . $tindex, + get_string('presets', 'filter_generico'), get_string('presets_desc', 'filter_generico'), $tindex, $presetdata)); + + //template key + $settings_page->add(new \admin_setting_configtext('filter_generico/templatekey_' . $tindex, + get_string('templatekey', 'filter_generico', $tindex), + get_string('templatekey_desc', 'filter_generico'), + '', PARAM_ALPHANUMEXT)); + + //template name + $settings_page->add(new \admin_setting_configtext('filter_generico/templatename_' . $tindex, + get_string('templatename', 'filter_generico', $tindex), + get_string('templatename_desc', 'filter_generico'), + '', PARAM_RAW)); + + //template version + $settings_page->add(new \admin_setting_configtext('filter_generico/templateversion_' . $tindex, + get_string('templateversion', 'filter_generico', $tindex), + get_string('templateversion_desc', 'filter_generico'), + '', PARAM_TEXT)); + + //template instructions + $settings_page->add(new \admin_setting_configtextarea('filter_generico/templateinstructions_' . $tindex, + get_string('templateinstructions', 'filter_generico', $tindex), + get_string('templateinstructions_desc', 'filter_generico'), + '', PARAM_RAW)); + + //template body + $settings_page->add(new \admin_setting_configtextarea('filter_generico/template_' . $tindex, + get_string('template', 'filter_generico', $tindex), + get_string('template_desc', 'filter_generico'), '')); + + //template body end + $settings_page->add(new \admin_setting_configtextarea('filter_generico/templateend_' . $tindex, + get_string('templateend', 'filter_generico', $tindex), + get_string('templateend_desc', 'filter_generico'), '')); + + //template defaults + $settings_page->add(new \admin_setting_configtextarea('filter_generico/templatedefaults_' . $tindex, + get_string('templatedefaults', 'filter_generico', $tindex), + get_string('templatedefaults_desc', 'filter_generico'), '')); + + //template page JS heading + $settings_page->add(new \admin_setting_heading('filter_generico/templateheading_js' . $tindex, + get_string('templateheadingjs', 'filter_generico', $tname), '')); + + //additional JS (external link) + $settings_page->add(new \admin_setting_configtext('filter_generico/templaterequire_js_' . $tindex, + get_string('templaterequire_js', 'filter_generico', $tindex), + get_string('templaterequire_js_desc', 'filter_generico'), + '', PARAM_RAW, 50)); + + //template requiredjs_shim + $defvalue = ''; + $settings_page->add(new \admin_setting_configtext('filter_generico/templaterequire_js_shim_' . $tindex, + get_string('templaterequirejsshim', 'filter_generico', $tindex), + get_string('templaterequirejsshim_desc', 'filter_generico'), + $defvalue, PARAM_RAW)); + + //template amd + $yesno = array('0' => get_string('no'), '1' => get_string('yes')); + $settings_page->add(new \admin_setting_configselect('filter_generico/template_amd_' . $tindex, + get_string('templaterequire_amd', 'filter_generico', $tindex), + get_string('templaterequire_amd_desc', 'filter_generico'), + 1, $yesno)); + + //template body script + $setting = new \admin_setting_configtextarea('filter_generico/templatescript_' . $tindex, + get_string('templatescript', 'filter_generico', $tindex), + get_string('templatescript_desc', 'filter_generico'), + '', PARAM_RAW); + $setting->set_updatedcallback('filter_generico_update_revision'); + $settings_page->add($setting); + + //additional JS (upload) + //see here: for integrating this https://moodle.org/mod/forum/discuss.php?d=227249 + $name = 'filter_generico/uploadjs' . $tindex; + $title = get_string('uploadjs', 'filter_generico', $tindex); + $description = get_string('uploadjs_desc', 'filter_generico'); + $settings_page->add(new \admin_setting_configstoredfile($name, $title, $description, 'uploadjs' . $tindex)); + + //template uploadjs_shim + $defvalue = ''; + $settings_page->add(new \admin_setting_configtext('filter_generico/uploadjs_shim_' . $tindex, + get_string('templateuploadjsshim', 'filter_generico', $tindex), + get_string('templateuploadjsshim_desc', 'filter_generico'), + $defvalue, PARAM_RAW)); + + //template page CSS heading + $settings_page->add(new \admin_setting_heading('filter_generico/templateheading_css_' . $tindex, + get_string('templateheadingcss', 'filter_generico', $tname), '')); + + //additional CSS (external link) + $settings_page->add(new \admin_setting_configtext('filter_generico/templaterequire_css_' . $tindex, + get_string('templaterequire_css', 'filter_generico', $tindex), + get_string('templaterequire_css_desc', 'filter_generico'), + '', PARAM_RAW, 50)); + + //template body css + $setting = new \admin_setting_configtextarea('filter_generico/templatestyle_' . $tindex, + get_string('templatestyle', 'filter_generico', $tindex), + get_string('templatestyle_desc', 'filter_generico'), + '', PARAM_RAW); + $setting->set_updatedcallback('filter_generico_update_revision'); + $settings_page->add($setting); + + //additional CSS (upload) + $name = 'filter_generico/uploadcss' . $tindex; + $title = get_string('uploadcss', 'filter_generico', $tindex); + $description = get_string('uploadcss_desc', 'filter_generico'); + $settings_page->add(new \admin_setting_configstoredfile($name, $title, $description, 'uploadcss' . $tindex)); + + //dataset + $settings_page->add(new \admin_setting_configtextarea('filter_generico/dataset_' . $tindex, + get_string('dataset', 'filter_generico', $tindex), + get_string('dataset_desc', 'filter_generico'), + '', PARAM_RAW)); + + //dataset vars + $settings_page->add(new \admin_setting_configtext('filter_generico/datasetvars_' . $tindex, + get_string('datasetvars', 'filter_generico', $tindex), + get_string('datasetvars_desc', 'filter_generico'), + '', PARAM_RAW, 50)); + + //alternative content + $settings_page->add(new \admin_setting_configtextarea('filter_generico/templatealternate_' . $tindex, + get_string('templatealternate', 'filter_generico', $tindex), + get_string('templatealternate_desc', 'filter_generico'), + '', PARAM_RAW)); + + //alternative content end + $settings_page->add(new \admin_setting_configtextarea('filter_generico/templatealternate_end_' . $tindex, + get_string('templatealternate_end', 'filter_generico', $tindex), + get_string('templatealternate_end_desc', 'filter_generico'), + '', PARAM_RAW)); + + $pages[] = $settings_page; + } - return $pages; - }//end of function fetch template pages + return $pages; + }//end of function fetch template pages }//end of class diff --git a/classes/template_script_generator.php b/classes/template_script_generator.php index 133e686..e8bff9f 100644 --- a/classes/template_script_generator.php +++ b/classes/template_script_generator.php @@ -22,14 +22,12 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - namespace filter_generico; defined('MOODLE_INTERNAL') || die; -class template_script_generator -{ - /** @var mixed int index of template*/ +class template_script_generator { + /** @var mixed int index of template */ public $templateindex; /** @@ -39,54 +37,53 @@ public function __construct($templateindex) { $this->templateindex = $templateindex; } - - public function get_template_script(){ + public function get_template_script() { global $CFG; $tindex = $this->templateindex; $conf = get_config('filter_generico'); - $template=$conf->{'template_' . $tindex}; + $template = $conf->{'template_' . $tindex}; //are we AMD and Moodle 2.9 or more? - $require_amd = $conf->{'template_amd_' . $tindex} && $CFG->version>=2015051100; + $require_amd = $conf->{'template_amd_' . $tindex} && $CFG->version >= 2015051100; //get presets - $thescript=$conf->{'templatescript_' . $tindex}; - $defaults=$conf->{'templatedefaults_' . $tindex}; - + $thescript = $conf->{'templatescript_' . $tindex}; + $defaults = $conf->{'templatedefaults_' . $tindex}; //fetch all the variables we use (make sure we have no duplicates) - $allvariables = generico_utils::fetch_variables($thescript. $template); + $allvariables = generico_utils::fetch_variables($thescript . $template); $uniquevariables = array_unique($allvariables); //these props are in the opts array in the allopts[] array on the page //since we are writing the JS we write the opts['name'] into the js, but //have to remove quotes from template eg "@@VAR@@" => opts['var'] //NB no quotes. //thats worth knowing for the admin who writed the JS load code for the template. - foreach($uniquevariables as $propname){ + foreach ($uniquevariables as $propname) { //case: single quotes - $thescript = str_replace("'@@" . $propname ."@@'",'opts["' . $propname . '"]',$thescript); + $thescript = str_replace("'@@" . $propname . "@@'", 'opts["' . $propname . '"]', $thescript); //case: double quotes - $thescript = str_replace('"@@' . $propname .'@@"',"opts['" . $propname . "']",$thescript); + $thescript = str_replace('"@@' . $propname . '@@"', "opts['" . $propname . "']", $thescript); //case: no quotes - $thescript = str_replace('@@' . $propname .'@@',"opts['" . $propname . "']",$thescript); + $thescript = str_replace('@@' . $propname . '@@', "opts['" . $propname . "']", $thescript); } - if($require_amd){ + if ($require_amd) { //figure out if this is https or http. We don't want to scare the browser - $scheme='http:'; - if(strpos(strtolower($CFG->wwwroot),'https')===0){$scheme='https:';} - + $scheme = 'http:'; + if (strpos(strtolower($CFG->wwwroot), 'https') === 0) { + $scheme = 'https:'; + } //this is for loading as dependencies the uploaded or linked files //massage the js URL depending on schemes and rel. links etc. Then insert it $requiredjs = $conf->{'templaterequire_js_' . $tindex}; - $requiredjs_shim =trim($conf->{'templaterequire_js_shim_' . $tindex}); - if($requiredjs){ - if(strpos($requiredjs,'//')===0){ + $requiredjs_shim = trim($conf->{'templaterequire_js_shim_' . $tindex}); + if ($requiredjs) { + if (strpos($requiredjs, '//') === 0) { $requiredjs = $scheme . $requiredjs; - }elseif(strpos($requiredjs,'/')===0){ + } else if (strpos($requiredjs, '/') === 0) { $requiredjs = $CFG->wwwroot . $requiredjs; } //remove .js from end @@ -95,9 +92,9 @@ public function get_template_script(){ //if we have an uploaded JS file, then lets include that $uploadjsfile = $conf->{'uploadjs' . $tindex}; - $uploadjs_shim =trim($conf->{'uploadjs_shim_' . $tindex}); - if($uploadjsfile){ - $uploadjs = generico_utils::setting_file_url($uploadjsfile,'uploadjs' . $tindex); + $uploadjs_shim = trim($conf->{'uploadjs_shim_' . $tindex}); + if ($uploadjsfile) { + $uploadjs = generico_utils::setting_file_url($uploadjsfile, 'uploadjs' . $tindex); } //Create the dependency stuff in the output js @@ -105,51 +102,51 @@ public function get_template_script(){ $params = array(); //these arrays are used for shimming - $shimkeys= array(); - $shimpaths= array(); - $shimexports= array(); + $shimkeys = array(); + $shimpaths = array(); + $shimexports = array(); //current key $currentkey = $conf->{'templatekey_' . $tindex}; //if we have a url based required js //either load it, or shim and load it - if($requiredjs){ - if($requiredjs_shim!=''){ + if ($requiredjs) { + if ($requiredjs_shim != '') { $shimkeys[] = $currentkey . '-requiredjs'; //remove .js from end of js filepath if its there - if(strrpos($requiredjs,'.js')==(strlen($requiredjs) -3)){ + if (strrpos($requiredjs, '.js') == (strlen($requiredjs) - 3)) { $requiredjs = substr($requiredjs, 0, -3); } - $shimpaths[]= $requiredjs; - $shimexports[]=$requiredjs_shim; + $shimpaths[] = $requiredjs; + $shimexports[] = $requiredjs_shim; $requires[] = "'" . $currentkey . '-requiredjs' . "'"; - $params[]=$requiredjs_shim; - }else{ - $requires[] = "'" . $requiredjs . "'"; + $params[] = $requiredjs_shim; + } else { + $requires[] = "'" . $requiredjs . "'"; $params[] = "requiredjs_" . $currentkey; } } //if we have an uploadedjs library //either load it, or shim and load it - if($uploadjsfile){ - if($uploadjs_shim!=''){ + if ($uploadjsfile) { + if ($uploadjs_shim != '') { $shimkeys[] = $currentkey . '-uploadjs'; //remove .js from end of js filepath if its there - if(strrpos($uploadjs,'.js')==(strlen($uploadjs) -3)){ + if (strrpos($uploadjs, '.js') == (strlen($uploadjs) - 3)) { $uploadjs = substr($uploadjs, 0, -3); } - $shimpaths[]=$uploadjs; - $shimexports[]=$uploadjs_shim; - $requires[] = "'" . $currentkey . '-uploadjs' . "'"; - $params[]=$uploadjs_shim; - }else{ - $requires[] = "'" . $uploadjs . "'"; + $shimpaths[] = $uploadjs; + $shimexports[] = $uploadjs_shim; + $requires[] = "'" . $currentkey . '-uploadjs' . "'"; + $params[] = $uploadjs_shim; + } else { + $requires[] = "'" . $uploadjs . "'"; $params[] = "uploadjs_" . $currentkey; } } @@ -158,7 +155,6 @@ public function get_template_script(){ //actually we build a php object first, and then we will json_encode it $theshim = $this->build_shim_function($currentkey, $shimkeys, $shimpaths, $shimexports); - //load a different jquery based on path if we are shimming //this is because, sigh, Moodle used no conflict for jquery, but //shimmed plugins rely on jquery n global scope @@ -166,46 +162,47 @@ public function get_template_script(){ //so we add a separate load of jquery with name '[currentkey]-jquery' and export it as '$', and don't use the //already set up (by mooodle and AMD) 'jquery' path. //we add jquery to beginning of requires and params using unshift. But the end would be find too - if(!empty($shimkeys)){ - array_unshift($requires,"'" . $currentkey . '-jquery' . "'"); - array_unshift($params,'$'); - }else{ - array_unshift($requires,"'" . 'jquery' . "'"); - array_unshift($params,'$'); - array_unshift($requires,"'" . 'jqueryui' . "'"); - array_unshift($params,'jqui'); + if (!empty($shimkeys)) { + array_unshift($requires, "'" . $currentkey . '-jquery' . "'"); + array_unshift($params, '$'); + } else { + array_unshift($requires, "'" . 'jquery' . "'"); + array_unshift($params, '$'); + array_unshift($requires, "'" . 'jqueryui' . "'"); + array_unshift($params, 'jqui'); } //Assemble the final javascript to pass to browser - $thefunction = "define('filter_generico_d" . $tindex . "',[" . implode(',',$requires) . "], function(" . implode(',',$params) . "){ "; - $thefunction .= "return function(opts){" . $thescript. " \r\n}; });"; + $thefunction = "define('filter_generico_d" . $tindex . "',[" . implode(',', $requires) . "], function(" . + implode(',', $params) . "){ "; + $thefunction .= "return function(opts){" . $thescript . " \r\n}; });"; $return_js = $theshim . $thefunction; //If not AMD return regular JS - }else{ + } else { $return_js = "if(typeof filter_generico_extfunctions == 'undefined'){filter_generico_extfunctions={};}"; - $return_js .= "filter_generico_extfunctions['" . $tindex . "']= function(opts) {" . $thescript. " \r\n};"; + $return_js .= "filter_generico_extfunctions['" . $tindex . "']= function(opts) {" . $thescript . " \r\n};"; } return $return_js; }//end of function - protected function build_shim_function($currentkey, $shimkeys, $shimpaths, $shimexports){ + protected function build_shim_function($currentkey, $shimkeys, $shimpaths, $shimexports) { global $CFG; - $theshim=""; + $theshim = ""; $theshimtemplate = "requirejs.config(@@THESHIMCONFIG@@);"; - if(!empty($shimkeys)){ + if (!empty($shimkeys)) { $paths = new \stdClass(); $shim = new \stdClass(); //Add a path to a separetely loaded jquery for shimmed libraries - $paths->{$currentkey . '-jquery'} = $CFG->wwwroot . '/filter/generico/jquery/jquery-1.12.4.min'; + $paths->{$currentkey . '-jquery'} = $CFG->wwwroot . '/filter/generico/jquery/jquery-1.12.4.min'; $jquery_shimconfig = new \stdClass(); $jquery_shimconfig->exports = '$'; - $shim->{$currentkey . '-jquery'}=$jquery_shimconfig; + $shim->{$currentkey . '-jquery'} = $jquery_shimconfig; - for($i=0;$i{$shimkeys[$i]} = $shimpaths[$i]; $oneshimconfig = new \stdClass(); $oneshimconfig->exports = $shimexports[$i]; @@ -217,10 +214,10 @@ protected function build_shim_function($currentkey, $shimkeys, $shimpaths, $shim //we use php object -> json to kep it simple. //But its still not simple $theshimobject = new \stdClass(); - $theshimobject->paths=$paths; - $theshimobject->shim =$shim; - $theshimconfig=json_encode($theshimobject,JSON_UNESCAPED_SLASHES); - $theshim = str_replace('@@THESHIMCONFIG@@', $theshimconfig,$theshimtemplate); + $theshimobject->paths = $paths; + $theshimobject->shim = $shim; + $theshimconfig = json_encode($theshimobject, JSON_UNESCAPED_SLASHES); + $theshim = str_replace('@@THESHIMCONFIG@@', $theshimconfig, $theshimtemplate); } return $theshim; } diff --git a/classes/templateadmintools.php b/classes/templateadmintools.php index 228eeb1..579007b 100644 --- a/classes/templateadmintools.php +++ b/classes/templateadmintools.php @@ -27,106 +27,104 @@ */ class templateadmintools { - /** * Returns an HTML string + * * @return string Returns an HTML string */ public static function fetch_template_table() { - global $OUTPUT,$CFG; + global $OUTPUT, $CFG; $conf = get_config('filter_generico'); $template_details = self::fetch_template_details($conf); - $have_updates=false; - - + $have_updates = false; $table = new \html_table(); $table->id = 'filter_generico_template_list'; $table->head = array( - get_string('name'), - get_string('version'), - get_string('description') + get_string('name'), + get_string('version'), + get_string('description') ); - $table->headspan = array(1,1,1); + $table->headspan = array(1, 1, 1); $table->colclasses = array( - 'templatenamecol', 'templateversioncol' ,'templateinstructionscol' + 'templatenamecol', 'templateversioncol', 'templateinstructionscol' ); //loop through templates and add to table foreach ($template_details as $item) { $row = new \html_table_row(); - $titlelink = $editlink = \html_writer::link($item->url,$item->title); + $titlelink = $editlink = \html_writer::link($item->url, $item->title); $titlecell = new \html_table_cell($titlelink); //version cell $updateversion = presets_control::template_has_update($item->index); - if($updateversion) { - $button = new \single_button( - new \moodle_url($CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php',array('updatetemplate'=>$item->index)), - get_string('updatetoversion','filter_generico',$updateversion)); + if ($updateversion) { + $button = new \single_button( + new \moodle_url($CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php', + array('updatetemplate' => $item->index)), + get_string('updatetoversion', 'filter_generico', $updateversion)); $update_html = $OUTPUT->render($button); $versioncell = new \html_table_cell($item->version . $update_html); - $have_updates=true; - }else{ + $have_updates = true; + } else { $versioncell = new \html_table_cell($item->version); } - $instructionscell = new \html_table_cell($item->instructions); $row->cells = array( - $titlecell, $versioncell, $instructionscell + $titlecell, $versioncell, $instructionscell ); $table->data[] = $row; } - $template_table= \html_writer::table($table); + $template_table = \html_writer::table($table); //if have_updates - $update_all_html=''; - if($have_updates){ - $all_button = new \single_button( - new \moodle_url($CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php',array('updatetemplate'=>-1)), - get_string('updateall','filter_generico')); + $update_all_html = ''; + if ($have_updates) { + $all_button = new \single_button( + new \moodle_url($CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php', array('updatetemplate' => -1)), + get_string('updateall', 'filter_generico')); $update_all_html = $OUTPUT->render($all_button); } + return $update_all_html . $template_table; - return $update_all_html . $template_table; - - }//end of output html + }//end of output html - public static function fetch_template_details($conf){ + public static function fetch_template_details($conf) { global $CFG; $ret = array(); //Get template count - if($conf && property_exists($conf,'templatecount')){ + if ($conf && property_exists($conf, 'templatecount')) { $templatecount = $conf->templatecount; - }else{ + } else { $templatecount = generico_utils::FILTER_GENERICO_TEMPLATE_COUNT; } - for($tindex=1;$tindex<=$templatecount;$tindex++) { - + for ($tindex = 1; $tindex <= $templatecount; $tindex++) { //template display name - if($conf && property_exists($conf,'templatename_' . $tindex)) { + if ($conf && property_exists($conf, 'templatename_' . $tindex)) { $template_title = $conf->{'templatename_' . $tindex}; if (empty($template_title)) { - if(property_exists($conf,'templatekey_' . $tindex)){ + if (property_exists($conf, 'templatekey_' . $tindex)) { $template_title = $conf->{'templatekey_' . $tindex}; } if (empty($template_title)) { $template_title = $tindex; } } - }elseif($conf && property_exists($conf,'templatekey_' . $tindex)){ - $template_title = $conf->{'templatekey_' . $tindex}; - if(empty($template_title )){ $template_title =$tindex;} - }else{ - $template_title = $tindex; + } else if ($conf && property_exists($conf, 'templatekey_' . $tindex)) { + $template_title = $conf->{'templatekey_' . $tindex}; + if (empty($template_title)) { + $template_title = $tindex; + } + } else { + $template_title = $tindex; } $template_details = new \stdClass(); @@ -134,18 +132,18 @@ public static function fetch_template_details($conf){ $template_details->title = $template_title; $template_details->version = ""; - if(property_exists($conf,'templateversion_' . $tindex)){ + if (property_exists($conf, 'templateversion_' . $tindex)) { $template_details->version = $conf->{'templateversion_' . $tindex}; } - - $template_details->instructions =""; - if(property_exists($conf,'templateinstructions_' . $tindex)) { + $template_details->instructions = ""; + if (property_exists($conf, 'templateinstructions_' . $tindex)) { $template_details->instructions = $conf->{'templateinstructions_' . $tindex}; } - $template_details->url = new \moodle_url( '/admin/settings.php', array('section'=> 'filter_generico_templatepage_' . $tindex)); - $ret[]=$template_details; + $template_details->url = + new \moodle_url('/admin/settings.php', array('section' => 'filter_generico_templatepage_' . $tindex)); + $ret[] = $template_details; } return $ret; }//end of fetch_templates function diff --git a/db/install.php b/db/install.php index 00a1161..22824a1 100644 --- a/db/install.php +++ b/db/install.php @@ -28,16 +28,16 @@ * Install the plugin. */ function xmldb_filter_generico_install() { - $admin_presets = new \filter_generico\presets_control('filter_generico/templatepresets_0', - 'presets', '',0); + $admin_presets = new \filter_generico\presets_control('filter_generico/templatepresets_0', + 'presets', '', 0); $presets = $admin_presets->fetch_presets(); - $forinstall = array('welcomeuser'); - $templateindex=0; - foreach($presets as $preset){ - if(in_array($preset['key'],$forinstall)){ - $templateindex++; - //set the config - $admin_presets->set_preset_to_config($preset,$templateindex); - } - }//end of for each presets + $forinstall = array('welcomeuser'); + $templateindex = 0; + foreach ($presets as $preset) { + if (in_array($preset['key'], $forinstall)) { + $templateindex++; + //set the config + $admin_presets->set_preset_to_config($preset, $templateindex); + } + }//end of for each presets } \ No newline at end of file diff --git a/db/upgrade.php b/db/upgrade.php index 83151a4..c8ae848 100644 --- a/db/upgrade.php +++ b/db/upgrade.php @@ -25,7 +25,6 @@ defined('MOODLE_INTERNAL') || die(); - /** * @param int $oldversion the version we are upgrading from * @return bool result @@ -35,26 +34,24 @@ function xmldb_filter_generico_upgrade($oldversion) { $dbman = $DB->get_manager(); - if ($oldversion < 2015080301) { - - - $conf = get_object_vars(get_config('filter_generico')); - - //determine which template we are using - for($tempindex=1;$tempindex<=20;$tempindex++){ - switch ($conf['templatekey_' . $tempindex]){ - case 'lightboxyoutube': - case 'piechart': - case 'barchart': - case 'linechart': - set_config('filter_generico/template_amd_' . $tempindex,0,'filter_generico'); - break; - default: - set_config('template_amd_' . $tempindex,1,'filter_generico'); - } - } + + $conf = get_object_vars(get_config('filter_generico')); + + //determine which template we are using + for ($tempindex = 1; $tempindex <= 20; $tempindex++) { + switch ($conf['templatekey_' . $tempindex]) { + case 'lightboxyoutube': + case 'piechart': + case 'barchart': + case 'linechart': + set_config('filter_generico/template_amd_' . $tempindex, 0, 'filter_generico'); + break; + default: + set_config('template_amd_' . $tempindex, 1, 'filter_generico'); + } + } upgrade_plugin_savepoint(true, 2015080301, 'filter', 'generico'); } @@ -64,16 +61,16 @@ function xmldb_filter_generico_upgrade($oldversion) { //Add the template name to the template $conf = get_config('filter_generico'); //Get template count - if(property_exists($conf,'templatecount')){ + if (property_exists($conf, 'templatecount')) { $templatecount = $conf->templatecount; - }else{ - $templatecount = \filter_generico\generico_utils::FILTER_GENERICO_TEMPLATE_COUNT; + } else { + $templatecount = \filter_generico\generico_utils::FILTER_GENERICO_TEMPLATE_COUNT; } //determine which template we are using - for($tempindex=1;$tempindex<=$templatecount;$tempindex++){ - if(property_exists($conf,'templatekey_' . $tempindex)){ - set_config('templatename_' . $tempindex,$conf->{'templatekey_' . $tempindex},'filter_generico'); + for ($tempindex = 1; $tempindex <= $templatecount; $tempindex++) { + if (property_exists($conf, 'templatekey_' . $tempindex)) { + set_config('templatename_' . $tempindex, $conf->{'templatekey_' . $tempindex}, 'filter_generico'); } } upgrade_plugin_savepoint(true, 2017032405, 'filter', 'generico'); diff --git a/filter.php b/filter.php index 714a0ed..ed7a155 100644 --- a/filter.php +++ b/filter.php @@ -16,7 +16,7 @@ // along with Moodle. If not, see . /** - * Filter for expanding Generico templates + * Filter for expanding Generico templates * * @package filter * @subpackage generico @@ -26,7 +26,6 @@ defined('MOODLE_INTERNAL') || die(); - class filter_generico extends moodle_text_filter { /** @@ -38,466 +37,476 @@ class filter_generico extends moodle_text_filter { * @return string text after processing */ public function filter($text, array $options = array()) { - //if we don't even have our tag, just bail out - if(strpos($text,'{GENERICO:')===false){ - return $text; - } - - $search = '/{GENERICO:.*?}/is'; - if (!is_string($text)) { - // non string data can not be filtered anyway - return $text; - } - $newtext=$text; - - $newtext = preg_replace_callback($search, 'filter_generico_callback', $newtext); - - if (is_null($newtext) or $newtext === $text) { - // error or not filtered - return $text; - } - - return $newtext; + //if we don't even have our tag, just bail out + if (strpos($text, '{GENERICO:') === false) { + return $text; + } + + $search = '/{GENERICO:.*?}/is'; + if (!is_string($text)) { + // non string data can not be filtered anyway + return $text; + } + $newtext = $text; + + $newtext = preg_replace_callback($search, 'filter_generico_callback', $newtext); + + if (is_null($newtext) or $newtext === $text) { + // error or not filtered + return $text; + } + + return $newtext; } - -}//end of class +}//end of class /* * Callback function , exists outside of class definition(because its a callback ...) * */ -function filter_generico_callback(array $link){ - global $CFG, $COURSE, $USER, $PAGE, $DB; - - $conf = get_object_vars(get_config('filter_generico')); - $context=false;//we get this if when we need it - - //get our filter props - $filterprops=\filter_generico\generico_utils::fetch_filter_properties($link[0]); - - //if we have no props, quit - if(empty($filterprops)){return "";} - - //we use this to see if its a web service calling this, - //in which case we return the alternate content +function filter_generico_callback(array $link) { + global $CFG, $COURSE, $USER, $PAGE, $DB; + + $conf = get_object_vars(get_config('filter_generico')); + $context = false;//we get this if when we need it + + //get our filter props + $filterprops = \filter_generico\generico_utils::fetch_filter_properties($link[0]); + + //if we have no props, quit + if (empty($filterprops)) { + return ""; + } + + //we use this to see if its a web service calling this, + //in which case we return the alternate content $climode = defined('CLI_SCRIPT') && CLI_SCRIPT; - $is_webservice = false; - if(!$climode){ - //we get a warning here if the PAGE url is not set. But its not dangerous. just annoying., - $is_webservice = strpos($PAGE->url, $CFG->wwwroot . '/webservice/') === 0; - } - - - //if we want to ignore the filter (for "how to use generico" or "cut and paste" this style use) we let it go - //to use this, make the last parameter of the filter passthrough=1 - if (!empty($filterprops['passthrough'])) return str_replace( ",passthrough=1","",$link[0]); - - //Perform role/permissions check on this filter + $is_webservice = false; + if (!$climode) { + //we get a warning here if the PAGE url is not set. But its not dangerous. just annoying., + $is_webservice = strpos($PAGE->url, $CFG->wwwroot . '/webservice/') === 0; + } + + //if we want to ignore the filter (for "how to use generico" or "cut and paste" this style use) we let it go + //to use this, make the last parameter of the filter passthrough=1 + if (!empty($filterprops['passthrough'])) { + return str_replace(",passthrough=1", "", $link[0]); + } + + //Perform role/permissions check on this filter if (!empty($filterprops['viewcapability'])) { - if(!$context) { + if (!$context) { $context = context_course::instance($COURSE->id); } - if(!has_capability($filterprops['viewcapability'],$context)) { + if (!has_capability($filterprops['viewcapability'], $context)) { return ''; } } if (!empty($filterprops['hidecapability'])) { - if(!$context) { + if (!$context) { $context = context_course::instance($COURSE->id); } - if(has_capability($filterprops['hidecapability'],$context)) { + if (has_capability($filterprops['hidecapability'], $context)) { return ''; } } - - //determine which template we are using - $endtag=false; - for($tempindex=1;$tempindex<=$conf['templatecount'];$tempindex++){ - if($filterprops['type']==$conf['templatekey_' . $tempindex]){ - break; - }elseif($filterprops['type']==$conf['templatekey_' . $tempindex] . '_end'){ - $endtag = true; - break; - } - } - //no key could be found if got all the way to the last template - if($tempindex==$conf['templatecount']+1){return '';} - - //fetch our template - if($endtag){ - $genericotemplate = $conf['templateend_' . $tempindex]; - //fetch alternate content (for use when no css or js available ala mobile app.) - $alternate_content = $conf['templatealternate_end_' . $tempindex]; - }else{ - $genericotemplate = $conf['template_' . $tempindex]; - //fetch alternate content (for use when no css or js available ala mobile app.) - $alternate_content = $conf['templatealternate_' . $tempindex]; - } - - //fetch dataset info - $dataset_body = $conf['dataset_' . $tempindex]; - $dataset_vars = $conf['datasetvars_' . $tempindex]; - - //js custom script - //we really just want to be sure anything that appears in custom script - //is stored in $filterprops and passed to js. we dont replace it server side because - //of caching - $js_custom_script = $conf['templatescript_' . $tempindex]; - - - - //replace the specified names with spec values - foreach($filterprops as $name=>$value){ - $genericotemplate = str_replace('@@' . $name .'@@',$value,$genericotemplate); - $dataset_vars = str_replace('@@' . $name .'@@',$value,$dataset_vars); - $alternate_content = str_replace('@@' . $name .'@@',$value,$alternate_content); - } - - //fetch defaults for this template - $defaults = $conf['templatedefaults_'. $tempindex]; - if(!empty($defaults)){ - $defaults = "{GENERICO:" . $defaults . "}"; - $defaultprops=\filter_generico\generico_utils::fetch_filter_properties($defaults); - //replace our defaults, if not spec in the the filter string - if(!empty($defaultprops)){ - foreach($defaultprops as $name=>$value){ - if(!array_key_exists($name,$filterprops)){ - //if we have options as defaults, lets just take the first one - if(strpos($value,'|')!==false){ - $value=explode('|',$value)[0]; - } - $genericotemplate = str_replace('@@' . $name .'@@',strip_tags($value),$genericotemplate); - $dataset_vars = str_replace('@@' . $name .'@@',strip_tags($value),$dataset_vars); - $alternate_content = str_replace('@@' . $name .'@@',strip_tags($value),$alternate_content); - - //stash for using in JS later - $filterprops[$name]=$value; - } - } - } - } - - //If we have autoid lets deal with that - $autoid = 'fg_' . time() . (string)rand(100,32767) ; - $genericotemplate = str_replace('@@AUTOID@@',$autoid,$genericotemplate); - $alternate_content = str_replace('@@AUTOID@@',$autoid,$alternate_content); - //stash this for passing to js - $filterprops['AUTOID']=$autoid; + + //determine which template we are using + $endtag = false; + for ($tempindex = 1; $tempindex <= $conf['templatecount']; $tempindex++) { + if ($filterprops['type'] == $conf['templatekey_' . $tempindex]) { + break; + } else if ($filterprops['type'] == $conf['templatekey_' . $tempindex] . '_end') { + $endtag = true; + break; + } + } + //no key could be found if got all the way to the last template + if ($tempindex == $conf['templatecount'] + 1) { + return ''; + } + + //fetch our template + if ($endtag) { + $genericotemplate = $conf['templateend_' . $tempindex]; + //fetch alternate content (for use when no css or js available ala mobile app.) + $alternate_content = $conf['templatealternate_end_' . $tempindex]; + } else { + $genericotemplate = $conf['template_' . $tempindex]; + //fetch alternate content (for use when no css or js available ala mobile app.) + $alternate_content = $conf['templatealternate_' . $tempindex]; + } + + //fetch dataset info + $dataset_body = $conf['dataset_' . $tempindex]; + $dataset_vars = $conf['datasetvars_' . $tempindex]; + + //js custom script + //we really just want to be sure anything that appears in custom script + //is stored in $filterprops and passed to js. we dont replace it server side because + //of caching + $js_custom_script = $conf['templatescript_' . $tempindex]; + + //replace the specified names with spec values + foreach ($filterprops as $name => $value) { + $genericotemplate = str_replace('@@' . $name . '@@', $value, $genericotemplate); + $dataset_vars = str_replace('@@' . $name . '@@', $value, $dataset_vars); + $alternate_content = str_replace('@@' . $name . '@@', $value, $alternate_content); + } + + //fetch defaults for this template + $defaults = $conf['templatedefaults_' . $tempindex]; + if (!empty($defaults)) { + $defaults = "{GENERICO:" . $defaults . "}"; + $defaultprops = \filter_generico\generico_utils::fetch_filter_properties($defaults); + //replace our defaults, if not spec in the the filter string + if (!empty($defaultprops)) { + foreach ($defaultprops as $name => $value) { + if (!array_key_exists($name, $filterprops)) { + //if we have options as defaults, lets just take the first one + if (strpos($value, '|') !== false) { + $value = explode('|', $value)[0]; + } + $genericotemplate = str_replace('@@' . $name . '@@', strip_tags($value), $genericotemplate); + $dataset_vars = str_replace('@@' . $name . '@@', strip_tags($value), $dataset_vars); + $alternate_content = str_replace('@@' . $name . '@@', strip_tags($value), $alternate_content); + + //stash for using in JS later + $filterprops[$name] = $value; + } + } + } + } + + //If we have autoid lets deal with that + $autoid = 'fg_' . time() . (string) rand(100, 32767); + $genericotemplate = str_replace('@@AUTOID@@', $autoid, $genericotemplate); + $alternate_content = str_replace('@@AUTOID@@', $autoid, $alternate_content); + //stash this for passing to js + $filterprops['AUTOID'] = $autoid; //If we need a Cloud Poodll token, lets fetch it - if(strpos($genericotemplate,'@@CLOUDPOODLLTOKEN@@') && - !empty($conf['cpapiuser']) && - !empty($conf['cpapisecret'])){ - $token = \filter_generico\generico_utils::fetch_token($conf['cpapiuser'],$conf['cpapisecret']); - $genericotemplate = str_replace('@@CLOUDPOODLLTOKEN@@',$token,$genericotemplate); + if (strpos($genericotemplate, '@@CLOUDPOODLLTOKEN@@') && + !empty($conf['cpapiuser']) && + !empty($conf['cpapisecret'])) { + $token = \filter_generico\generico_utils::fetch_token($conf['cpapiuser'], $conf['cpapisecret']); + if ($token) { + $genericotemplate = str_replace('@@CLOUDPOODLLTOKEN@@', $token, $genericotemplate); + } else { + $genericotemplate = str_replace('@@CLOUDPOODLLTOKEN@@', 'INVALID TOKEN', $genericotemplate); + } } - //If template requires a MOODLEPAGEID lets give them one - //this is legacy really. Now we have @@URLPARAM we could do it that way - $moodlepageid = optional_param('id',0,PARAM_INT); - $genericotemplate = str_replace('@@MOODLEPAGEID@@',$moodlepageid,$genericotemplate); - $dataset_vars = str_replace('@@MOODLEPAGEID@@',$moodlepageid,$dataset_vars); - $alternate_content = str_replace('@@MOODLEPAGEID@@',$moodlepageid,$alternate_content); - - //stash this for passing to js - $filterprops['MOODLEPAGEID']=$moodlepageid; - - - //if we have urlparam variables e.g @@URLPARAM:id@@ - if(strpos($genericotemplate . ' ' . $dataset_vars . ' ' - . $alternate_content . ' ' . $js_custom_script ,'@@URLPARAM:')!==false){ - $urlparamstubs = explode('@@URLPARAM:',$genericotemplate); - - $dv_stubs = explode('@@URLPARAM:',$dataset_vars); - if($dv_stubs){ - $urlparamstubs = array_merge($urlparamstubs,$dv_stubs); - } - - $js_stubs = explode('@@URLPARAM:',$js_custom_script); - if($js_stubs){ - $urlparamstubs = array_merge($urlparamstubs,$js_stubs); - } - - $alt_stubs = explode('@@URLPARAM:',$alternate_content); - if($alt_stubs){ - $urlparamstubs = array_merge($urlparamstubs,$alt_stubs); - } - - //URL Param Props - $count=0; - foreach($urlparamstubs as $propstub){ - //we don't want the first one, its junk - $count++; - if($count==1){continue;} - //init our prop value - $propvalue=false; - - //fetch the property name - //user can use any case, but we work with lower case version - $end = strpos($propstub,'@@'); - $urlprop = substr($propstub,0,$end); - if(empty($urlprop)){continue;} - - //check if it exists in the params to the url and if so, set it. - $propvalue = optional_param($urlprop,'',PARAM_TEXT); - $genericotemplate = str_replace('@@URLPARAM:' . $urlprop .'@@',$propvalue,$genericotemplate); - $dataset_vars = str_replace('@@URLPARAM:' . $urlprop .'@@',$propvalue,$dataset_vars); - $alternate_content = str_replace('@@URLPARAM:' . $urlprop .'@@',$propvalue,$alternate_content); - - //stash this for passing to js - $filterprops['URLPARAM:' . $urlprop]=$propvalue; - }//end of for each - }//end of if we have@@URLPARAM - - - //we should stash our wwwroot too - $genericotemplate = str_replace('@@WWWROOT@@',$CFG->wwwroot,$genericotemplate); - $dataset_vars = str_replace('@@WWWROOT@@',$CFG->wwwroot,$dataset_vars); - $alternate_content = str_replace('@@WWWROOT@@',$CFG->wwwroot,$alternate_content); - - //actually this is available from JS anyway M.cfg.wwwroot . But lets make it easy for people - $filterprops['WWWROOT']=$CFG->wwwroot; - - - //if we have course variables e.g @@COURSE:ID@@ - if(strpos($genericotemplate . ' ' . $dataset_vars ,'@@COURSE:')!==false){ - $coursevars = get_object_vars($COURSE); - $coursepropstubs = explode('@@COURSE:',$genericotemplate); - $d_stubs = explode('@@COURSE:',$dataset_vars); - if($d_stubs){ - $coursepropstubs = array_merge($coursepropstubs,$d_stubs); - } - $j_stubs=explode('@@COURSE:',$js_custom_script); - if($j_stubs){ - $coursepropstubs = array_merge($coursepropstubs,$j_stubs); - } - $alt_stubs=explode('@@COURSE:',$alternate_content); - if($alt_stubs){ - $coursepropstubs = array_merge($coursepropstubs,$alt_stubs); - } - - - //Course Props - $profileprops=false; - $count=0; - foreach($coursepropstubs as $propstub){ - //we don't want the first one, its junk - $count++; - if($count==1){continue;} - //init our prop value - $propvalue=false; - - //fetch the property name - //user can use any case, but we work with lower case version - $end = strpos($propstub,'@@'); - $courseprop_allcase = substr($propstub,0,$end); - $courseprop=strtolower($courseprop_allcase); - - //check if it exists in course - if(array_key_exists($courseprop,$coursevars)){ - $propvalue=$coursevars[$courseprop]; - }elseif($courseprop=='contextid'){ - if(!$context) { - $context = context_course::instance($COURSE->id); + //If template requires a MOODLEPAGEID lets give them one + //this is legacy really. Now we have @@URLPARAM we could do it that way + $moodlepageid = optional_param('id', 0, PARAM_INT); + $genericotemplate = str_replace('@@MOODLEPAGEID@@', $moodlepageid, $genericotemplate); + $dataset_vars = str_replace('@@MOODLEPAGEID@@', $moodlepageid, $dataset_vars); + $alternate_content = str_replace('@@MOODLEPAGEID@@', $moodlepageid, $alternate_content); + + //stash this for passing to js + $filterprops['MOODLEPAGEID'] = $moodlepageid; + + //if we have urlparam variables e.g @@URLPARAM:id@@ + if (strpos($genericotemplate . ' ' . $dataset_vars . ' ' + . $alternate_content . ' ' . $js_custom_script, '@@URLPARAM:') !== false) { + $urlparamstubs = explode('@@URLPARAM:', $genericotemplate); + + $dv_stubs = explode('@@URLPARAM:', $dataset_vars); + if ($dv_stubs) { + $urlparamstubs = array_merge($urlparamstubs, $dv_stubs); + } + + $js_stubs = explode('@@URLPARAM:', $js_custom_script); + if ($js_stubs) { + $urlparamstubs = array_merge($urlparamstubs, $js_stubs); + } + + $alt_stubs = explode('@@URLPARAM:', $alternate_content); + if ($alt_stubs) { + $urlparamstubs = array_merge($urlparamstubs, $alt_stubs); + } + + //URL Param Props + $count = 0; + foreach ($urlparamstubs as $propstub) { + //we don't want the first one, its junk + $count++; + if ($count == 1) { + continue; + } + //init our prop value + $propvalue = false; + + //fetch the property name + //user can use any case, but we work with lower case version + $end = strpos($propstub, '@@'); + $urlprop = substr($propstub, 0, $end); + if (empty($urlprop)) { + continue; + } + + //check if it exists in the params to the url and if so, set it. + $propvalue = optional_param($urlprop, '', PARAM_TEXT); + $genericotemplate = str_replace('@@URLPARAM:' . $urlprop . '@@', $propvalue, $genericotemplate); + $dataset_vars = str_replace('@@URLPARAM:' . $urlprop . '@@', $propvalue, $dataset_vars); + $alternate_content = str_replace('@@URLPARAM:' . $urlprop . '@@', $propvalue, $alternate_content); + + //stash this for passing to js + $filterprops['URLPARAM:' . $urlprop] = $propvalue; + }//end of for each + }//end of if we have@@URLPARAM + + //we should stash our wwwroot too + $genericotemplate = str_replace('@@WWWROOT@@', $CFG->wwwroot, $genericotemplate); + $dataset_vars = str_replace('@@WWWROOT@@', $CFG->wwwroot, $dataset_vars); + $alternate_content = str_replace('@@WWWROOT@@', $CFG->wwwroot, $alternate_content); + + //actually this is available from JS anyway M.cfg.wwwroot . But lets make it easy for people + $filterprops['WWWROOT'] = $CFG->wwwroot; + + //if we have course variables e.g @@COURSE:ID@@ + if (strpos($genericotemplate . ' ' . $dataset_vars, '@@COURSE:') !== false) { + $coursevars = get_object_vars($COURSE); + $coursepropstubs = explode('@@COURSE:', $genericotemplate); + $d_stubs = explode('@@COURSE:', $dataset_vars); + if ($d_stubs) { + $coursepropstubs = array_merge($coursepropstubs, $d_stubs); + } + $j_stubs = explode('@@COURSE:', $js_custom_script); + if ($j_stubs) { + $coursepropstubs = array_merge($coursepropstubs, $j_stubs); + } + $alt_stubs = explode('@@COURSE:', $alternate_content); + if ($alt_stubs) { + $coursepropstubs = array_merge($coursepropstubs, $alt_stubs); + } + + //Course Props + $profileprops = false; + $count = 0; + foreach ($coursepropstubs as $propstub) { + //we don't want the first one, its junk + $count++; + if ($count == 1) { + continue; + } + //init our prop value + $propvalue = false; + + //fetch the property name + //user can use any case, but we work with lower case version + $end = strpos($propstub, '@@'); + $courseprop_allcase = substr($propstub, 0, $end); + $courseprop = strtolower($courseprop_allcase); + + //check if it exists in course + if (array_key_exists($courseprop, $coursevars)) { + $propvalue = $coursevars[$courseprop]; + } else if ($courseprop == 'contextid') { + if (!$context) { + $context = context_course::instance($COURSE->id); + } + if ($context) { + $propvalue = $context->id; + } + } + //if we have a propname and a propvalue, do the replace + if (!empty($courseprop) && !empty($propvalue)) { + $genericotemplate = str_replace('@@COURSE:' . $courseprop_allcase . '@@', $propvalue, $genericotemplate); + $dataset_vars = str_replace('@@COURSE:' . $courseprop_allcase . '@@', $propvalue, $dataset_vars); + $alternate_content = str_replace('@@COURSE:' . $courseprop_allcase . '@@', $propvalue, $alternate_content); + //stash this for passing to js + $filterprops['COURSE:' . $courseprop_allcase] = $propvalue; + } + } + }//end of if @@COURSE + + //if we have user variables e.g @@USER:FIRSTNAME@@ + //It is a bit wordy, because trying to avoid loading a lib + //or making a DB call if unneccessary + if (strpos($genericotemplate . ' ' . $dataset_vars . ' ' . $js_custom_script, '@@USER:') !== false) { + $uservars = get_object_vars($USER); + $userpropstubs = explode('@@USER:', $genericotemplate); + $d_stubs = explode('@@USER:', $dataset_vars); + if ($d_stubs) { + $userpropstubs = array_merge($userpropstubs, $d_stubs); + } + $j_stubs = explode('@@USER:', $js_custom_script); + if ($j_stubs) { + $userpropstubs = array_merge($userpropstubs, $j_stubs); + } + + //User Props + $profileprops = false; + $count = 0; + foreach ($userpropstubs as $propstub) { + //we don't want the first one, its junk + $count++; + if ($count == 1) { + continue; + } + //init our prop value + $propvalue = false; + + //fetch the property name + //user can use any case, but we work with lower case version + $end = strpos($propstub, '@@'); + $userprop_allcase = substr($propstub, 0, $end); + $userprop = strtolower($userprop_allcase); + + //check if it exists in user, else look for it in profile fields + if (array_key_exists($userprop, $uservars)) { + $propvalue = $uservars[$userprop]; + } else { + if (!$profileprops) { + require_once("$CFG->dirroot/user/profile/lib.php"); + $profileprops = get_object_vars(profile_user_record($USER->id)); + } + if ($profileprops && array_key_exists($userprop, $profileprops)) { + $propvalue = $profileprops[$userprop]; + } else { + switch ($userprop) { + case 'picurl': + require_once("$CFG->libdir/outputcomponents.php"); + global $PAGE; + $user_picture = new user_picture($USER); + $propvalue = $user_picture->get_url($PAGE); + break; + + case 'pic': + global $OUTPUT; + $propvalue = $OUTPUT->user_picture($USER, array('popup' => true)); + break; } - if($context){ - $propvalue=$context->id; - } - } - //if we have a propname and a propvalue, do the replace - if(!empty($courseprop) && !empty($propvalue)){ - $genericotemplate = str_replace('@@COURSE:' . $courseprop_allcase .'@@',$propvalue,$genericotemplate); - $dataset_vars = str_replace('@@COURSE:' . $courseprop_allcase .'@@',$propvalue,$dataset_vars); - $alternate_content = str_replace('@@COURSE:' . $courseprop_allcase .'@@',$propvalue,$alternate_content); - //stash this for passing to js - $filterprops['COURSE:' . $courseprop_allcase]=$propvalue; - } - } - }//end of if @@COURSE - - //if we have user variables e.g @@USER:FIRSTNAME@@ - //It is a bit wordy, because trying to avoid loading a lib - //or making a DB call if unneccessary - if(strpos($genericotemplate . ' ' . $dataset_vars . ' ' . $js_custom_script ,'@@USER:')!==false){ - $uservars = get_object_vars($USER); - $userpropstubs = explode('@@USER:',$genericotemplate); - $d_stubs = explode('@@USER:',$dataset_vars); - if($d_stubs){ - $userpropstubs = array_merge($userpropstubs,$d_stubs); - } - $j_stubs = explode('@@USER:',$js_custom_script); - if($j_stubs){ - $userpropstubs = array_merge($userpropstubs,$j_stubs); - } - - //User Props - $profileprops=false; - $count=0; - foreach($userpropstubs as $propstub){ - //we don't want the first one, its junk - $count++; - if($count==1){continue;} - //init our prop value - $propvalue=false; - - //fetch the property name - //user can use any case, but we work with lower case version - $end = strpos($propstub,'@@'); - $userprop_allcase = substr($propstub,0,$end); - $userprop=strtolower($userprop_allcase); - - //check if it exists in user, else look for it in profile fields - if(array_key_exists($userprop,$uservars)){ - $propvalue=$uservars[$userprop]; - }else{ - if(!$profileprops){ - require_once("$CFG->dirroot/user/profile/lib.php"); - $profileprops = get_object_vars(profile_user_record($USER->id)); - } - if($profileprops && array_key_exists($userprop,$profileprops)){ - $propvalue=$profileprops[$userprop]; - }else{ - switch($userprop){ - case 'picurl': - require_once("$CFG->libdir/outputcomponents.php"); - global $PAGE; - $user_picture=new user_picture($USER); - $propvalue = $user_picture->get_url($PAGE); - break; - - case 'pic': - global $OUTPUT; - $propvalue = $OUTPUT->user_picture($USER, array('popup'=>true)); - break; - } - } - } - - //if we have a propname and a propvalue, do the replace - if(!empty($userprop) && !empty($propvalue)){ - //echo "userprop:" . $userprop . '
propvalue:' . $propvalue; - $genericotemplate = str_replace('@@USER:' . $userprop_allcase .'@@',$propvalue,$genericotemplate); - $dataset_vars = str_replace('@@USER:' . $userprop_allcase .'@@',$propvalue,$dataset_vars); - $alternate_content = str_replace('@@USER:' . $userprop_allcase .'@@',$propvalue,$alternate_content); - //stash this for passing to js - $filterprops['USER:' . $userprop_allcase]=$propvalue; - } - } - }//end of of we @@USER - - //if we have a dataset body - //we split the $data_vars string passed in by user (which should have had all the replacing done) - //into the vars array. This is passed to get_records_sql and the returned result is stored - //in filter props. If its a single record, its available to the body area. - //otherwise it needs to be accessewd from javascript in the DATASET variable - $filterprops['DATASET']=false; - if($dataset_body){ - $vars = array(); - if($dataset_vars){ - $vars=explode(',',$dataset_vars); - } - //turn numeric vars into numbers (not strings) - $query_vars = array(); - for($i = 0; $i < sizeof($vars); $i++) { - if(is_numeric($vars[$i])) { - $query_vars[] = intval($vars[$i]); - } else { - $query_vars[] = $vars[$i]; - } - } - - try { - $alldata = $DB->get_records_sql($dataset_body, $query_vars); - if($alldata) { - $filterprops['DATASET'] = $alldata; - //replace the specified names with spec values, if its a one element array - if (sizeof($filterprops['DATASET']) == 1) { - $thedata = get_object_vars(array_pop($alldata)); - foreach ($thedata as $name => $value) { - $genericotemplate = str_replace('@@DATASET:' . $name . '@@', $value, $genericotemplate); - $alternate_content = str_replace('@@DATASET:' . $name . '@@', $value, $alternate_content); - } - } - } - }catch(Exception $e){ - //do nothing; - } - }//end of if dataset - - //If this is a webservice request, we don't need subsequent CSS and JS stuff - if($is_webservice && !empty($alternate_content)){ - return $alternate_content; - } - - //If this is the end tag we don't need to subsequent CSS and JS stuff. We already did it. - if($endtag){ - return $genericotemplate; - } - - //get the conf info we need for this template - $thescript = $conf['templatescript_' . $tempindex]; - $defaults=$conf['templatedefaults_' . $tempindex]; - $require_js = $conf['templaterequire_js_' . $tempindex]; - $require_css = $conf['templaterequire_css_' . $tempindex]; - //are we AMD and Moodle 2.9 or more? - $require_amd = $conf['template_amd_' . $tempindex] && $CFG->version>=2015051100; - - //figure out if this is https or http. We don't want to scare the browser - if(!$climode && strpos($PAGE->url->out(),'https:')===0){ - $scheme='https:'; - }else{ - $scheme='http:'; - } - - //massage the js URL depending on schemes and rel. links etc. Then insert it - //with AMD we set these as dependencies, so we don't need this song and dance - if(!$require_amd){ - $filterprops['JSLINK']=false; - if($require_js){ - if(strpos($require_js,'//')===0){ - $require_js = $scheme . $require_js; - }elseif(strpos($require_js,'/')===0){ - $require_js = $CFG->wwwroot . $require_js; - } - - //for load method: NO AMD - $PAGE->requires->js(new moodle_url($require_js)); - - //for load method: AMD - //$require_js = substr($require_js, 0, -3); - $filterprops['JSLINK'] = $require_js; - } - - //if we have an uploaded JS file, then lets include that - $filterprops['JSUPLOAD']=false; - $uploadjsfile = $conf['uploadjs' . $tempindex]; - if($uploadjsfile){ - $uploadjsurl = \filter_generico\generico_utils::setting_file_url($uploadjsfile,'uploadjs' . $tempindex); - - //for load method: NO AMD - $PAGE->requires->js($uploadjsurl); - - //for load method: AMD - //$uploadjsurl = substr($uploadjsurl, 0, -3); - $filterprops['JSUPLOAD'] = $uploadjsurl; - } - } - - //massage the CSS URL depending on schemes and rel. links etc. - if(!empty($require_css)){ - if(strpos($require_css,'//')===0){ - $require_css = $scheme . $require_css; - }elseif(strpos($require_css,'/')===0){ - $require_css = $CFG->wwwroot . $require_css; - } - } - - //if we have an uploaded CSS file, then lets include that - $uploadcssfile = $conf['uploadcss' . $tempindex]; - if($uploadcssfile){ - $uploadcssurl = \filter_generico\generico_utils::setting_file_url($uploadcssfile,'uploadcss' . $tempindex); - } + } + } + + //if we have a propname and a propvalue, do the replace + if (!empty($userprop) && !empty($propvalue)) { + //echo "userprop:" . $userprop . '
propvalue:' . $propvalue; + $genericotemplate = str_replace('@@USER:' . $userprop_allcase . '@@', $propvalue, $genericotemplate); + $dataset_vars = str_replace('@@USER:' . $userprop_allcase . '@@', $propvalue, $dataset_vars); + $alternate_content = str_replace('@@USER:' . $userprop_allcase . '@@', $propvalue, $alternate_content); + //stash this for passing to js + $filterprops['USER:' . $userprop_allcase] = $propvalue; + } + } + }//end of of we @@USER + + //if we have a dataset body + //we split the $data_vars string passed in by user (which should have had all the replacing done) + //into the vars array. This is passed to get_records_sql and the returned result is stored + //in filter props. If its a single record, its available to the body area. + //otherwise it needs to be accessewd from javascript in the DATASET variable + $filterprops['DATASET'] = false; + if ($dataset_body) { + $vars = array(); + if ($dataset_vars) { + $vars = explode(',', $dataset_vars); + } + //turn numeric vars into numbers (not strings) + $query_vars = array(); + for ($i = 0; $i < sizeof($vars); $i++) { + if (is_numeric($vars[$i])) { + $query_vars[] = intval($vars[$i]); + } else { + $query_vars[] = $vars[$i]; + } + } + + try { + $alldata = $DB->get_records_sql($dataset_body, $query_vars); + if ($alldata) { + $filterprops['DATASET'] = $alldata; + //replace the specified names with spec values, if its a one element array + if (sizeof($filterprops['DATASET']) == 1) { + $thedata = get_object_vars(array_pop($alldata)); + foreach ($thedata as $name => $value) { + $genericotemplate = str_replace('@@DATASET:' . $name . '@@', $value, $genericotemplate); + $alternate_content = str_replace('@@DATASET:' . $name . '@@', $value, $alternate_content); + } + } + } + } catch (Exception $e) { + //do nothing; + } + }//end of if dataset + + //If this is a webservice request, we don't need subsequent CSS and JS stuff + if ($is_webservice && !empty($alternate_content)) { + return $alternate_content; + } + + //If this is the end tag we don't need to subsequent CSS and JS stuff. We already did it. + if ($endtag) { + return $genericotemplate; + } + + //get the conf info we need for this template + $thescript = $conf['templatescript_' . $tempindex]; + $defaults = $conf['templatedefaults_' . $tempindex]; + $require_js = $conf['templaterequire_js_' . $tempindex]; + $require_css = $conf['templaterequire_css_' . $tempindex]; + //are we AMD and Moodle 2.9 or more? + $require_amd = $conf['template_amd_' . $tempindex] && $CFG->version >= 2015051100; + + //figure out if this is https or http. We don't want to scare the browser + if (!$climode && strpos($PAGE->url->out(), 'https:') === 0) { + $scheme = 'https:'; + } else { + $scheme = 'http:'; + } + + //massage the js URL depending on schemes and rel. links etc. Then insert it + //with AMD we set these as dependencies, so we don't need this song and dance + if (!$require_amd) { + $filterprops['JSLINK'] = false; + if ($require_js) { + if (strpos($require_js, '//') === 0) { + $require_js = $scheme . $require_js; + } else if (strpos($require_js, '/') === 0) { + $require_js = $CFG->wwwroot . $require_js; + } + + //for load method: NO AMD + $PAGE->requires->js(new moodle_url($require_js)); + + //for load method: AMD + //$require_js = substr($require_js, 0, -3); + $filterprops['JSLINK'] = $require_js; + } + + //if we have an uploaded JS file, then lets include that + $filterprops['JSUPLOAD'] = false; + $uploadjsfile = $conf['uploadjs' . $tempindex]; + if ($uploadjsfile) { + $uploadjsurl = \filter_generico\generico_utils::setting_file_url($uploadjsfile, 'uploadjs' . $tempindex); + + //for load method: NO AMD + $PAGE->requires->js($uploadjsurl); + + //for load method: AMD + //$uploadjsurl = substr($uploadjsurl, 0, -3); + $filterprops['JSUPLOAD'] = $uploadjsurl; + } + } + + //massage the CSS URL depending on schemes and rel. links etc. + if (!empty($require_css)) { + if (strpos($require_css, '//') === 0) { + $require_css = $scheme . $require_css; + } else if (strpos($require_css, '/') === 0) { + $require_css = $CFG->wwwroot . $require_css; + } + } + + //if we have an uploaded CSS file, then lets include that + $uploadcssfile = $conf['uploadcss' . $tempindex]; + if ($uploadcssfile) { + $uploadcssurl = \filter_generico\generico_utils::setting_file_url($uploadcssfile, 'uploadcss' . $tempindex); + } //set up our revision flag for forcing cache refreshes etc if (!empty($conf['revision'])) { @@ -506,92 +515,89 @@ function filter_generico_callback(array $link){ $revision = '0'; } - //if not too late: load css in header - // if too late: inject it there via JS - $filterprops['CSSLINK']=false; - $filterprops['CSSUPLOAD']=false; - $filterprops['CSSCUSTOM']=false; + //if not too late: load css in header + // if too late: inject it there via JS + $filterprops['CSSLINK'] = false; + $filterprops['CSSUPLOAD'] = false; + $filterprops['CSSCUSTOM'] = false; - - //require any scripts from the template - $customcssurl=false; - if($conf['templatestyle_' . $tempindex]){ + //require any scripts from the template + $customcssurl = false; + if ($conf['templatestyle_' . $tempindex]) { $url = '/filter/generico/genericocss.php'; $params = array( - 't' => $tempindex, - 'rev' => $revision + 't' => $tempindex, + 'rev' => $revision ); - $customcssurl = new moodle_url($url, $params); - } - - if(!$PAGE->headerprinted && !$PAGE->requires->is_head_done()){ - if($require_css){ - $PAGE->requires->css( new moodle_url($require_css)); - } - if($uploadcssfile){ - $PAGE->requires->css($uploadcssurl); - } - if($customcssurl){ - $PAGE->requires->css($customcssurl); - } - }else{ - if($require_css){ - $filterprops['CSSLINK']=$require_css; - } - if($uploadcssfile){ - $filterprops['CSSUPLOAD']=$uploadcssurl->out(); - } - if($customcssurl){ - $filterprops['CSSCUSTOM']=$customcssurl->out(); - } - - } - - - //Tell javascript which template this is - $filterprops['TEMPLATEID'] = $tempindex; - - - $jsmodule = array( - 'name' => 'filter_generico', - 'fullpath' => '/filter/generico/module.js', - 'requires' => array('json') - ); - - - //AMD or not, and then load our js for this template on the page - if($require_amd){ - - $generator = new \filter_generico\template_script_generator($tempindex); - $template_amd_script = $generator->get_template_script(); - - //props can't be passed at much length , Moodle complains about too many - //so we do this ... lets hope it don't break things - $jsonstring = json_encode($filterprops); - $props_html = \html_writer::tag('input', '', array('id' => 'filter_generico_amdopts_' . $filterprops['AUTOID'], 'type' => 'hidden', 'value' => $jsonstring)); - $genericotemplate = $props_html . $genericotemplate; - - //load define for this template. Later it will be called from loadgenerico - $PAGE->requires->js_amd_inline($template_amd_script); - //for AMD generico script - $PAGE->requires->js_call_amd('filter_generico/generico_amd','loadgenerico', array(array('AUTOID'=>$filterprops['AUTOID']))); - - - }else{ - - //require any scripts from the template + $customcssurl = new moodle_url($url, $params); + } + + if (!$PAGE->headerprinted && !$PAGE->requires->is_head_done()) { + if ($require_css) { + $PAGE->requires->css(new moodle_url($require_css)); + } + if ($uploadcssfile) { + $PAGE->requires->css($uploadcssurl); + } + if ($customcssurl) { + $PAGE->requires->css($customcssurl); + } + } else { + if ($require_css) { + $filterprops['CSSLINK'] = $require_css; + } + if ($uploadcssfile) { + $filterprops['CSSUPLOAD'] = $uploadcssurl->out(); + } + if ($customcssurl) { + $filterprops['CSSCUSTOM'] = $customcssurl->out(); + } + + } + + //Tell javascript which template this is + $filterprops['TEMPLATEID'] = $tempindex; + + $jsmodule = array( + 'name' => 'filter_generico', + 'fullpath' => '/filter/generico/module.js', + 'requires' => array('json') + ); + + //AMD or not, and then load our js for this template on the page + if ($require_amd) { + + $generator = new \filter_generico\template_script_generator($tempindex); + $template_amd_script = $generator->get_template_script(); + + //props can't be passed at much length , Moodle complains about too many + //so we do this ... lets hope it don't break things + $jsonstring = json_encode($filterprops); + $props_html = \html_writer::tag('input', '', + array('id' => 'filter_generico_amdopts_' . $filterprops['AUTOID'], 'type' => 'hidden', 'value' => $jsonstring)); + $genericotemplate = $props_html . $genericotemplate; + + //load define for this template. Later it will be called from loadgenerico + $PAGE->requires->js_amd_inline($template_amd_script); + //for AMD generico script + $PAGE->requires->js_call_amd('filter_generico/generico_amd', 'loadgenerico', + array(array('AUTOID' => $filterprops['AUTOID']))); + + } else { + + //require any scripts from the template $url = '/filter/generico/genericojs.php'; $params = array( - 't' => $tempindex, - 'rev' => $revision + 't' => $tempindex, + 'rev' => $revision ); $moodle_url = new moodle_url($url, $params); - $PAGE->requires->js($moodle_url); - - //for no AMD - $PAGE->requires->js_init_call('M.filter_generico.loadgenerico', array($filterprops),false,$jsmodule); - } - - //finally return our template text - return $genericotemplate; + $PAGE->requires->js($moodle_url); + + //for no AMD + $PAGE->requires->js_init_call('M.filter_generico.loadgenerico', array($filterprops), false, $jsmodule); + } + + //finally return our template text + return $genericotemplate; } diff --git a/genericocss.php b/genericocss.php index c467b66..20bebf9 100644 --- a/genericocss.php +++ b/genericocss.php @@ -24,15 +24,15 @@ */ //define('AJAX_SCRIPT', true); -require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); -require_once(dirname(__FILE__).'/lib.php'); +require_once(dirname(dirname(dirname(__FILE__))) . '/config.php'); +require_once(dirname(__FILE__) . '/lib.php'); -$tindex = required_param('t',PARAM_TEXT); +$tindex = required_param('t', PARAM_TEXT); $conf = get_config('filter_generico'); //get presets -$thestyle=$conf->{'templatestyle_' . $tindex}; +$thestyle = $conf->{'templatestyle_' . $tindex}; header('Content-Type: text/css'); echo $thestyle; diff --git a/genericojs.php b/genericojs.php index 6648e5d..adfea85 100644 --- a/genericojs.php +++ b/genericojs.php @@ -24,11 +24,10 @@ */ //define('AJAX_SCRIPT', true); -require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); +require_once(dirname(dirname(dirname(__FILE__))) . '/config.php'); - -$tindex = required_param('t',PARAM_TEXT); +$tindex = required_param('t', PARAM_TEXT); $generator = new \filter_generico\template_script_generator($tindex); $template_script = $generator->get_template_script(); header('Content-Type: application/javascript'); -echo $template_script; \ No newline at end of file +echo $template_script; \ No newline at end of file diff --git a/genericotemplatesadmin.php b/genericotemplatesadmin.php index 4ceb2af..39b2066 100644 --- a/genericotemplatesadmin.php +++ b/genericotemplatesadmin.php @@ -14,30 +14,29 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . - require_once("../../config.php"); -require_once($CFG->libdir.'/adminlib.php'); +require_once($CFG->libdir . '/adminlib.php'); admin_externalpage_setup('genericotemplatesadmin'); //get template to update -$updatetemplate = optional_param('updatetemplate',0,PARAM_INT); - -$updated=0; -$redirecturl = new moodle_url($CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php',array()); -if($updatetemplate==-1) { - $updated= \filter_generico\presets_control::update_all_templates(); - redirect($redirecturl,get_string('templateupdated','filter_generico',$updated)); -}elseif($updatetemplate > 0){ - $updated= \filter_generico\presets_control::update_template($updatetemplate); - redirect($redirecturl,get_string('templateupdated','filter_generico',$updated)); -}else{ +$updatetemplate = optional_param('updatetemplate', 0, PARAM_INT); + +$updated = 0; +$redirecturl = new moodle_url($CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php', array()); +if ($updatetemplate == -1) { + $updated = \filter_generico\presets_control::update_all_templates(); + redirect($redirecturl, get_string('templateupdated', 'filter_generico', $updated)); +} else if ($updatetemplate > 0) { + $updated = \filter_generico\presets_control::update_template($updatetemplate); + redirect($redirecturl, get_string('templateupdated', 'filter_generico', $updated)); +} else { //do nothing we just want to show the table } //if we are exporting html, do that echo $OUTPUT->header(); -echo $OUTPUT->heading(get_string('genericotemplatesadmin','filter_generico'),3); +echo $OUTPUT->heading(get_string('genericotemplatesadmin', 'filter_generico'), 3); echo \filter_generico\templateadmintools::fetch_template_table(); echo $OUTPUT->footer(); diff --git a/lang/en/filter_generico.php b/lang/en/filter_generico.php index fb19e07..3e9800f 100644 --- a/lang/en/filter_generico.php +++ b/lang/en/filter_generico.php @@ -41,13 +41,17 @@ $string['templatename'] = 'Template Name'; $string['templatename_desc'] = 'The name of this template.'; $string['templateinstructions'] = 'Instructions (template {$a})'; -$string['templateinstructions_desc'] = 'Any instructions entered here will be displayed on the Generic atto form for this template is displayed. Keep them short or it will look bad.'; +$string['templateinstructions_desc'] = + 'Any instructions entered here will be displayed on the Generic atto form for this template is displayed. Keep them short or it will look bad.'; $string['templateend'] = 'End tags(template {$a})'; -$string['templateend_desc'] = 'If your template encloses user content, eg an info box, put the closing tags here. The user will enter something like {GENERICO:mytag_end} to close out the filter.'; +$string['templateend_desc'] = + 'If your template encloses user content, eg an info box, put the closing tags here. The user will enter something like {GENERICO:mytag_end} to close out the filter.'; $string['templatescript'] = 'Custom JS (template {$a})'; -$string['templatescript_desc'] = 'If your template needs to run custom javascript, enter that here. It will be run once all the elements have loaded on the page.'; +$string['templatescript_desc'] = + 'If your template needs to run custom javascript, enter that here. It will be run once all the elements have loaded on the page.'; $string['templatedefaults'] = 'variable defaults (template {$a})'; -$string['templatedefaults_desc'] = 'Define the defaults in comma delimited sets of name=value pairs. eg width=800,height=900,feeling=joy'; +$string['templatedefaults_desc'] = + 'Define the defaults in comma delimited sets of name=value pairs. eg width=800,height=900,feeling=joy'; $string['templaterequire_css'] = 'Requires CSS (template {$a})'; $string['templaterequire_js'] = 'Requires JS (template {$a})'; $string['templaterequire_css_desc'] = 'A link(1 only) to an external CSS file that this template requires. optional.'; @@ -58,10 +62,12 @@ $string['templateheadingcss'] = 'CSS/Style Settings.'; $string['templatestyle'] = 'Custom CSS (template {$a})'; -$string['templatestyle_desc'] = 'Enter any custom CSS that your template uses here. Template variables will not work here. Just plain old css.'; +$string['templatestyle_desc'] = + 'Enter any custom CSS that your template uses here. Template variables will not work here. Just plain old css.'; $string['templaterequire_amd'] = 'Load via AMD'; -$string['templaterequire_amd_desc'] = 'AMD is a javascript loading mechanism. If you upload or link to javascript libraries in your template, you might have to uncheck this. It only applies if on Moodle 2.9 or greater'; +$string['templaterequire_amd_desc'] = + 'AMD is a javascript loading mechanism. If you upload or link to javascript libraries in your template, you might have to uncheck this. It only applies if on Moodle 2.9 or greater'; $string['templateupdated'] = '{$a} Poodll Templates Updated.'; $string['updatetoversion'] = 'Update to version: {$a}'; @@ -75,13 +81,15 @@ $string['uploadcss_desc'] = 'You can upload one CSS file which will be loaded for your template. Only one.'; $string['presets'] = 'Autofill template with a Preset'; -$string['presets_desc'] = 'Generico comes with some default presets you can use out of the box, or to help you get started with your own template. Choose one of those here, or just create your own template from scratch. You can export a template as a bundle by clicking on the green box above. You can import a bundle by dragging it onto the green box.'; +$string['presets_desc'] = + 'Generico comes with some default presets you can use out of the box, or to help you get started with your own template. Choose one of those here, or just create your own template from scratch. You can export a template as a bundle by clicking on the green box above. You can import a bundle by dragging it onto the green box.'; $string['dataset'] = 'Dataset'; -$string['dataset_desc'] = 'Generico allows you to pull a dataset from the database for use in your template. This is an advanced feature. Enter the sql portion of a $DB->get_records_sql call here.'; +$string['dataset_desc'] = + 'Generico allows you to pull a dataset from the database for use in your template. This is an advanced feature. Enter the sql portion of a $DB->get_records_sql call here.'; $string['datasetvars'] = 'Dataset Variables'; -$string['datasetvars_desc'] = 'Put a comma separated list of variables that make up the vars for the SQL. You can and probably will want to use variables here.'; - +$string['datasetvars_desc'] = + 'Put a comma separated list of variables that make up the vars for the SQL. You can and probably will want to use variables here.'; $string['bundle'] = 'Bundle'; @@ -90,31 +98,36 @@ $string['templaterequirejsshim'] = ' Require Shim export'; $string['templaterequirejsshim_desc'] = ' Leave blank unless you know what shimming is'; $string['templateversion'] = 'The version of this template {$a}'; -$string['templateversion_desc'] = 'Use semantic versioning e.g 1.0.0. Generico will show an update button when the preset version is greater than the template version.';; -$string['templatealternate'] = 'Alternate content'; -$string['templatealternate_desc'] = 'Content that can be used when the custom and uploaded CSS and javascript content is not available. Currently this is used when the template is processed by a webservice, probably for content on the mobile app'; +$string['templateversion_desc'] = + 'Use semantic versioning e.g 1.0.0. Generico will show an update button when the preset version is greater than the template version.';; +$string['templatealternate'] = 'Alternate content'; +$string['templatealternate_desc'] = + 'Content that can be used when the custom and uploaded CSS and javascript content is not available. Currently this is used when the template is processed by a webservice, probably for content on the mobile app'; $string['templatealternate_end'] = 'Alternate content end (template {$a})'; -$string['templatealternate_end_desc'] = 'Closing alternate content tags for templates that enclose user content with start and end Generico tags'; +$string['templatealternate_end_desc'] = + 'Closing alternate content tags for templates that enclose user content with start and end Generico tags'; //Settings tree headings -$string['templates']='Templates'; -$string['jumpcat_heading']='Generico filter settings'; -$string['jumpcat_explanation']='The full set of Generico filter settings can be found here.'; +$string['templates'] = 'Templates'; +$string['jumpcat_heading'] = 'Generico filter settings'; +$string['jumpcat_explanation'] = 'The full set of Generico filter settings can be found here.'; //cloud poodll settings $string['cpapi_heading'] = 'Cloud Poodll API Settings'; -$string['cpapi_heading_desc'] = "Cloud Poodll allows you to embed recorders direct from cloud.poodll.com in widgets. This is optional and you do not need to fill this in."; +$string['cpapi_heading_desc'] = + "Cloud Poodll allows you to embed recorders direct from cloud.poodll.com in widgets. This is optional and you do not need to fill this in."; $string['cpapiuser'] = 'Cloud Poodll API User'; $string['cpapiuser_details'] = 'This is the same as your username at Poodll.com.'; $string['cpapisecret'] = 'Cloud Poodll API Secret'; -$string['cpapisecret_details'] = "This is a special secret key that can be generated from the API tab in your members area on Poodll.com. "; +$string['cpapisecret_details'] = + "This is a special secret key that can be generated from the API tab in your members area on Poodll.com. "; //CLOUD POODLL API summary display info $string['displaysubs'] = '{$a->subscriptionname} : expires {$a->expiredate}'; $string['noapiuser'] = "No API username entered."; $string['noapisecret'] = "No API secret entered."; $string['credentialsinvalid'] = "The API username and secret entered could not be used to get access. Please check them."; -$string['appauthorised']= "Cloud Poodll is authorised for this site."; -$string['appnotauthorised']= "Cloud Poodll is not authorised for this site."; -$string['refreshtoken']= "Refresh Cloud Poodll license information."; -$string['notokenincache']= "Refresh Cloud Poodll license information to see details."; \ No newline at end of file +$string['appauthorised'] = "Cloud Poodll is authorised for this site."; +$string['appnotauthorised'] = "Cloud Poodll is not authorised for this site."; +$string['refreshtoken'] = "Refresh Cloud Poodll license information."; +$string['notokenincache'] = "Refresh Cloud Poodll license information to see details."; \ No newline at end of file diff --git a/lib.php b/lib.php index eefa961..c3b69ee 100644 --- a/lib.php +++ b/lib.php @@ -23,18 +23,17 @@ defined('MOODLE_INTERNAL') || die; - function filter_generico_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) { - $config = get_config('filter_generico'); - - for($i=1;$i<=$config->templatecount;$i++){ - if($context->contextlevel == CONTEXT_SYSTEM){ - if($filearea === 'uploadjs' . $i || $filearea === 'uploadcss' . $i ) { - return \filter_generico\generico_utils::setting_file_serve($filearea,$args,$forcedownload, $options); - } - } - } - send_file_not_found(); + $config = get_config('filter_generico'); + + for ($i = 1; $i <= $config->templatecount; $i++) { + if ($context->contextlevel == CONTEXT_SYSTEM) { + if ($filearea === 'uploadjs' . $i || $filearea === 'uploadcss' . $i) { + return \filter_generico\generico_utils::setting_file_serve($filearea, $args, $forcedownload, $options); + } + } + } + send_file_not_found(); } /** diff --git a/module.js b/module.js index 07067a8..ccfca6d 100644 --- a/module.js +++ b/module.js @@ -9,62 +9,62 @@ M.filter_generico = { - allopts: {}, - - extscripts: {}, - - csslinks: Array(), - - gyui: null, - - injectcss: function(csslink){ - var link = document.createElement("link"); - link.href = csslink; - if(csslink.toLowerCase().lastIndexOf('.html')==csslink.length-5){ - link.rel = 'import'; - }else{ - link.type = "text/css"; - link.rel = "stylesheet"; - } - document.getElementsByTagName("head")[0].appendChild(link); - }, - - // Replace poodll_flowplayer divs with flowplayers - loadgenerico: function(Y,opts) { - //stash our Y and opts for later use - this.gyui = Y; - //console.log(opts); - //load our css in head if required - //only do it once per extension though - if(opts['CSSLINK']){ - if (this.csslinks.indexOf(opts['CSSLINK'])<0){ - this.csslinks.push(opts['CSSLINK']); - this.injectcss(opts['CSSLINK']); - } - } - //load our css in head if required - //only do it once per extension though - if(opts['CSSUPLOAD']){ - if (this.csslinks.indexOf(opts['CSSUPLOAD'])<0){ - this.csslinks.push(opts['CSSUPLOAD']); - this.injectcss(opts['CSSUPLOAD']); - } - } - - //load our css in head if required - //only do it once per extension though - if(opts['CSSCUSTOM']){ - if (this.csslinks.indexOf(opts['CSSCUSTOM'])<0){ - this.csslinks.push(opts['CSSCUSTOM']); - this.injectcss(opts['CSSCUSTOM']); - } - } - - if(typeof filter_generico_extfunctions != 'undefined'){ - if(typeof filter_generico_extfunctions[opts['TEMPLATEID']] == 'function'){ - filter_generico_extfunctions[opts['TEMPLATEID']](opts); - } - } - - }//end of function + allopts: {}, + + extscripts: {}, + + csslinks: Array(), + + gyui: null, + + injectcss: function (csslink) { + var link = document.createElement("link"); + link.href = csslink; + if (csslink.toLowerCase().lastIndexOf('.html') == csslink.length - 5) { + link.rel = 'import'; + } else { + link.type = "text/css"; + link.rel = "stylesheet"; + } + document.getElementsByTagName("head")[0].appendChild(link); + }, + + // Replace poodll_flowplayer divs with flowplayers + loadgenerico: function (Y, opts) { + //stash our Y and opts for later use + this.gyui = Y; + //console.log(opts); + //load our css in head if required + //only do it once per extension though + if (opts['CSSLINK']) { + if (this.csslinks.indexOf(opts['CSSLINK']) < 0) { + this.csslinks.push(opts['CSSLINK']); + this.injectcss(opts['CSSLINK']); + } + } + //load our css in head if required + //only do it once per extension though + if (opts['CSSUPLOAD']) { + if (this.csslinks.indexOf(opts['CSSUPLOAD']) < 0) { + this.csslinks.push(opts['CSSUPLOAD']); + this.injectcss(opts['CSSUPLOAD']); + } + } + + //load our css in head if required + //only do it once per extension though + if (opts['CSSCUSTOM']) { + if (this.csslinks.indexOf(opts['CSSCUSTOM']) < 0) { + this.csslinks.push(opts['CSSCUSTOM']); + this.injectcss(opts['CSSCUSTOM']); + } + } + + if (typeof filter_generico_extfunctions != 'undefined') { + if (typeof filter_generico_extfunctions[opts['TEMPLATEID']] == 'function') { + filter_generico_extfunctions[opts['TEMPLATEID']](opts); + } + } + + }//end of function }//end of class \ No newline at end of file diff --git a/poodllloader.html b/poodllloader.html index 5f9cd33..d89a301 100644 --- a/poodllloader.html +++ b/poodllloader.html @@ -14,20 +14,23 @@ - +
diff --git a/refreshtoken.php b/refreshtoken.php index 8e1c78d..24b9354 100644 --- a/refreshtoken.php +++ b/refreshtoken.php @@ -24,19 +24,18 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - -require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); +require_once(dirname(dirname(dirname(__FILE__))) . '/config.php'); use \filter_generico\constants; require_login(0, false); $systemcontext = context_system::instance(); -if(has_capability('moodle/site:config',$systemcontext)){ - $apiuser = get_config(constants::MOD_FRANKY,'cpapiuser'); - $apisecret=get_config(constants::MOD_FRANKY,'cpapisecret'); - $force=true; - if($apiuser && $apisecret) { +if (has_capability('moodle/site:config', $systemcontext)) { + $apiuser = get_config(constants::MOD_FRANKY, 'cpapiuser'); + $apisecret = get_config(constants::MOD_FRANKY, 'cpapisecret'); + $force = true; + if ($apiuser && $apisecret) { $gu = new \filter_generico\generico_utils(); $gu->fetch_token($apiuser, $apisecret, $force); } diff --git a/settings.php b/settings.php index 735558d..310a0aa 100644 --- a/settings.php +++ b/settings.php @@ -29,56 +29,54 @@ $settings = null; if (is_siteadmin()) { - global $PAGE; + global $PAGE; - - //add folder in property tree for settings pages - $generico_category_name='generico_category'; + //add folder in property tree for settings pages + $generico_category_name = 'generico_category'; $generico_category = new admin_category($generico_category_name, 'Generico'); - $ADMIN->add('filtersettings',$generico_category); - $conf = get_config('filter_generico'); + $ADMIN->add('filtersettings', $generico_category); + $conf = get_config('filter_generico'); + + //add the common settings page + // we changed this to use the default settings id for the top page. This way in the settings link on the manage filters + //page, we will arrive here. Else the link will show there, but it will error out if clicked. + //$settings_page = new admin_settingpage('filter_generico_commonsettingspage' ,get_string('commonpageheading', 'filter_generico')); + $settings_page = new admin_settingpage('filtersettinggenerico', get_string('commonpageheading', 'filter_generico')); - //add the common settings page - // we changed this to use the default settings id for the top page. This way in the settings link on the manage filters - //page, we will arrive here. Else the link will show there, but it will error out if clicked. - //$settings_page = new admin_settingpage('filter_generico_commonsettingspage' ,get_string('commonpageheading', 'filter_generico')); - $settings_page = new admin_settingpage('filtersettinggenerico' ,get_string('commonpageheading', 'filter_generico')); - - $settings_page->add(new admin_setting_configtext('filter_generico/templatecount', - get_string('templatecount', 'filter_generico'), - get_string('templatecount_desc', 'filter_generico'), - \filter_generico\generico_utils::FILTER_GENERICO_TEMPLATE_COUNT, PARAM_INT,20)); + $settings_page->add(new admin_setting_configtext('filter_generico/templatecount', + get_string('templatecount', 'filter_generico'), + get_string('templatecount_desc', 'filter_generico'), + \filter_generico\generico_utils::FILTER_GENERICO_TEMPLATE_COUNT, PARAM_INT, 20)); //cloud poodll credentials - $settings_page->add(new admin_setting_heading('filter_generico_cpapi_settings', get_string('cpapi_heading', 'filter_generico'), get_string('cpapi_heading_desc', 'filter_generico'))); + $settings_page->add(new admin_setting_heading('filter_generico_cpapi_settings', get_string('cpapi_heading', 'filter_generico'), + get_string('cpapi_heading_desc', 'filter_generico'))); $settings_page->add(new admin_setting_configtext('filter_generico/cpapiuser', get_string('cpapiuser', 'filter_generico'), - get_string('cpapiuser_details', 'filter_generico'), '')); + get_string('cpapiuser_details', 'filter_generico'), '')); //we show a summary of the users apps if we can get the info - $apiuser=get_config(constants::MOD_FRANKY,'cpapiuser'); - $apisecret=get_config(constants::MOD_FRANKY,'cpapisecret'); - if($apiuser && $apisecret) { + $apiuser = get_config(constants::MOD_FRANKY, 'cpapiuser'); + $apisecret = get_config(constants::MOD_FRANKY, 'cpapisecret'); + if ($apiuser && $apisecret) { $gu = new \filter_generico\generico_utils(); - $tokeninfo = $gu->fetch_token_for_display($apiuser, $apisecret); - }else{ + $tokeninfo = $gu->fetch_token_for_display($apiuser, $apisecret); + } else { $tokeninfo = get_string('cpapisecret_details', constants::MOD_FRANKY); } $settings_page->add(new admin_setting_configtext('filter_generico/cpapisecret', get_string('cpapisecret', 'filter_generico'), - $tokeninfo, '')); - + $tokeninfo, '')); - - //add page to category - $ADMIN->add($generico_category_name, $settings_page); + //add page to category + $ADMIN->add($generico_category_name, $settings_page); $genericotemplatesadmin_settings = new admin_externalpage('genericotemplatesadmin', get_string('templates', 'filter_generico'), - $CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php' ); + $CFG->wwwroot . '/filter/generico/genericotemplatesadmin.php'); $ADMIN->add($generico_category_name, $genericotemplatesadmin_settings); //Templates - $template_pages = \filter_generico\settingstools::fetch_template_pages($conf); + $template_pages = \filter_generico\settingstools::fetch_template_pages($conf); foreach ($template_pages as $template_page) { $ADMIN->add($generico_category_name, $template_page); } - + } diff --git a/styles.css b/styles.css index 2be8642..d8e824e 100644 --- a/styles.css +++ b/styles.css @@ -1,17 +1,17 @@ .filter_generico_dragdropsquare { - width:130px; - height:25px; + width: 130px; + height: 25px; line-height: 25px; text-align: center; border-radius: 5px; color: #73AD21; border: 1px solid #73AD21; - padding:1px 1px 1px 1px; - background-color:#CBF2DC; - margin-top:5px; - float:right; + padding: 1px 1px 1px 1px; + background-color: #CBF2DC; + margin-top: 5px; + float: right; } div.filter_generico_dragging { - border:2px dashed #0000FF; + border: 2px dashed #0000FF; } \ No newline at end of file diff --git a/version.php b/version.php index cc42884..e033c41 100644 --- a/version.php +++ b/version.php @@ -25,8 +25,8 @@ defined('MOODLE_INTERNAL') || die(); -$plugin->version = 2019061400; // The current plugin version (Date: YYYYMMDDXX) -$plugin->requires = 2011070100; // Requires this Moodle version +$plugin->version = 2019071300; // The current plugin version (Date: YYYYMMDDXX) +$plugin->requires = 2011070100; // Requires this Moodle version $plugin->component = 'filter_generico'; // Full name of the plugin (used for diagnostics) -$plugin->maturity = MATURITY_STABLE; -$plugin->release = 'Version 1.4.09(Build 2019061400)'; +$plugin->maturity = MATURITY_STABLE; +$plugin->release = 'Version 1.4.10(Build 2019071300)';