diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cba214f8..f62779a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,5 +9,5 @@ jobs: # Required if you plan to publish (uncomment the below) # secrets: # moodle_org_token: ${{ secrets.MOODLE_ORG_TOKEN }} - # with: - # Any further options in this section + with: + disable_phpcpd: true diff --git a/amd/src/calendar.js b/amd/src/calendar.js index e07da603..5c0de108 100644 --- a/amd/src/calendar.js +++ b/amd/src/calendar.js @@ -21,7 +21,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notification, Ajax) { +define(['core/str', 'core/notification', 'core/ajax'], function (Str, Notification, Ajax) { /** * Module level variables. @@ -93,7 +93,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Number} month The month to get the number of days for. * @param {Number} year The year to get the number of days for. */ - const daysInMonth = function(month, year) { + const daysInMonth = function (month, year) { return 32 - new Date(year, month, 32).getDate(); }; @@ -102,15 +102,15 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * * @method getHeatColors */ - const getHeatColors = function() { + const getHeatColors = function () { return new Promise((resolve, reject) => { Ajax.call([{ methodname: 'local_assessfreq_get_heat_colors', args: {}, - }], true, false)[0].done(function(response) { + }], true, false)[0].done(function (response) { colorArray = JSON.parse(response); resolve(colorArray); - }).fail(function() { + }).fail(function () { reject(new Error('Failed to get heat colors')); }); }); @@ -121,15 +121,15 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * * @method getProcessEvents */ - const getProcessModules = function() { + const getProcessModules = function () { return new Promise((resolve, reject) => { Ajax.call([{ methodname: 'local_assessfreq_get_process_modules', args: {}, - }], true, false)[0].done(function(response) { + }], true, false)[0].done(function (response) { processModules = JSON.parse(response); resolve(processModules); - }).fail(function() { + }).fail(function () { reject(new Error('Failed to get process events')); }); }); @@ -142,7 +142,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Object} eventArray All the event count for the heatmap. * @param {Object} dateObj Date details. */ - const calcHeatRange = function(eventArray, dateObj) { + const calcHeatRange = function (eventArray, dateObj) { return new Promise((resolve) => { // Resolve early if there are no events. @@ -155,7 +155,6 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio // If scheduled tasks have not run yet we may not have any data. let eventArrayLength = Object.keys(eventArray).length; if ((eventArrayLength > 0) && (eventArray[dateObj.year] !== "undefined")) { - let eventcount = new Array; let year = eventArray[dateObj.year]; @@ -191,7 +190,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Number} eventCount The count to get the heat value. * @return {Number} heat The heat value. */ - const getHeat = function(eventCount) { + const getHeat = function (eventCount) { let scaleMin = 1; if (eventCount == heatRangeMin) { @@ -224,7 +223,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Array} modules Array of the modules to get. * @return {Promise} */ - const getEvents = function({year, metric, modules}) { + const getEvents = function ({year, metric, modules}) { return new Promise((resolve, reject) => { let args = { year: year, @@ -255,7 +254,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Number} month The month to get the number of days for. * @return {Array} monthevents The events for the supplied month. */ - const getMonthEvents = function(year, month) { + const getMonthEvents = function (year, month) { let monthevents; if ((typeof eventArray[year] !== "undefined") && (typeof eventArray[year][month] !== "undefined")) { @@ -273,7 +272,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Number} endMonth The month to generate the tables to. * @return {Promise} */ - const createTables = function({year, startMonth, endMonth}) { + const createTables = function ({year, startMonth, endMonth}) { return new Promise((resolve, reject) => { let calendarContainer = document.createElement('div'); let month = startMonth; @@ -337,7 +336,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Object} dayArray The details of the events for that day/ * @return {String} tipHTML The HTML for the tooltip. */ - const getTooltip = function(dayArray) { + const getTooltip = function (dayArray) { let tipHTML = ''; for (let [key, value] of Object.entries(dayArray)) { @@ -354,7 +353,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Number} year The year to generate calendar for. * @param {Number} month The monthe to generate calendar for. */ - const populateCalendarDays = function(table, year, month) { + const populateCalendarDays = function (table, year, month) { let firstDay = (new Date(year, month)).getDay(); // Get the starting day of the month. let monthEvents = getMonthEvents(year, (month + 1)); // We add one due to month diferences between PHP and JS. let date = 1; // Creating all cells. @@ -368,7 +367,6 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio var cell = document.createElement("td"); var cellText = document.createTextNode(""); cell.dataset.event = 'false'; - } else if (date > daysInMonth(month, year)) { // Break if we have generated all the days for this month. break; } else { @@ -391,7 +389,6 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio cell.dataset.date = year + '-' + (month + 1) + '-' + date; cell.title = getTooltip(monthEvents[date]); cell.style.cursor = "pointer"; - } date++; } @@ -411,7 +408,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Number} startMonth The month to start generation from. * @return {Promise} */ - const populateCalendar = function({calendarContainer, year, startMonth}) { + const populateCalendar = function ({calendarContainer, year, startMonth}) { return new Promise((resolve, reject) => { // Get the table boodies. let tables = calendarContainer.getElementsByTagName("tbody"); @@ -437,7 +434,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * * @method createHeatScale */ - Calendar.createHeatScale = function() { + Calendar.createHeatScale = function () { return new Promise((resolve) => { let table = document.createElement('table'); let tbody = document.createElement('tbody'); @@ -454,7 +451,6 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio trow.appendChild(cell); } - } tbody.appendChild(trow); @@ -477,7 +473,7 @@ define(['core/str', 'core/notification', 'core/ajax'], function(Str, Notificatio * @param {Array} modules The modules to display in the heatamp. * @return {Promise} */ - Calendar.generate = function(year, startMonth, endMonth, metric, modules) { + Calendar.generate = function (year, startMonth, endMonth, metric, modules) { return new Promise((resolve, reject) => { const dateObj = { year : year, diff --git a/amd/src/chart_data.js b/amd/src/chart_data.js index 82180756..c66a818d 100644 --- a/amd/src/chart_data.js +++ b/amd/src/chart_data.js @@ -95,9 +95,9 @@ export const getCardCharts = (quizId, hoursFilter, yearSelect) => { }); } }).fail(() => { - Notification.exception(new Error('Failed to load card.')); - return; - }); + Notification.exception(new Error('Failed to load card.')); + return; + }); }); }; diff --git a/amd/src/chart_output_chartjs.js b/amd/src/chart_output_chartjs.js index 893a6920..4cc3039c 100644 --- a/amd/src/chart_output_chartjs.js +++ b/amd/src/chart_output_chartjs.js @@ -20,7 +20,7 @@ * @copyright 2020 Matt Porritt <mattp@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['core/chart_output_chartjs'], function(Output) { +define(['core/chart_output_chartjs'], function (Output) { /** * Module level variables. @@ -36,7 +36,7 @@ define(['core/chart_output_chartjs'], function(Output) { * @param {module:core/chart_axis} axis The axis. * @return {Object} The axis config. */ - Output.prototype._makeConfig = function() { + Output.prototype._makeConfig = function () { var config = { type: this._getChartType(), data: { @@ -56,11 +56,11 @@ define(['core/chart_output_chartjs'], function(Output) { } // Override legend options with those provided at run time. - if (rtLegendoptions) { + if (rtLegendoptions) { config.options.legend = rtLegendoptions; } - this._chart.getXAxes().forEach(function(axis, i) { + this._chart.getXAxes().forEach(function (axis, i) { var axisLabels = axis.getLabels(); config.options.scales = config.options.scales || {}; @@ -68,14 +68,14 @@ define(['core/chart_output_chartjs'], function(Output) { config.options.scales.xAxes[i] = this._makeAxisConfig(axis, 'x', i); if (axisLabels !== null) { - config.options.scales.xAxes[i].ticks.callback = function(value, index) { + config.options.scales.xAxes[i].ticks.callback = function (value, index) { return axisLabels[index] || ''; }; } config.options.scales.xAxes[i].stacked = this._isStacked(); }.bind(this)); - this._chart.getYAxes().forEach(function(axis, i) { + this._chart.getYAxes().forEach(function (axis, i) { var axisLabels = axis.getLabels(); config.options.scales = config.options.scales || {}; @@ -83,7 +83,7 @@ define(['core/chart_output_chartjs'], function(Output) { config.options.scales.yAxes[i] = this._makeAxisConfig(axis, 'y', i); if (axisLabels !== null) { - config.options.scales.yAxes[i].ticks.callback = function(value) { + config.options.scales.yAxes[i].ticks.callback = function (value) { return axisLabels[parseInt(value, 10)] || ''; }; } @@ -104,7 +104,7 @@ define(['core/chart_output_chartjs'], function(Output) { /** * Get the aspect ratio setting and initialise the chart. */ - ChartOutput.init = function(chartImage, ChartInst, aspect, legend) { + ChartOutput.init = function (chartImage, ChartInst, aspect, legend) { aspectRatio = aspect; rtLegendoptions = legend; new Output(chartImage, ChartInst); diff --git a/amd/src/course_selector.js b/amd/src/course_selector.js index bcc41e89..472cc8e5 100644 --- a/amd/src/course_selector.js +++ b/amd/src/course_selector.js @@ -23,7 +23,7 @@ * @licensehttp://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['core/ajax', 'core/notification'], function(Ajax, Notification) { +define(['core/ajax', 'core/notification'], function (Ajax, Notification) { /** * Module level variables. @@ -38,7 +38,7 @@ define(['core/ajax', 'core/notification'], function(Ajax, Notification) { * @param {Function} callback A callback function receiving an array of results. * @return {Void} */ - CourseSelector.transport = function(selector, query, callback) { + CourseSelector.transport = function (selector, query, callback) { Ajax.call([{ methodname: 'local_assessfreq_get_courses', args: { @@ -59,7 +59,7 @@ define(['core/ajax', 'core/notification'], function(Ajax, Notification) { * @param {Array} results An array or results. * @return {Array} New array of results. */ - CourseSelector.processResults = function(selector, results) { + CourseSelector.processResults = function (selector, results) { let options = []; results.forEach((element) => { options.push({ diff --git a/amd/src/dashboard_assessment.js b/amd/src/dashboard_assessment.js index 36cb4955..6ecaacea 100644 --- a/amd/src/dashboard_assessment.js +++ b/amd/src/dashboard_assessment.js @@ -272,7 +272,7 @@ const moduleListChildrenEvents = (element) => { let module = links[i].dataset.module; if (module.toLowerCase() === 'all') { - links[i].addEventListener('click', function(event){ + links[i].addEventListener('click', function (event) { event.preventDefault(); // Remove active class from all other links. for (var j = 0; j < links.length; j++) { @@ -281,7 +281,7 @@ const moduleListChildrenEvents = (element) => { updateHeatmapDebounce(); // Call function to update heatmap. }); } else if (module.toLowerCase() === 'close') { - links[i].addEventListener('click', function(event){ + links[i].addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); @@ -290,9 +290,8 @@ const moduleListChildrenEvents = (element) => { updateHeatmapDebounce(); // Call function to update heatmap. }); - } else { - links[i].addEventListener('click', function(event){ + links[i].addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); @@ -302,7 +301,6 @@ const moduleListChildrenEvents = (element) => { updateHeatmapDebounce(); }); } - } }; diff --git a/amd/src/dashboard_quiz.js b/amd/src/dashboard_quiz.js index 0334e2d1..6a036bfb 100644 --- a/amd/src/dashboard_quiz.js +++ b/amd/src/dashboard_quiz.js @@ -33,9 +33,8 @@ import * as TableHandler from 'local_assessfreq/table_handler'; import * as UserPreference from 'local_assessfreq/user_preferences'; import * as ZoomModal from 'local_assessfreq/zoom_modal'; -/** - * Module level variables. - */ +// Module level variables. + var selectQuizStr = ''; var contextid; var quizId = 0; diff --git a/amd/src/dayview.js b/amd/src/dayview.js index 5abf45c5..4e3bdb08 100644 --- a/amd/src/dayview.js +++ b/amd/src/dayview.js @@ -21,187 +21,189 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['core/str', 'core/notification', 'core/modal_factory', 'local_assessfreq/modal_large', 'core/templates', 'core/ajax'], -function(Str, Notification, ModalFactory, ModalLarge, Templates, Ajax) { - - /** - * Module level variables. - */ - var Dayview = {}; - var modalObj; - const spinner = '<p class="text-center">' - + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' - + '</p>'; - - const stringArr = [ - {key: 'sun', component: 'calendar'}, - {key: 'mon', component: 'calendar'}, - {key: 'tue', component: 'calendar'}, - {key: 'wed', component: 'calendar'}, - {key: 'thu', component: 'calendar'}, - {key: 'fri', component: 'calendar'}, - {key: 'sat', component: 'calendar'}, - {key: 'jan', component: 'local_assessfreq'}, - {key: 'feb', component: 'local_assessfreq'}, - {key: 'mar', component: 'local_assessfreq'}, - {key: 'apr', component: 'local_assessfreq'}, - {key: 'may', component: 'local_assessfreq'}, - {key: 'jun', component: 'local_assessfreq'}, - {key: 'jul', component: 'local_assessfreq'}, - {key: 'aug', component: 'local_assessfreq'}, - {key: 'sep', component: 'local_assessfreq'}, - {key: 'oct', component: 'local_assessfreq'}, - {key: 'nov', component: 'local_assessfreq'}, - {key: 'dec', component: 'local_assessfreq'}, - ]; - var stringResult; - var systemTimezone = 'Australia/Melbourne'; - var dayViewTitle = ''; - - const getUserDate = function (timestamp, format) { - return new Promise((resolve) => { - const systemTimezoneTime = new Date(timestamp * 1000).toLocaleString('en-US', {timeZone: systemTimezone}); - let date = new Date(systemTimezoneTime); - const year = date.getFullYear(); - const month = stringResult[(7 + date.getMonth())]; - const day = date.getDate(); - const hours = date.getHours(); - const minutes = '0' + date.getMinutes(); - - const strftimetime = hours + ':' + minutes.substr(-2); // Will display time in 10:30 format. - const strftimedatetime = day + ' ' + month + ' ' + year + ', ' + strftimetime; - - if (format === 'strftimetime') { - resolve(strftimetime); - } else { - resolve(strftimedatetime); - } +define( + ['core/str', 'core/notification', 'core/modal_factory', 'local_assessfreq/modal_large', 'core/templates', 'core/ajax'], + function (Str, Notification, ModalFactory, ModalLarge, Templates, Ajax) { + + /** + * Module level variables. + */ + var Dayview = {}; + var modalObj; + const spinner = '<p class="text-center">' + + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' + + '</p>'; + + const stringArr = [ + {key: 'sun', component: 'calendar'}, + {key: 'mon', component: 'calendar'}, + {key: 'tue', component: 'calendar'}, + {key: 'wed', component: 'calendar'}, + {key: 'thu', component: 'calendar'}, + {key: 'fri', component: 'calendar'}, + {key: 'sat', component: 'calendar'}, + {key: 'jan', component: 'local_assessfreq'}, + {key: 'feb', component: 'local_assessfreq'}, + {key: 'mar', component: 'local_assessfreq'}, + {key: 'apr', component: 'local_assessfreq'}, + {key: 'may', component: 'local_assessfreq'}, + {key: 'jun', component: 'local_assessfreq'}, + {key: 'jul', component: 'local_assessfreq'}, + {key: 'aug', component: 'local_assessfreq'}, + {key: 'sep', component: 'local_assessfreq'}, + {key: 'oct', component: 'local_assessfreq'}, + {key: 'nov', component: 'local_assessfreq'}, + {key: 'dec', component: 'local_assessfreq'}, + ]; + var stringResult; + var systemTimezone = 'Australia/Melbourne'; + var dayViewTitle = ''; + + const getUserDate = function (timestamp, format) { + return new Promise((resolve) => { + const systemTimezoneTime = new Date(timestamp * 1000).toLocaleString('en-US', {timeZone: systemTimezone}); + let date = new Date(systemTimezoneTime); + const year = date.getFullYear(); + const month = stringResult[(7 + date.getMonth())]; + const day = date.getDate(); + const hours = date.getHours(); + const minutes = '0' + date.getMinutes(); + + const strftimetime = hours + ':' + minutes.substr(-2); // Will display time in 10:30 format. + const strftimedatetime = day + ' ' + month + ' ' + year + ', ' + strftimetime; + + if (format === 'strftimetime') { + resolve(strftimetime); + } else { + resolve(strftimedatetime); + } - }); - }; - - const formatData = async function(response) { - let responseArr = JSON.parse(response); - - // We are displaying the event as a bar whose width represents the start and end time of the event. - // We need to scale the width of the bar to match the width of the container. Therefore 100% width of the container - // equals 24 hours (one day). - // There are 1440 mins per day. 1440 mins equals 100%, therefore 1 min = (100/1440)%. 5/72 == 100/1440. - let scaler = 5 / 72; - - for (let i = 0; i < responseArr.length; i++) { - const year = responseArr[i].endyear; - const month = (responseArr[i].endmonth) - 1; // Minus 1 for difference between months in PHP and JS. - const day = responseArr[i].endday; - const dayStart = (new Date(year, month, day).getTime()) / 1000; - const timeStart = new Date(responseArr[i].timestart * 1000).toLocaleString('en-US', {timeZone: systemTimezone}); - const timeStartTimestamp = (new Date(timeStart).getTime()) / 1000; - const timeEnd = new Date(responseArr[i].timeend * 1000).toLocaleString('en-US', {timeZone: systemTimezone}); - const timeEndTimestamp = (new Date(timeEnd).getTime()) / 1000; - let secondsSinceDayStart = timeStartTimestamp - dayStart; - let leftMargin = 0; - let width = 0; - - if (secondsSinceDayStart <= 0) { - secondsSinceDayStart = 0; - width = ((timeEndTimestamp - dayStart) / 60) * scaler; - responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimedatetime'); - } else { - leftMargin = (secondsSinceDayStart / 60) * scaler; - width = ((timeEndTimestamp - timeStartTimestamp) / 60) * scaler; - responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimetime'); - } + }); + }; - if (leftMargin + width > 100) { - width = 100 - leftMargin; + const formatData = async function (response) { + let responseArr = JSON.parse(response); + + // We are displaying the event as a bar whose width represents the start and end time of the event. + // We need to scale the width of the bar to match the width of the container. Therefore 100% width of the container + // equals 24 hours (one day). + // There are 1440 mins per day. 1440 mins equals 100%, therefore 1 min = (100/1440)%. 5/72 == 100/1440. + let scaler = 5 / 72; + + for (let i = 0; i < responseArr.length; i++) { + const year = responseArr[i].endyear; + const month = (responseArr[i].endmonth) - 1; // Minus 1 for difference between months in PHP and JS. + const day = responseArr[i].endday; + const dayStart = (new Date(year, month, day).getTime()) / 1000; + const timeStart = new Date(responseArr[i].timestart * 1000).toLocaleString('en-US', {timeZone: systemTimezone}); + const timeStartTimestamp = (new Date(timeStart).getTime()) / 1000; + const timeEnd = new Date(responseArr[i].timeend * 1000).toLocaleString('en-US', {timeZone: systemTimezone}); + const timeEndTimestamp = (new Date(timeEnd).getTime()) / 1000; + let secondsSinceDayStart = timeStartTimestamp - dayStart; + let leftMargin = 0; + let width = 0; + + if (secondsSinceDayStart <= 0) { + secondsSinceDayStart = 0; + width = ((timeEndTimestamp - dayStart) / 60) * scaler; + responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimedatetime'); + } else { + leftMargin = (secondsSinceDayStart / 60) * scaler; + width = ((timeEndTimestamp - timeStartTimestamp) / 60) * scaler; + responseArr[i].start = await getUserDate(responseArr[i].timestart, 'strftimetime'); + } + + if (leftMargin + width > 100) { + width = 100 - leftMargin; + } + + responseArr[i].leftmargin = leftMargin; + responseArr[i].width = width; + responseArr[i].end = await getUserDate(responseArr[i].timeend, 'strftimetime'); } - responseArr[i].leftmargin = leftMargin; - responseArr[i].width = width; - responseArr[i].end = await getUserDate(responseArr[i].timeend, 'strftimetime'); - } - - return new Promise((resolve) => { - resolve(responseArr); - }); - }; - - /** - * Initialise the base modal to be used. - * - */ - Dayview.display = function(date) { - modalObj.setBody(spinner); - modalObj.show(); - let args = { - date: date, - modules: ['all'] + return new Promise((resolve) => { + resolve(responseArr); + }); }; - let jsonArgs = JSON.stringify(args); - Ajax.call([{ - methodname: 'local_assessfreq_get_day_events', - args: {jsondata: jsonArgs}, - }])[0] - .then(formatData) - .then((responseArr) => { - - let context = {rows: responseArr}; - const year = responseArr[0].endyear; - const day = responseArr[0].endday; - const month = stringResult[(6 + parseInt(responseArr[0].endmonth))]; - const dayDate = day + ' ' + month + ' ' + year; - - modalObj.setTitle(dayViewTitle + ' ' + dayDate); - modalObj.setBody(Templates.render('local_assessfreq/dayview', context)); - - }).fail(() => { - Notification.exception(new Error('Failed to load day view')); - }); - }; - - /** - * Initialise the base modal to be used. - * - * @param {integer} context The current context id. - */ - Dayview.init = function() { - // Load the strings we'll need later. - Str.get_strings(stringArr).catch(() => { // Get required strings. - Notification.exception(new Error('Failed to load strings')); - return; - }).then(stringReturn => { // Save string to global to be used later. - stringResult = stringReturn; - }); - - // Get the system timzone. - Ajax.call([{ - methodname: 'local_assessfreq_get_system_timezone', - args: {}, - }], true, false)[0].then((response) => { - systemTimezone = response; - return; - }).fail(() => { - Notification.exception(new Error('Failed to get system timezone')); - }); - - Str.get_string('schedule', 'local_assessfreq').then((title) => { - dayViewTitle = title; - - // Create the Modal. - ModalFactory.create({ - type: ModalLarge.TYPE, - title: title, - body: spinner - }) - .done((modal) => { - modalObj = modal; + /** + * Initialise the base modal to be used. + * + */ + Dayview.display = function (date) { + modalObj.setBody(spinner); + modalObj.show(); + let args = { + date: date, + modules: ['all'] + }; + let jsonArgs = JSON.stringify(args); + Ajax.call([{ + methodname: 'local_assessfreq_get_day_events', + args: {jsondata: jsonArgs}, + }])[0] + .then(formatData) + .then((responseArr) => { + + let context = {rows: responseArr}; + const year = responseArr[0].endyear; + const day = responseArr[0].endday; + const month = stringResult[(6 + parseInt(responseArr[0].endmonth))]; + const dayDate = day + ' ' + month + ' ' + year; + + modalObj.setTitle(dayViewTitle + ' ' + dayDate); + modalObj.setBody(Templates.render('local_assessfreq/dayview', context)); + + }).fail(() => { + Notification.exception(new Error('Failed to load day view')); }); - }).catch(() => { - Notification.exception(new Error('Failed to load string: loading')); - }); + }; - }; + /** + * Initialise the base modal to be used. + * + * @param {integer} context The current context id. + */ + Dayview.init = function () { + // Load the strings we'll need later. + Str.get_strings(stringArr).catch(() => { // Get required strings. + Notification.exception(new Error('Failed to load strings')); + return; + }).then(stringReturn => { // Save string to global to be used later. + stringResult = stringReturn; + }); + + // Get the system timzone. + Ajax.call([{ + methodname: 'local_assessfreq_get_system_timezone', + args: {}, + }], true, false)[0].then((response) => { + systemTimezone = response; + return; + }).fail(() => { + Notification.exception(new Error('Failed to get system timezone')); + }); + + Str.get_string('schedule', 'local_assessfreq').then((title) => { + dayViewTitle = title; + + // Create the Modal. + ModalFactory.create({ + type: ModalLarge.TYPE, + title: title, + body: spinner + }) + .done((modal) => { + modalObj = modal; + + }); + }).catch(() => { + Notification.exception(new Error('Failed to load string: loading')); + }); + + }; - return Dayview; -}); + return Dayview; + } +); diff --git a/amd/src/form_modal.js b/amd/src/form_modal.js index c3b7b58b..23117f27 100644 --- a/amd/src/form_modal.js +++ b/amd/src/form_modal.js @@ -21,223 +21,221 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax'], -function(Str, ModalFactory, Fragment, Ajax) { - - /** - * Module level variables. - */ - var FormModal = {}; - var contextid; - var modalObj; - var resetOptions = []; - var callback; - - const spinner = '<p class="text-center">' - + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' - + '</p>'; - - const observerConfig = { attributes: true, childList: false, subtree: true }; - - const ObserverCallback = function(mutationsList) { - for (let i = 0; i < mutationsList.length; i++) { - let element = mutationsList[i].target; - if(element.tagName.toLowerCase() === 'span' && element.classList.contains('badge')) { - element.addEventListener('click', updateModalBody); - document.getElementById('id_courses').dataset.course = element.dataset.value; - - document.getElementById('id_quiz').value = -1; - Ajax.call([{ - methodname: 'local_assessfreq_get_quizzes', - args: { - query: mutationsList[i].target.dataset.value - }, - }])[0].done((response) => { - let quizArray = JSON.parse(response); - let selectElement = document.getElementById('id_quiz'); - let selectElementLength = selectElement.options.length; - if (document.getElementById('noquizwarning') !== null) { - document.getElementById('noquizwarning').remove(); - } - // Clear exisitng options. - for (let j = selectElementLength - 1; j >= 0; j--) { - selectElement.options[j] = null; - } - - if (quizArray.length > 0) { - - // Add new options. - for (let k = 0; k < quizArray.length; k++) { - let opt = quizArray[k]; - let el = document.createElement('option'); - el.textContent = opt.name; - el.value = opt.id; - selectElement.appendChild(el); - } - selectElement.removeAttribute('disabled'); +define( + ['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax'], + function (Str, ModalFactory, Fragment, Ajax) { + + /** + * Module level variables. + */ + var FormModal = {}; + var contextid; + var modalObj; + var resetOptions = []; + var callback; + + const spinner = '<p class="text-center">' + + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' + + '</p>'; + + const observerConfig = { attributes: true, childList: false, subtree: true }; + + const ObserverCallback = function (mutationsList) { + for (let i = 0; i < mutationsList.length; i++) { + let element = mutationsList[i].target; + if (element.tagName.toLowerCase() === 'span' && element.classList.contains('badge')) { + element.addEventListener('click', updateModalBody); + document.getElementById('id_courses').dataset.course = element.dataset.value; + + document.getElementById('id_quiz').value = -1; + Ajax.call([{ + methodname: 'local_assessfreq_get_quizzes', + args: { + query: mutationsList[i].target.dataset.value + }, + }])[0].done((response) => { + let quizArray = JSON.parse(response); + let selectElement = document.getElementById('id_quiz'); + let selectElementLength = selectElement.options.length; if (document.getElementById('noquizwarning') !== null) { document.getElementById('noquizwarning').remove(); } - } else { - resetOptions.forEach((option) => { - selectElement.appendChild(option); - }); - document.getElementById('id_quiz').value = 0; - selectElement.disabled = true; - } + // Clear exisitng options. + for (let j = selectElementLength - 1; j >= 0; j--) { + selectElement.options[j] = null; + } - }).fail(() => { - Notification.exception(new Error('Failed to get quizzes')); - }); + if (quizArray.length > 0) { + // Add new options. + for (let k = 0; k < quizArray.length; k++) { + let opt = quizArray[k]; + let el = document.createElement('option'); + el.textContent = opt.name; + el.value = opt.id; + selectElement.appendChild(el); + } + selectElement.removeAttribute('disabled'); + if (document.getElementById('noquizwarning') !== null) { + document.getElementById('noquizwarning').remove(); + } + } else { + resetOptions.forEach((option) => { + selectElement.appendChild(option); + }); + document.getElementById('id_quiz').value = 0; + selectElement.disabled = true; + } - break; + }).fail(() => { + Notification.exception(new Error('Failed to get quizzes')); + }); + + break; + } } + }; - } - }; - - const observer = new MutationObserver(ObserverCallback); - - /** - * Create the modal window. - * - * @private - */ - const createModal = function() { - Str.get_string('loading', 'local_assessfreq').then((title) => { - // Create the Modal. - ModalFactory.create({ - type: ModalFactory.types.DEFAULT, - title: title, - body: spinner, - large: true - }) - .done((modal) => { - modalObj = modal; - - // Explicitly handle form click events. - modalObj.getRoot().on('click', '#id_submitbutton', processModalForm); - modalObj.getRoot().on('click', '#id_cancel', (e) => { - e.preventDefault(); - modalObj.setBody(spinner); - modalObj.hide(); + const observer = new MutationObserver(ObserverCallback); + + /** + * Create the modal window. + * + * @private + */ + const createModal = function () { + Str.get_string('loading', 'local_assessfreq').then((title) => { + // Create the Modal. + ModalFactory.create({ + type: ModalFactory.types.DEFAULT, + title: title, + body: spinner, + large: true + }) + .done((modal) => { + modalObj = modal; + + // Explicitly handle form click events. + modalObj.getRoot().on('click', '#id_submitbutton', processModalForm); + modalObj.getRoot().on('click', '#id_cancel', (e) => { + e.preventDefault(); + modalObj.setBody(spinner); + modalObj.hide(); + }); }); - }); - return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: loading')); - }); - }; - - const getOptionPlaceholders = function() { - return new Promise((resolve, reject) => { - const stringArr = [ - {key: 'selectcourse', component: 'local_assessfreq'}, - {key: 'loadingquiz', component: 'local_assessfreq'}, - ]; - - Str.get_strings(stringArr).catch(() => { // Get required strings. - reject(new Error('Failed to load strings')); return; - }).then(stringReturn => { // Save string to global to be used later. - for (let i = 0; i < stringReturn.length; i++) { - let el = document.createElement('option'); - el.textContent = stringReturn[i]; - el.value = 0 - i; - resetOptions.push(el); - } - resolve(); + }).catch(() => { + Notification.exception(new Error('Failed to load string: loading')); }); - }); - }; - - /** - * Updates the body of the modal window. - * - * @param {Object} formdata - * @private - */ - const updateModalBody = function(formdata) { - if (typeof formdata === "undefined") { - formdata = {}; - } - - let params = { - 'jsonformdata': JSON.stringify(formdata) }; - getOptionPlaceholders() - .then(() => { - Str.get_string('searchquiz', 'local_assessfreq').then((title) => { - modalObj.setTitle(title); - modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_base_form', contextid, params)); - let modalContainer = document.querySelectorAll('[data-region*="modal-container"]')[0]; - observer.observe(modalContainer, observerConfig); + const getOptionPlaceholders = function () { + return new Promise((resolve, reject) => { + const stringArr = [ + {key: 'selectcourse', component: 'local_assessfreq'}, + {key: 'loadingquiz', component: 'local_assessfreq'}, + ]; - return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: searchquiz')); + Str.get_strings(stringArr).catch(() => { // Get required strings. + reject(new Error('Failed to load strings')); + return; + }).then(stringReturn => { // Save string to global to be used later. + for (let i = 0; i < stringReturn.length; i++) { + let el = document.createElement('option'); + el.textContent = stringReturn[i]; + el.value = 0 - i; + resetOptions.push(el); + } + resolve(); + }); }); - }); - }; - - /** - * Updates Moodle form with selected information. - * - * @param {Object} e - * @private - */ - const processModalForm = function(e) { - e.preventDefault(); // Stop modal from closing. - - let quizElement = document.getElementById('id_quiz'); - let quizId = quizElement.options[quizElement.selectedIndex].value; - let courseId = document.getElementById('id_courses').dataset.course; - - if (courseId === undefined || quizId < 1) { - if (document.getElementById('noquizwarning') === null) { - Str.get_string('noquizselected', 'local_assessfreq').then((warning) => { - let element = document.createElement('div'); - element.innerHTML = warning; - element.id = 'noquizwarning'; - element.classList.add('alert', 'alert-danger'); - modalObj.getBody().prepend(element); + }; + + /** + * Updates the body of the modal window. + * + * @param {Object} formdata + * @private + */ + const updateModalBody = function (formdata) { + if (typeof formdata === "undefined") { + formdata = {}; + } + + let params = { + 'jsonformdata': JSON.stringify(formdata) + }; + + getOptionPlaceholders() + .then(() => { + Str.get_string('searchquiz', 'local_assessfreq').then((title) => { + modalObj.setTitle(title); + modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_base_form', contextid, params)); + let modalContainer = document.querySelectorAll('[data-region*="modal-container"]')[0]; + observer.observe(modalContainer, observerConfig); return; }).catch(() => { Notification.exception(new Error('Failed to load string: searchquiz')); }); + }); + }; + /** + * Updates Moodle form with selected information. + * + * @param {Object} e + * @private + */ + const processModalForm = function (e) { + e.preventDefault(); // Stop modal from closing. + + let quizElement = document.getElementById('id_quiz'); + let quizId = quizElement.options[quizElement.selectedIndex].value; + let courseId = document.getElementById('id_courses').dataset.course; + + if (courseId === undefined || quizId < 1) { + if (document.getElementById('noquizwarning') === null) { + Str.get_string('noquizselected', 'local_assessfreq').then((warning) => { + let element = document.createElement('div'); + element.innerHTML = warning; + element.id = 'noquizwarning'; + element.classList.add('alert', 'alert-danger'); + modalObj.getBody().prepend(element); + + return; + }).catch(() => { + Notification.exception(new Error('Failed to load string: searchquiz')); + }); + } + } else { + modalObj.hide(); // Close modal. + modalObj.setBody(''); // Cleaer form. + observer.disconnect(); // Remove observer. + callback(quizId, courseId); // Trigger dashboard update. } - } else { - modalObj.hide(); // Close modal. - modalObj.setBody(''); // Cleaer form. - observer.disconnect(); // Remove observer. - callback(quizId, courseId); // Trigger dashboard update. - } - - }; - - /** - * Display the Modal form. - */ - const displayModalForm = function() { - updateModalBody(); - modalObj.show(); - }; - - /** - * Initialise method for quiz dashboard rendering. - */ - FormModal.init = function(context, processDashboard) { - contextid = context; - callback = processDashboard; - createModal(); - - let createBroadcastButton = document.getElementById('local-assessfreq-find-quiz'); - createBroadcastButton.addEventListener('click', displayModalForm); - }; - - return FormModal; -}); + }; + + /** + * Display the Modal form. + */ + const displayModalForm = function () { + updateModalBody(); + modalObj.show(); + }; + + /** + * Initialise method for quiz dashboard rendering. + */ + FormModal.init = function (context, processDashboard) { + contextid = context; + callback = processDashboard; + createModal(); + + let createBroadcastButton = document.getElementById('local-assessfreq-find-quiz'); + createBroadcastButton.addEventListener('click', displayModalForm); + }; + + return FormModal; + } +); diff --git a/amd/src/modal_large.js b/amd/src/modal_large.js index 0c279f02..4ba79b6f 100644 --- a/amd/src/modal_large.js +++ b/amd/src/modal_large.js @@ -21,40 +21,42 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['jquery', 'core/notification', 'core/custom_interaction_events', 'core/modal', 'core/modal_registry'], -function($, Notification, CustomEvents, Modal, ModalRegistry) { - - var registered = false; - - /** - * Constructor for the Modal. - * - * @param {object} root The root jQuery element for the modal - */ - var ModalLarge = function(root) { - Modal.call(this, root); - }; - - ModalLarge.TYPE = 'local_assesfreq-large_modal'; - ModalLarge.prototype = Object.create(Modal.prototype); - ModalLarge.prototype.constructor = ModalLarge; - - /** - * Set up all of the event handling for the modal. - * - * @method registerEventListeners - */ - ModalLarge.prototype.registerEventListeners = function() { - // Apply parent event listeners. - Modal.prototype.registerEventListeners.call(this); - }; - - // Automatically register with the modal registry the first time this module is imported so that you can create modals - // of this type using the modal factory. - if (!registered) { - ModalRegistry.register(ModalLarge.TYPE, ModalLarge, 'local_assessfreq/modal_large'); - registered = true; +define( + ['jquery', 'core/notification', 'core/custom_interaction_events', 'core/modal', 'core/modal_registry'], + function ($, Notification, CustomEvents, Modal, ModalRegistry) { + + var registered = false; + + /** + * Constructor for the Modal. + * + * @param {object} root The root jQuery element for the modal + */ + var ModalLarge = function (root) { + Modal.call(this, root); + }; + + ModalLarge.TYPE = 'local_assesfreq-large_modal'; + ModalLarge.prototype = Object.create(Modal.prototype); + ModalLarge.prototype.constructor = ModalLarge; + + /** + * Set up all of the event handling for the modal. + * + * @method registerEventListeners + */ + ModalLarge.prototype.registerEventListeners = function () { + // Apply parent event listeners. + Modal.prototype.registerEventListeners.call(this); + }; + + // Automatically register with the modal registry the first time this module is imported so that you can create modals + // of this type using the modal factory. + if (!registered) { + ModalRegistry.register(ModalLarge.TYPE, ModalLarge, 'local_assessfreq/modal_large'); + registered = true; + } + + return ModalLarge; } - - return ModalLarge; -}); \ No newline at end of file +); diff --git a/amd/src/override_modal.js b/amd/src/override_modal.js index 51a28381..6409e511 100644 --- a/amd/src/override_modal.js +++ b/amd/src/override_modal.js @@ -21,148 +21,150 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['jquery', 'core/str', 'core/modal_factory', 'core/modal_events', 'core/fragment', 'core/ajax'], -function($,Str, ModalFactory, ModalEvents, Fragment, Ajax) { - - /** - * Module level variables. - */ - var OverrideModal = {}; - var contextid; - var modalObj; - var callback; - var quizid; - var userid; - var hoursFilter; - - const spinner = '<p class="text-center">' - + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' - + '</p>'; - - /** - * Create the modal window. - * - * @private - */ - const createModal = function() { - Str.get_string('loading', 'local_assessfreq').then((title) => { - // Create the Modal. - ModalFactory.create({ - type: ModalFactory.types.DEFAULT, - title: title, - body: spinner, - large: true - }) - .done((modal) => { - modalObj = modal; - // Explicitly handle form click events. - modalObj.getRoot().on('click', '#id_submitbutton', processModalForm); - modalObj.getRoot().on('click', '#id_cancel', function(e) { - e.preventDefault(); - modalObj.setBody(spinner); - modalObj.hide(); +define( + ['jquery', 'core/str', 'core/modal_factory', 'core/modal_events', 'core/fragment', 'core/ajax'], + function ($,Str, ModalFactory, ModalEvents, Fragment, Ajax) { + + /** + * Module level variables. + */ + var OverrideModal = {}; + var contextid; + var modalObj; + var callback; + var quizid; + var userid; + var hoursFilter; + + const spinner = '<p class="text-center">' + + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' + + '</p>'; + + /** + * Create the modal window. + * + * @private + */ + const createModal = function () { + Str.get_string('loading', 'local_assessfreq').then((title) => { + // Create the Modal. + ModalFactory.create({ + type: ModalFactory.types.DEFAULT, + title: title, + body: spinner, + large: true + }) + .done((modal) => { + modalObj = modal; + // Explicitly handle form click events. + modalObj.getRoot().on('click', '#id_submitbutton', processModalForm); + modalObj.getRoot().on('click', '#id_cancel', function (e) { + e.preventDefault(); + modalObj.setBody(spinner); + modalObj.hide(); + }); }); + return; + }).catch(() => { + Notification.exception(new Error('Failed to load string: loading')); }); - return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: loading')); - }); - }; - - /** - * Updates the body of the modal window. - * - * @param {Object} formdata - * @private - */ - const updateModalBody = function(quiz, user, formdata) { - if (typeof formdata === "undefined") { - formdata = {}; - } + }; + + /** + * Updates the body of the modal window. + * + * @param {Object} formdata + * @private + */ + const updateModalBody = function (quiz, user, formdata) { + if (typeof formdata === "undefined") { + formdata = {}; + } + + let params = { + 'jsonformdata': JSON.stringify(formdata), + 'quizid': quiz, + 'userid': user + }; - let params = { - 'jsonformdata': JSON.stringify(formdata), - 'quizid': quiz, - 'userid': user + modalObj.setBody(spinner); + Str.get_string('useroverride', 'local_assessfreq').then((title) => { + modalObj.setTitle(title); + modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_override_form', contextid, params)); + return; + }).catch(() => { + Notification.exception(new Error('Failed to load string: useroverride')); + }); }; - modalObj.setBody(spinner); - Str.get_string('useroverride', 'local_assessfreq').then((title) => { - modalObj.setTitle(title); - modalObj.setBody(Fragment.loadFragment('local_assessfreq', 'new_override_form', contextid, params)); - return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: useroverride')); - }); - }; - - /** - * Updates Moodle form with selected information. - * - * @param {Object} e - * @private - */ - function processModalForm(e) { - e.preventDefault(); // Stop modal from closing. - - // Form data. - let overrideform = modalObj.getRoot().find('form').serialize(); - let formjson = JSON.stringify(overrideform); - - // Handle invalid form fields for better UX. - // I hate that I had to use JQuery for this. - var invalid = $.merge( + /** + * Updates Moodle form with selected information. + * + * @param {Object} e + * @private + */ + function processModalForm(e) { + e.preventDefault(); // Stop modal from closing. + + // Form data. + let overrideform = modalObj.getRoot().find('form').serialize(); + let formjson = JSON.stringify(overrideform); + + // Handle invalid form fields for better UX. + // I hate that I had to use JQuery for this. + var invalid = $.merge( modalObj.getRoot().find('[aria-invalid="true"]'), modalObj.getRoot().find('.error') - ); + ); + + if (invalid.length) { + invalid.first().focus(); + return; + } - if (invalid.length) { - invalid.first().focus(); - return; + // Submit form via ajax. + Ajax.call([{ + methodname: 'local_assessfreq_process_override_form', + args: { + 'jsonformdata': formjson, + 'quizid': quizid + }, + }])[0].done(() => { + // For submission succeeded. + modalObj.setBody(spinner); + modalObj.hide(); + if (hoursFilter) { + callback(quizid, hoursFilter); + } else { + callback(quizid); + } + }).fail(() => { + // Form submission failed server side, redisplay with errors. + updateModalBody(quizid, userid, overrideform); + }); } - // Submit form via ajax. - Ajax.call([{ - methodname: 'local_assessfreq_process_override_form', - args: { - 'jsonformdata': formjson, - 'quizid': quizid - }, - }])[0].done(() => { - // For submission succeeded. - modalObj.setBody(spinner); - modalObj.hide(); - if (hoursFilter) { - callback(quizid, hoursFilter); - } else { - callback(quizid); - } - }).fail(() => { - // Form submission failed server side, redisplay with errors. - updateModalBody(quizid, userid, overrideform); - }); - } + /** + * Display the Modal form. + */ + OverrideModal.displayModalForm = function (quiz, user, hours = null) { + quizid = quiz; + userid = user; + hoursFilter = hours; + updateModalBody(quiz, user); + modalObj.show(); + }; + + /** + * Initialise method for quiz dashboard rendering. + */ + OverrideModal.init = function (context, callbackFunction, hours = null) { + contextid = context; + callback = callbackFunction; + hoursFilter = hours; + createModal(); + }; - /** - * Display the Modal form. - */ - OverrideModal.displayModalForm = function(quiz, user, hours = null) { - quizid = quiz; - userid = user; - hoursFilter = hours; - updateModalBody(quiz, user); - modalObj.show(); - }; - - /** - * Initialise method for quiz dashboard rendering. - */ - OverrideModal.init = function(context, callbackFunction, hours = null) { - contextid = context; - callback = callbackFunction; - hoursFilter = hours; - createModal(); - }; - - return OverrideModal; -}); + return OverrideModal; + } +); diff --git a/amd/src/student_search.js b/amd/src/student_search.js index 27480e0a..e0c80aa9 100644 --- a/amd/src/student_search.js +++ b/amd/src/student_search.js @@ -185,7 +185,7 @@ export const init = (context) => { .fail(() => { Notification.exception(new Error('Failed to get use preference: hoursahead')); }) - ).done(function() { + ).done(function () { TableHandler.getTable(0, [hoursAhead, hoursBehind], null); OverrideModal.init(context, TableHandler.getTable, [hoursAhead, hoursBehind]); }); diff --git a/amd/src/summary_participants.js b/amd/src/summary_participants.js index 9e2461e0..3182a805 100644 --- a/amd/src/summary_participants.js +++ b/amd/src/summary_participants.js @@ -21,54 +21,56 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['core/fragment', 'core/templates', 'core/str', 'core/notification'], -function(Fragment, Templates, Str, Notification) { +define( + ['core/fragment', 'core/templates', 'core/str', 'core/notification'], + function (Fragment, Templates, Str, Notification) { - /** - * Module level variables. - */ - var Summary = {}; + /** + * Module level variables. + */ + var Summary = {}; - Summary.chart = function(assessids, contextid) { - assessids.forEach((assessid) => { - let chartElement = document.getElementById(assessid + '-summary-graph'); - let params = {'data': JSON.stringify({'quiz' : assessid, 'call': 'participant_summary'})}; + Summary.chart = function (assessids, contextid) { + assessids.forEach((assessid) => { + let chartElement = document.getElementById(assessid + '-summary-graph'); + let params = {'data': JSON.stringify({'quiz' : assessid, 'call': 'participant_summary'})}; - Fragment.loadFragment('local_assessfreq', 'get_quiz_chart', contextid, params) - .done((response) => { - let resObj = JSON.parse(response); - if (resObj.hasdata == true) { - let legend = {position: 'left'}; - let context = { - 'withtable' : false, - 'chartdata' : JSON.stringify(resObj.chart), - 'aspect' : false, - 'legend' : JSON.stringify(legend) - }; - Templates.render('local_assessfreq/chart', context).done((html, js) => { - // Load card body. - Templates.replaceNodeContents(chartElement, html, js); - }).fail(() => { - Notification.exception(new Error('Failed to load chart template.')); + Fragment.loadFragment('local_assessfreq', 'get_quiz_chart', contextid, params) + .done((response) => { + let resObj = JSON.parse(response); + if (resObj.hasdata == true) { + let legend = {position: 'left'}; + let context = { + 'withtable' : false, + 'chartdata' : JSON.stringify(resObj.chart), + 'aspect' : false, + 'legend' : JSON.stringify(legend) + }; + Templates.render('local_assessfreq/chart', context).done((html, js) => { + // Load card body. + Templates.replaceNodeContents(chartElement, html, js); + }).fail(() => { + Notification.exception(new Error('Failed to load chart template.')); + return; + }); return; - }); + } else { + Str.get_string('nodata', 'local_assessfreq').then((str) => { + const noDatastr = document.createElement('h3'); + noDatastr.innerHTML = str; + chartElement.innerHTML = noDatastr.outerHTML; + return; + }).catch(() => { + Notification.exception(new Error('Failed to load string: nodata')); + }); + } + }).fail(() => { + Notification.exception(new Error('Failed to load card.')); return; - } else { - Str.get_string('nodata', 'local_assessfreq').then((str) => { - const noDatastr = document.createElement('h3'); - noDatastr.innerHTML = str; - chartElement.innerHTML = noDatastr.outerHTML; - return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: nodata')); - }); - } - }).fail(() => { - Notification.exception(new Error('Failed to load card.')); - return; + }); }); - }); - }; + }; - return Summary; -}); \ No newline at end of file + return Summary; + } +); diff --git a/amd/src/table_handler.js b/amd/src/table_handler.js index ed889156..3e713a7f 100644 --- a/amd/src/table_handler.js +++ b/amd/src/table_handler.js @@ -111,8 +111,8 @@ export const getTable = (quiz, hours = null, sortValueTable = null, page) => { tableEventListeners(); // Re-add table event listeners. }).fail(() => { - Notification.exception(new Error('Failed to update table.')); - }); + Notification.exception(new Error('Failed to update table.')); + }); }; /** @@ -196,7 +196,6 @@ const tableHide = (event) => { if (action === 'show') { hideArray[column] = 1; } - } hideArray[targetColumn] = (targetAction === 'hide') ? 1 : 0; // We want to flip the clicked column. @@ -321,7 +320,6 @@ export const tableSortButtonAction = (event) => { UserPreference.setUserPreference('local_assessfreq_quiz_table_inprogress_sort_preference', sortValue); debounceTable(); // Call function to update table. - } }; @@ -346,7 +344,6 @@ const tableEventListeners = () => { } else if (linkUrl.search.indexOf('tsort') !== -1) { links[i].addEventListener('click', tableSort); } - } if (resetLink.length > 0) { @@ -410,13 +407,13 @@ export const init = (quiz, tableSearchElement, tableId = null, tableMethodName = null) => { - quizId = quiz; - contextId = context; - cardElement = tableCardElement; - elementId = tableElementId; - fragmentValue = tableFragmentValue; - rowPreference = tableRowPreference; - searchElement = tableSearchElement; - id = tableId; - methodName = tableMethodName; -}; + quizId = quiz; + contextId = context; + cardElement = tableCardElement; + elementId = tableElementId; + fragmentValue = tableFragmentValue; + rowPreference = tableRowPreference; + searchElement = tableSearchElement; + id = tableId; + methodName = tableMethodName; + }; diff --git a/amd/src/zoom_modal.js b/amd/src/zoom_modal.js index ae7c4321..06bbc1ed 100644 --- a/amd/src/zoom_modal.js +++ b/amd/src/zoom_modal.js @@ -21,85 +21,87 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -define(['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax', 'core/templates', 'local_assessfreq/modal_large', +define( + ['core/str', 'core/modal_factory', 'core/fragment', 'core/ajax', 'core/templates', 'local_assessfreq/modal_large', 'core/notification'], -function(Str, ModalFactory, Fragment, Ajax, Templates, ModalLarge, Notification) { + function (Str, ModalFactory, Fragment, Ajax, Templates, ModalLarge, Notification) { - /** - * Module level variables. - */ - var ZoomModal = {}; - var contextid; - var modalObj; - const spinner = '<p class="text-center">' - + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' - + '</p>'; + /** + * Module level variables. + */ + var ZoomModal = {}; + var contextid; + var modalObj; + const spinner = '<p class="text-center">' + + '<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' + + '</p>'; - /** - * Provides zoom functionality for card graphs. - */ - ZoomModal.zoomGraph = function(event, params, method) { - let title = event.target.parentElement.dataset.title; + /** + * Provides zoom functionality for card graphs. + */ + ZoomModal.zoomGraph = function (event, params, method) { + let title = event.target.parentElement.dataset.title; - Fragment.loadFragment('local_assessfreq', method, contextid, params) - .done((response) => { - let resObj = JSON.parse(response); - if (resObj.hasdata == true) { - var context = { 'withtable' : false, 'chartdata' : JSON.stringify(resObj.chart), aspect: false}; - modalObj.setTitle(title); - modalObj.setBody(Templates.render('local_assessfreq/chart', context)); - modalObj.show(); - return; - } else { - Str.get_string('nodata', 'local_assessfreq').then((str) => { - const noDatastr = document.createElement('h3'); - noDatastr.innerHTML = str; + Fragment.loadFragment('local_assessfreq', method, contextid, params) + .done((response) => { + let resObj = JSON.parse(response); + if (resObj.hasdata == true) { + var context = { 'withtable' : false, 'chartdata' : JSON.stringify(resObj.chart), aspect: false}; modalObj.setTitle(title); - modalObj.setBody(noDatastr.outerHTML); + modalObj.setBody(Templates.render('local_assessfreq/chart', context)); modalObj.show(); return; - }).catch(() => { - Notification.exception(new Error('Failed to load string: nodata')); - }); - } - }).fail(() => { - Notification.exception(new Error('Failed to load zoomed graph')); - return; - }); + } else { + Str.get_string('nodata', 'local_assessfreq').then((str) => { + const noDatastr = document.createElement('h3'); + noDatastr.innerHTML = str; + modalObj.setTitle(title); + modalObj.setBody(noDatastr.outerHTML); + modalObj.show(); + return; + }).catch(() => { + Notification.exception(new Error('Failed to load string: nodata')); + }); + } + }).fail(() => { + Notification.exception(new Error('Failed to load zoomed graph')); + return; + }); - }; + }; - /** - * Create the modal window for graph zooming. - * - * @private - */ - const createModal = function() { - return new Promise((resolve, reject) => { - Str.get_string('loading', 'core').then((title) => { - // Create the Modal. - ModalFactory.create({ - type: ModalLarge.TYPE, - title: title, - body: spinner - }) - .done((modal) => { - modalObj = modal; - resolve(); + /** + * Create the modal window for graph zooming. + * + * @private + */ + const createModal = function () { + return new Promise((resolve, reject) => { + Str.get_string('loading', 'core').then((title) => { + // Create the Modal. + ModalFactory.create({ + type: ModalLarge.TYPE, + title: title, + body: spinner + }) + .done((modal) => { + modalObj = modal; + resolve(); + }); + }).catch(() => { + reject(new Error('Failed to load string: loading')); }); - }).catch(() => { - reject(new Error('Failed to load string: loading')); }); - }); - }; + }; - /** - * Initialise method for quiz dashboard rendering. - */ - ZoomModal.init = function(context) { - contextid = context; - createModal(); - }; + /** + * Initialise method for quiz dashboard rendering. + */ + ZoomModal.init = function (context) { + contextid = context; + createModal(); + }; - return ZoomModal; -}); + return ZoomModal; + } +); diff --git a/classes/event/event_processed.php b/classes/event/event_processed.php index da13bcd0..e42cdeab 100644 --- a/classes/event/event_processed.php +++ b/classes/event/event_processed.php @@ -24,8 +24,6 @@ namespace local_assessfreq\event; -defined('MOODLE_INTERNAL') || die(); - /** * Event class. * @@ -34,7 +32,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class event_processed extends \core\event\base { - /** * Init method. */ diff --git a/classes/external.php b/classes/external.php index 4576a99e..feebbc07 100644 --- a/classes/external.php +++ b/classes/external.php @@ -33,16 +33,15 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class local_assessfreq_external extends external_api { - /** * Returns description of method parameters. * * @return void */ public static function get_frequency_parameters() { - return new external_function_parameters(array( - 'jsondata' => new external_value(PARAM_RAW, 'The data encoded as a json array') - )); + return new external_function_parameters([ + 'jsondata' => new external_value(PARAM_RAW, 'The data encoded as a json array'), + ]); } /** @@ -57,8 +56,8 @@ public static function get_frequency($jsondata) { // Parameter validation. self::validate_parameters( self::get_frequency_parameters(), - array('jsondata' => $jsondata) - ); + ['jsondata' => $jsondata] + ); // Context validation and permission check. $context = context_system::instance(); @@ -87,9 +86,9 @@ public static function get_frequency_returns() { * @return void */ public static function get_heat_colors_parameters() { - return new external_function_parameters(array( + return new external_function_parameters([ // If I had params they'd be here, but I don't, so they're not. - )); + ]); } /** @@ -123,9 +122,9 @@ public static function get_heat_colors_returns() { * @return void */ public static function get_process_modules_parameters() { - return new external_function_parameters(array( + return new external_function_parameters([ // If I had params they'd be here, but I don't, so they're not. - )); + ]); } /** @@ -136,7 +135,7 @@ public static function get_process_modules_parameters() { public static function get_process_modules() { \core\session\manager::write_close(); // Close session early this is a read op. - $modulesandstrings = array('number' => get_string('numberevents', 'local_assessfreq')); + $modulesandstrings = ['number' => get_string('numberevents', 'local_assessfreq')]; // Execute API call. $frequency = new \local_assessfreq\frequency(); @@ -164,9 +163,9 @@ public static function get_process_modules_returns() { * @return void */ public static function get_day_events_parameters() { - return new external_function_parameters(array( - 'jsondata' => new external_value(PARAM_RAW, 'The data encoded as a json array') - )); + return new external_function_parameters([ + 'jsondata' => new external_value(PARAM_RAW, 'The data encoded as a json array'), + ]); } /** @@ -181,8 +180,8 @@ public static function get_day_events($jsondata) { // Parameter validation. self::validate_parameters( self::get_day_events_parameters(), - array('jsondata' => $jsondata) - ); + ['jsondata' => $jsondata] + ); // Context validation and permission check. $context = context_system::instance(); @@ -211,9 +210,9 @@ public static function get_day_events_returns() { * @return void */ public static function get_courses_parameters() { - return new external_function_parameters(array( - 'query' => new external_value(PARAM_TEXT, 'The query to find') - )); + return new external_function_parameters([ + 'query' => new external_value(PARAM_TEXT, 'The query to find'), + ]); } /** @@ -229,8 +228,8 @@ public static function get_courses($query) { // Parameter validation. self::validate_parameters( self::get_courses_parameters(), - array('query' => $query) - ); + ['query' => $query] + ); // Context validation and permission check. $context = context_system::instance(); @@ -239,13 +238,16 @@ public static function get_courses($query) { // Execute API call. $sql = 'SELECT id, fullname FROM {course} WHERE ' . $DB->sql_like('fullname', ':fullname', false) . ' AND id <> 1'; - $params = array('fullname' => '%' . $DB->sql_like_escape($query) . '%'); + $params = ['fullname' => '%' . $DB->sql_like_escape($query) . '%']; $courses = $DB->get_records_sql($sql, $params, 0, 11); $data = []; foreach ($courses as $course) { - $data[$course->id] = ["id" => $course->id, "fullname" => format_string($course->fullname, - true, ["context" => $context, "escape" => false])]; + $data[$course->id] = ["id" => $course->id, "fullname" => format_string( + $course->fullname, + true, + ["context" => $context, "escape" => false] + ), ]; } return json_encode(array_values($data)); @@ -265,9 +267,9 @@ public static function get_courses_returns() { * @return void */ public static function get_quizzes_parameters() { - return new external_function_parameters(array( - 'query' => new external_value(PARAM_INT, 'The query to find') - )); + return new external_function_parameters([ + 'query' => new external_value(PARAM_INT, 'The query to find'), + ]); } /** @@ -283,8 +285,8 @@ public static function get_quizzes($query) { // Parameter validation. self::validate_parameters( self::get_quizzes_parameters(), - array('query' => $query) - ); + ['query' => $query] + ); // Context validation and permission check. $context = context_system::instance(); @@ -292,13 +294,16 @@ public static function get_quizzes($query) { has_capability('moodle/site:config', $context); // Execute API call. - $params = array('course' => $query); + $params = ['course' => $query]; $quizzes = $DB->get_records('quiz', $params, 'name ASC', 'id, name'); $data = []; foreach ($quizzes as $quiz) { - $data[$quiz->id] = ["id" => $quiz->id, "name" => format_string($quiz->name, - true, ["context" => $context, "escape" => false])]; + $data[$quiz->id] = ["id" => $quiz->id, "name" => format_string( + $quiz->name, + true, + ["context" => $context, "escape" => false] + ), ]; } return json_encode(array_values($data)); @@ -318,9 +323,9 @@ public static function get_quizzes_returns() { * @return void */ public static function get_quiz_data_parameters() { - return new external_function_parameters(array( - 'quizid' => new external_value(PARAM_INT, 'The quiz id to get data for') - )); + return new external_function_parameters([ + 'quizid' => new external_value(PARAM_INT, 'The quiz id to get data for'), + ]); } /** @@ -335,8 +340,8 @@ public static function get_quiz_data($quizid) { // Parameter validation. self::validate_parameters( self::get_quiz_data_parameters(), - array('quizid' => $quizid) - ); + ['quizid' => $quizid] + ); // Context validation and permission check. $context = context_system::instance(); @@ -364,11 +369,11 @@ public static function get_quiz_data_returns() { * @return void */ public static function set_table_preference_parameters() { - return new external_function_parameters(array( + return new external_function_parameters([ 'tableid' => new external_value(PARAM_ALPHANUMEXT, 'The table id to set the preference for'), 'preference' => new external_value(PARAM_ALPHAEXT, 'The table preference to set'), 'values' => new external_value(PARAM_RAW, 'The values to set as JSON'), - )); + ]); } /** @@ -385,8 +390,8 @@ public static function set_table_preference($tableid, $preference, $values) { // Parameter validation. self::validate_parameters( self::set_table_preference_parameters(), - array('tableid' => $tableid, 'preference' => $preference, 'values' => $values) - ); + ['tableid' => $tableid, 'preference' => $preference, 'values' => $values] + ); // Context validation and permission check. $context = context_system::instance(); @@ -397,24 +402,24 @@ public static function set_table_preference($tableid, $preference, $values) { if (isset($SESSION->flextable[$tableid])) { $prefs = $SESSION->flextable[$tableid]; } else { - $prefs = array( - 'collapse' => array(), - 'sortby' => array(), + $prefs = [ + 'collapse' => [], + 'sortby' => [], 'i_first' => '', 'i_last' => '', - 'textsort' => array(), - ); + 'textsort' => [], + ]; } // Set or reset the preferences. if ($preference == 'reset') { - $prefs = array( - 'collapse' => array(), - 'sortby' => array(), + $prefs = [ + 'collapse' => [], + 'sortby' => [], 'i_first' => '', 'i_last' => '', - 'textsort' => array(), - ); + 'textsort' => [], + ]; } else { $prefs[$preference] = json_decode($values, true); } @@ -439,11 +444,11 @@ public static function set_table_preference_returns() { */ public static function process_override_form_parameters() { return new external_function_parameters( - array( + [ 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the create copy form, encoded as a json array'), - 'quizid' => new external_value(PARAM_INT, 'The quiz id to processs the override for') - ) - ); + 'quizid' => new external_value(PARAM_INT, 'The quiz id to processs the override for'), + ] + ); } /** @@ -463,12 +468,12 @@ public static function process_override_form($jsonformdata, $quizid) { // We always must pass webservice params through validate_parameters. $params = self::validate_parameters( self::process_override_form_parameters(), - array('jsonformdata' => $jsonformdata, 'quizid' => $quizid) - ); + ['jsonformdata' => $jsonformdata, 'quizid' => $quizid] + ); $formdata = json_decode($params['jsonformdata']); - $submitteddata = array(); + $submitteddata = []; parse_str($formdata, $submitteddata); // Check access. @@ -478,23 +483,23 @@ public static function process_override_form($jsonformdata, $quizid) { has_capability('mod/quiz:manageoverrides', $context); // Check if we have an existing override for this user. - $override = $DB->get_record('quiz_overrides', array('quiz' => $quizid, 'userid' => $submitteddata['userid'])); + $override = $DB->get_record('quiz_overrides', ['quiz' => $quizid, 'userid' => $submitteddata['userid']]); // Submit the form data. - $quiz = $DB->get_record('quiz', array('id' => $quizid), '*', MUST_EXIST); + $quiz = $DB->get_record('quiz', ['id' => $quizid], '*', MUST_EXIST); $cm = get_course_and_cm_from_cmid($context->instanceid, 'quiz')[1]; $mform = new \local_assessfreq\form\quiz_override_form($cm, $quiz, $context, $override, $submitteddata); $mdata = $mform->get_data(); if ($mdata) { - $params = array( + $params = [ 'context' => $context, - 'other' => array( - 'quizid' => $quizid - ), - 'relateduserid' => $mdata->userid - ); + 'other' => [ + 'quizid' => $quizid, + ], + 'relateduserid' => $mdata->userid, + ]; $mdata->quiz = $quizid; if (!empty($override->id)) { @@ -516,12 +521,11 @@ public static function process_override_form($jsonformdata, $quizid) { // Trigger the override created event. $event->trigger(); } - } else { throw new moodle_exception('submitoverridefail', 'local_assessfreq'); } - return json_encode(array('overrideid' => $mdata->id)); + return json_encode(['overrideid' => $mdata->id]); } /** @@ -539,9 +543,9 @@ public static function process_override_form_returns() { * @return void */ public static function get_system_timezone_parameters() { - return new external_function_parameters(array( + return new external_function_parameters([ // If I had params they'd be here, but I don't, so they're not. - )); + ]); } /** @@ -556,7 +560,7 @@ public static function get_system_timezone() { global $DB; // Execute API call. - $timezone = $DB->get_field('config', 'value', array('name' => 'timezone'), MUST_EXIST); + $timezone = $DB->get_field('config', 'value', ['name' => 'timezone'], MUST_EXIST); return $timezone; } @@ -576,9 +580,9 @@ public static function get_system_timezone_returns() { * @return void */ public static function get_inprogress_counts_parameters() { - return new external_function_parameters(array( + return new external_function_parameters([ // If I had params they'd be here, but I don't, so they're not. - )); + ]); } /** diff --git a/classes/form/quiz_override_form.php b/classes/form/quiz_override_form.php index 32ede7ba..d35fd935 100644 --- a/classes/form/quiz_override_form.php +++ b/classes/form/quiz_override_form.php @@ -27,7 +27,7 @@ defined('MOODLE_INTERNAL') || die(); require_once("$CFG->libdir/formslib.php"); -require_once($CFG->dirroot.'/mod/quiz/override_form.php'); +require_once($CFG->dirroot . '/mod/quiz/override_form.php'); /** * Form to add override for quiz. @@ -37,7 +37,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class quiz_override_form extends \quiz_override_form { - /** * Constructor. * @param object $cm course module object. @@ -46,7 +45,7 @@ class quiz_override_form extends \quiz_override_form { * @param object $override the override being edited, if it already exists. * @param null|object $submitteddata The data submitted to the form via ajax. */ - public function __construct($cm, $quiz, $context, $override, $submitteddata=null) { + public function __construct($cm, $quiz, $context, $override, $submitteddata = null) { $this->cm = $cm; $this->quiz = $quiz; @@ -56,7 +55,6 @@ public function __construct($cm, $quiz, $context, $override, $submitteddata=null $this->userid = empty($override->userid) ? 0 : $override->userid; \moodleform::__construct(null, null, 'post', '', ['class' => 'ignoredirty'], true, $submitteddata); - } /** @@ -72,5 +70,4 @@ protected function definition() { $mform->removeElement('buttonbar'); $this->add_action_buttons(); } - } diff --git a/classes/form/quiz_search_form.php b/classes/form/quiz_search_form.php index ca3a348d..385dc744 100644 --- a/classes/form/quiz_search_form.php +++ b/classes/form/quiz_search_form.php @@ -36,7 +36,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class quiz_search_form extends \moodleform { - /** * Build form for the broadcast message. * @@ -48,32 +47,36 @@ public function definition() { $mform->disable_form_change_checker(); // Form heading. - $mform->addElement('html', - \html_writer::div(get_string('searchquizform', 'local_assessfreq'), 'form-description mb-3')); + $mform->addElement( + 'html', + \html_writer::div(get_string('searchquizform', 'local_assessfreq'), 'form-description mb-3') + ); - $courseoptions = array( + $courseoptions = [ 'multiple' => false, 'placeholder' => get_string('entercourse', 'local_assessfreq'), 'noselectionstring' => get_string('nocourse', 'local_assessfreq'), 'ajax' => 'local_assessfreq/course_selector', - 'casesensitive' => false - ); - $mform->addElement('autocomplete', 'courses', get_string('course', 'local_assessfreq'), array(), $courseoptions); + 'casesensitive' => false, + ]; + $mform->addElement('autocomplete', 'courses', get_string('course', 'local_assessfreq'), [], $courseoptions); $mform->addElement('hidden', 'coursechoice', '0'); $mform->setType('coursechoice', PARAM_INT); - $selectoptions = array( + $selectoptions = [ 0 => get_string('selectcourse', 'local_assessfreq'), -1 => get_string('loadingquiz', 'local_assessfreq'), - ); - $mform->addElement('select', 'quiz', + ]; + $mform->addElement( + 'select', + 'quiz', get_string('quiz', 'local_assessfreq'), - $selectoptions); + $selectoptions + ); $mform->disabledIf('quiz', 'coursechoice', 'eq', '0'); $btnstring = get_string('selectquiz', 'local_assessfreq'); $this->add_action_buttons(true, $btnstring); - } } diff --git a/classes/form/scheduler.php b/classes/form/scheduler.php index 2427e163..fa06bbf5 100644 --- a/classes/form/scheduler.php +++ b/classes/form/scheduler.php @@ -39,7 +39,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class scheduler_form_element extends MoodleQuickForm_static implements templatable { - /** * Form element scheduler. * @@ -47,9 +46,9 @@ class scheduler_form_element extends MoodleQuickForm_static implements templatab * @param string $elementlabel (optional) text field label. * @param string $text (optional) Text to put in text field. */ - public function __construct($elementname=null, $elementlabel=null, $text=null) { + public function __construct($elementname = null, $elementlabel = null, $text = null) { global $OUTPUT; - $text = $OUTPUT->render_from_template('local_assessfreq/scheduler_form_element', array('foo' => $text)); + $text = $OUTPUT->render_from_template('local_assessfreq/scheduler_form_element', ['foo' => $text]); parent::__construct($elementname, $elementlabel, $text); } diff --git a/classes/frequency.php b/classes/frequency.php index 4ed8939d..a08b3115 100644 --- a/classes/frequency.php +++ b/classes/frequency.php @@ -41,14 +41,13 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class frequency { - /** * The due date databse field differs between module types. * This map provides the translation. * * @var array $modduefield */ - private $moduleendfield = array ( + private $moduleendfield = [ 'assign' => 'duedate', 'choice' => 'timeclose', 'data' => 'timeavailableto', @@ -57,8 +56,8 @@ class frequency { 'lesson' => 'deadline', 'quiz' => 'timeclose', 'scorm' => 'timeclose', - 'workshop' => 'submissionend' - ); + 'workshop' => 'submissionend', + ]; /** * The start date databse field differs between module types. @@ -66,7 +65,7 @@ class frequency { * * @var array $modduefield */ - private $modulestartfield = array ( + private $modulestartfield = [ 'assign' => 'allowsubmissionsfromdate', 'choice' => 'timeopen', 'data' => 'timeavailablefrom', @@ -75,8 +74,8 @@ class frequency { 'lesson' => 'available', 'quiz' => 'timeopen', 'scorm' => 'timeopen', - 'workshop' => 'submissionstart' - ); + 'workshop' => 'submissionstart', + ]; /** * The time limit databse field differs between module types and only some support it. @@ -84,11 +83,11 @@ class frequency { * * @var array $moduletimelimit */ - private $moduletimelimit = array ( + private $moduletimelimit = [ 'leesson' => 'timelimit', 'quiz' => 'timelimit', - ); + ]; /** @@ -97,18 +96,18 @@ class frequency { * * @var array $capabilitymap */ - private $capabilitymap = array ( - 'assign' => array('mod/assign:submit', 'mod/assign:view'), - 'choice' => array('mod/choice:choose', 'mod/choice:view'), - 'data' => array('mod/data:writeentry', 'mod/data:viewentry', 'mod/data:view'), - 'feedback' => array('mod/feedback:complete', 'mod/feedback:viewanalysepage', 'mod/feedback:view'), - 'forum' => array( - 'mod/forum:startdiscussion', 'mod/forum:createattachment', 'mod/forum:replypost', 'mod/forum:viewdiscussion'), - 'lesson' => array('mod/lesson:view'), - 'quiz' => array('mod/quiz:attempt', 'mod/quiz:view'), - 'scorm' => array('mod/scorm:savetrack', 'mod/scorm:viewscores'), - 'workshop' => array('mod/workshop:submit', 'mod/workshop:view') - ); + private $capabilitymap = [ + 'assign' => ['mod/assign:submit', 'mod/assign:view'], + 'choice' => ['mod/choice:choose', 'mod/choice:view'], + 'data' => ['mod/data:writeentry', 'mod/data:viewentry', 'mod/data:view'], + 'feedback' => ['mod/feedback:complete', 'mod/feedback:viewanalysepage', 'mod/feedback:view'], + 'forum' => [ + 'mod/forum:startdiscussion', 'mod/forum:createattachment', 'mod/forum:replypost', 'mod/forum:viewdiscussion', ], + 'lesson' => ['mod/lesson:view'], + 'quiz' => ['mod/quiz:attempt', 'mod/quiz:view'], + 'scorm' => ['mod/scorm:savetrack', 'mod/scorm:viewscores'], + 'workshop' => ['mod/workshop:submit', 'mod/workshop:view'], + ]; /** * Expiry period for caches. @@ -130,15 +129,15 @@ class frequency { * * @return array $modules The enabled modules. */ - public function get_modules() : array { + public function get_modules(): array { $version = get_config('moodle', 'version'); // Start with a hardcoded list of modules. As there is not a good way to get a list of suppoerted modules. // Different versions of Moodle have different supported modules. This is an anti pattern, but yeah... if ($version < 2019052000) { // Versions less than 3.7 don't support forum due dates. - $availablemodules = array ('assign', 'choice', 'data', 'feedback', 'lesson', 'quiz', 'scorm', 'workshop'); + $availablemodules = ['assign', 'choice', 'data', 'feedback', 'lesson', 'quiz', 'scorm', 'workshop']; } else { - $availablemodules = array ('assign', 'choice', 'data', 'feedback', 'forum', 'lesson', 'quiz', 'scorm', 'workshop'); + $availablemodules = ['assign', 'choice', 'data', 'feedback', 'forum', 'lesson', 'quiz', 'scorm', 'workshop']; } return $availablemodules; @@ -163,7 +162,7 @@ public function get_module_capabilities(string $module): array { public function get_enabled_modules(): array { global $DB; - $modules = $DB->get_records_menu('modules', array(), '', 'name, visible'); + $modules = $DB->get_records_menu('modules', [], '', 'name, visible'); return $modules; } @@ -201,7 +200,7 @@ public function get_process_modules(): array { * @param string $module Activity module to get data for. * @return string $sql The generated SQL. */ - private function get_sql_query(string $module) : string { + private function get_sql_query(string $module): string { $includehiddencourses = get_config('local_assessfreq', 'hiddencourses'); $duedate = $this->moduleendfield[$module]; @@ -242,7 +241,7 @@ private function get_sql_query(string $module) : string { * @param array $params * @return \moodle_recordset */ - private function get_module_events(string $sql, array $params) : \moodle_recordset { + private function get_module_events(string $sql, array $params): \moodle_recordset { global $DB; $recordset = $DB->get_recordset_sql($sql, $params); @@ -257,12 +256,12 @@ private function get_module_events(string $sql, array $params) : \moodle_records * @param int $timestamp The unix timestamp to split. * @return array $timeelements Array of split time. */ - private function format_time(int $timestamp) : array { - $timeelements = array( + private function format_time(int $timestamp): array { + $timeelements = [ 'endyear' => date('Y', $timestamp), 'endmonth' => date('m', $timestamp), 'endday' => date('d', $timestamp), - ); + ]; return $timeelements; } @@ -277,14 +276,13 @@ private function format_time(int $timestamp) : array { private function cleanup_record(\stdClass $record): void { global $DB; - $params = array('module' => $record->module, 'instanceid' => $record->instanceid); + $params = ['module' => $record->module, 'instanceid' => $record->instanceid]; $id = $DB->get_field('local_assessfreq_site', 'id', $params); if ($id) { - $DB->delete_records('local_assessfreq_site', array('id' => $id)); - $DB->delete_records('local_assessfreq_user', array('eventid' => $id)); + $DB->delete_records('local_assessfreq_site', ['id' => $id]); + $DB->delete_records('local_assessfreq_user', ['eventid' => $id]); } - } /** @@ -294,13 +292,12 @@ private function cleanup_record(\stdClass $record): void { * @param \moodle_recordset $recordset * @return array */ - private function process_module_events(\moodle_recordset $recordset) : int { + private function process_module_events(\moodle_recordset $recordset): int { global $DB; $recordsprocessed = 0; - $toinsert = array(); + $toinsert = []; foreach ($recordset as $record) { - if (empty($record->startdate)) { $record->startdate = 0; } @@ -330,7 +327,7 @@ private function process_module_events(\moodle_recordset $recordset) : int { if (count($toinsert) == $this->batchsize) { // Insert in database. $DB->insert_records('local_assessfreq_site', $toinsert); - $toinsert = array(); // Reset array. + $toinsert = []; // Reset array. $recordsprocessed += count($toinsert); } } @@ -353,7 +350,7 @@ private function process_module_events(\moodle_recordset $recordset) : int { * @param int $duedate The timestamp to start processing from. * @return int $recordsprocessed The number of records processed. */ - public function process_site_events(int $duedate) : int { + public function process_site_events(int $duedate): int { $recordsprocessed = 0; $enabledmods = $this->get_process_modules(); $includehiddencourses = get_config('local_assessfreq', 'hiddencourses'); @@ -363,9 +360,9 @@ public function process_site_events(int $duedate) : int { foreach ($enabledmods as $module) { $sql = $this->get_sql_query($module); if ($includehiddencourses) { - $params = array($module, CONTEXT_MODULE, $duedate, 1); + $params = [$module, CONTEXT_MODULE, $duedate, 1]; } else { - $params = array($module, CONTEXT_MODULE, $duedate, 1, 1); + $params = [$module, CONTEXT_MODULE, $duedate, 1, 1]; } $moduleevents = $this->get_module_events($sql, $params); // Get all events for module. @@ -387,8 +384,8 @@ public function process_site_events(int $duedate) : int { */ public function generate_enrolled_wheres_joins_params(\context $context, array $capabilities): array { $uid = 'u.id'; - $joins = array(); - $wheres = array(); + $joins = []; + $wheres = []; $enrolledjoin = get_enrolled_join($context, $uid, true); $joins[] = $enrolledjoin->joins; @@ -404,7 +401,7 @@ public function generate_enrolled_wheres_joins_params(\context $context, array $ $wheres[] = "u.deleted = 0"; $wheres = implode(" AND ", $wheres); - $wherejoin = array($joins, $wheres, $params); + $wherejoin = [$joins, $wheres, $params]; return $wherejoin; } @@ -420,7 +417,7 @@ public function generate_enrolled_wheres_joins_params(\context $context, array $ private function get_enrolled_users(\context $context, array $capabilities): array { global $DB; - list($joins, $wheres, $params) = $this->generate_enrolled_wheres_joins_params($context, $capabilities); + [$joins, $wheres, $params] = $this->generate_enrolled_wheres_joins_params($context, $capabilities); $finaljoin = new \core\dml\sql_join($joins, $wheres, $params); @@ -461,9 +458,9 @@ public function get_event_users_raw(int $contextid, string $module): array { * @param bool $cache If false cache won't be used fresh data will be retrieved from DB. * @return array $users Array of user ids. */ - public function get_event_users(int $contextid, string $module, bool $cache=true): array { + public function get_event_users(int $contextid, string $module, bool $cache = true): array { global $DB; - $users = array(); + $users = []; $cachekey = (string)$contextid . '_' . $module; // Try to get value from cache. @@ -479,7 +476,7 @@ public function get_event_users(int $contextid, string $module, bool $cache=true INNER JOIN {local_assessfreq_site} s ON u.eventid = s.id WHERE s.contextid = ? AND s.module = ?'; - $params = array($contextid, $module); + $params = [$contextid, $module]; $users = $DB->get_records_sql($sql, $params); @@ -502,17 +499,18 @@ public function get_event_users(int $contextid, string $module, bool $cache=true * @param int $duedate The duedate to get events from. * @return \moodle_recordset Recordset of event info. */ - private function get_stored_events(int $duedate) : \moodle_recordset { + private function get_stored_events(int $duedate): \moodle_recordset { global $DB; $select = 'timeend >= ?'; - $params = array($duedate); + $params = [$duedate]; $recordset = $DB->get_recordset_select( 'local_assessfreq_site', $select, $params, 'timeend DESC', - 'id, contextid, module'); + 'id, contextid, module' + ); return $recordset; } @@ -525,8 +523,8 @@ private function get_stored_events(int $duedate) : \moodle_recordset { * @param int $eventid The related event id. * @return array $userrecords Array of objects ready to store in database. */ - private function prepare_user_event_records(array $users, int $eventid) : array { - $userrecords = array(); + private function prepare_user_event_records(array $users, int $eventid): array { + $userrecords = []; foreach ($users as $user) { $record = new \stdClass(); $record->userid = $user->id; @@ -545,7 +543,7 @@ private function prepare_user_event_records(array $users, int $eventid) : array * @param int $duedate The timestamp to start processing from. * @return int $recordsprocessed The number of records processed. */ - public function process_user_events(int $duedate) : int { + public function process_user_events(int $duedate): int { global $DB; $recordsprocessed = 0; @@ -571,30 +569,29 @@ public function process_user_events(int $duedate) : int { * * @param int $duedate The unix timestamp to delete events from. */ - public function delete_events(int $duedate) : void { + public function delete_events(int $duedate): void { global $DB; $select = 'timeend >= ?'; // We do the following in a transaction to maintain data consistency. try { $transaction = $DB->start_delegated_transaction(); - $userevents = $DB->get_fieldset_select('local_assessfreq_site', 'id', $select, array($duedate)); + $userevents = $DB->get_fieldset_select('local_assessfreq_site', 'id', $select, [$duedate]); // Delete site events. - $DB->delete_records_select('local_assessfreq_site', $select, array($duedate)); + $DB->delete_records_select('local_assessfreq_site', $select, [$duedate]); // Delete user events. if (!empty($userevents)) { $chunks = array_chunk($userevents, 30000); foreach ($chunks as $usereventschunk) { - list($insql, $inparams) = $DB->get_in_or_equal($usereventschunk); + [$insql, $inparams] = $DB->get_in_or_equal($usereventschunk); $inselect = "eventid $insql"; $DB->delete_records_select('local_assessfreq_user', $inselect, $inparams); } } $transaction->allow_commit(); - } catch (\Exception $e) { $transaction->rollback($e); } @@ -613,11 +610,10 @@ public function delete_event(\stdClass $event): void { $transaction = $DB->start_delegated_transaction(); // Delete site events. - $DB->delete_records('local_assessfreq_site', array('id' => $event->id)); - $DB->delete_records('local_assessfreq_user', array('eventid' => $event->id)); + $DB->delete_records('local_assessfreq_site', ['id' => $event->id]); + $DB->delete_records('local_assessfreq_user', ['eventid' => $event->id]); $transaction->allow_commit(); - } catch (\Exception $e) { $transaction->rollback($e); } @@ -632,8 +628,8 @@ public function delete_event(\stdClass $event): void { * @param int $to Timestamp to fiter to. * @return array $filteredevents The list of filtered events. */ - private function filter_event_data($events, int $from, int $to=0) : array { - $filteredevents = array(); + private function filter_event_data($events, int $from, int $to = 0): array { + $filteredevents = []; // If an explicit to date was not defined default to a year from now. if ($to == 0) { @@ -642,7 +638,6 @@ private function filter_event_data($events, int $from, int $to=0) : array { // Filter events. foreach ($events as $event) { - if (($event->timeend >= $from) && ($event->timeend < $to)) { $filteredevents[] = $event; } @@ -661,9 +656,9 @@ private function filter_event_data($events, int $from, int $to=0) : array { * @param bool $cache If false cache won't be used fresh data will be retrieved from DB. * @return array $events An array of site events */ - public function get_site_events(string $module='all', int $from=0, int $to=0, bool $cache=true) : array { + public function get_site_events(string $module = 'all', int $from = 0, int $to = 0, bool $cache = true): array { global $DB; - $events = array(); + $events = []; // Try to get value from cache. $sitecache = cache::make('local_assessfreq', 'siteevents'); @@ -673,7 +668,6 @@ public function get_site_events(string $module='all', int $from=0, int $to=0, bo // Only return data for chosen range. $events = $this->filter_event_data($data->events, $from, $to); } else { // Not valid cache data. - $sql = "SELECT s.* FROM {local_assessfreq_site} s LEFT JOIN {course} c ON s.courseid = c.id"; @@ -681,11 +675,10 @@ public function get_site_events(string $module='all', int $from=0, int $to=0, bo // Get data from database. if ($module == 'all') { $modules = $this->get_process_modules(); - list($insql, $params) = $DB->get_in_or_equal($modules); + [$insql, $params] = $DB->get_in_or_equal($modules); $sql .= " WHERE s.module $insql"; - } else { - $params = array($module); + $params = [$module]; $sql .= " WHERE s.module = ?"; } @@ -720,14 +713,14 @@ public function get_site_events(string $module='all', int $from=0, int $to=0, bo * * @return array $events An array of site events */ - public function get_day_ending_events(string $date, string $module='all'): array { + public function get_day_ending_events(string $date, string $module = 'all'): array { global $DB; - $events = array(); + $events = []; // TODO: Think about some caching here. // TODO: Improve unit test coverage for this. - list($year, $month, $day) = explode('-', $date); + [$year, $month, $day] = explode('-', $date); $from = 0; $tostart = mktime(0, 0, 0, $month, $day, $year); $toend = mktime(23, 59, 59, $month, $day, $year); @@ -739,12 +732,12 @@ public function get_day_ending_events(string $date, string $module='all'): array // Get data from database. if ($module == 'all') { $modules = $this->get_process_modules(); - list ($insql, $params) = $DB->get_in_or_equal($modules); + [$insql, $params] = $DB->get_in_or_equal($modules); $sql .= " WHERE s.module $insql"; } else { - $params = array( - $module - ); + $params = [ + $module, + ]; $sql .= " WHERE s.module = ?"; } @@ -777,9 +770,15 @@ public function get_day_ending_events(string $date, string $module='all'): array * @param bool $cache If false cache won't be used fresh data will be retrieved from DB. * @return array $events An array of site events */ - public function get_course_events(int $courseid, string $module='all', int $from=0, int $to=0, bool $cache=true) : array { + public function get_course_events( + int $courseid, + string $module = 'all', + int $from = 0, + int $to = 0, + bool $cache = true + ): array { global $DB; - $events = array(); + $events = []; $cachekey = (string)$courseid . '_' . $module; // Try to get value from cache. @@ -790,12 +789,11 @@ public function get_course_events(int $courseid, string $module='all', int $from // Only return data for chosen range. $events = $this->filter_event_data($data->events, $from, $to); } else { // Not valid cache data. - // Get data from database. if ($module == 'all') { - $rawevents = $DB->get_records('local_assessfreq_site', array('courseid' => $courseid)); + $rawevents = $DB->get_records('local_assessfreq_site', ['courseid' => $courseid]); } else { - $rawevents = $DB->get_records('local_assessfreq_site', array('module' => $module, 'courseid' => $courseid)); + $rawevents = $DB->get_records('local_assessfreq_site', ['module' => $module, 'courseid' => $courseid]); } $events = $this->filter_event_data($rawevents, $from, $to); @@ -823,9 +821,9 @@ public function get_course_events(int $courseid, string $module='all', int $from * @param bool $cache If false cache won't be used fresh data will be retrieved from DB. * @return array $events An array of site events */ - public function get_user_events(int $userid, string $module='all', int $from=0, int $to=0, bool $cache=true) : array { + public function get_user_events(int $userid, string $module = 'all', int $from = 0, int $to = 0, bool $cache = true): array { global $DB; - $events = array(); + $events = []; $cachekey = (string)$userid . '_' . $module; // Try to get value from cache. @@ -843,9 +841,9 @@ public function get_user_events(int $userid, string $module='all', int $from=0, WHERE u.userid = ?'; // Get data from database. if ($module == 'all') { - $params = array($userid); + $params = [$userid]; } else { - $params = array($userid, $module); + $params = [$userid, $module]; $sql .= ' AND s.module = ?'; } @@ -879,7 +877,7 @@ public function get_user_events(int $userid, string $module='all', int $from=0, * @param int $to The timestamp to get events to. * @return array $events An array of site events */ - public function get_user_events_all(string $module='all', int $from=0, int $to=0) : Iterable { + public function get_user_events_all(string $module = 'all', int $from = 0, int $to = 0): iterable { global $DB; $rowkey = $DB->sql_concat('s.id', "'_'", 'u.userid'); @@ -891,11 +889,10 @@ public function get_user_events_all(string $module='all', int $from=0, int $to=0 // Get data from database. if ($module == 'all') { $modules = $this->get_process_modules(); - list($insql, $params) = $DB->get_in_or_equal($modules); + [$insql, $params] = $DB->get_in_or_equal($modules); $sql .= " WHERE s.module $insql"; - } else { - $params = array($module); + $params = [$module]; $sql .= ' WHERE s.module = ?'; } @@ -926,9 +923,9 @@ public function get_user_events_all(string $module='all', int $from=0, int $to=0 * @param bool $cache Fetch events from cache. * @return array $events The events. */ - public function get_events_due_by_month(int $year, bool $cache=true): array { + public function get_events_due_by_month(int $year, bool $cache = true): array { global $DB; - $events = array(); + $events = []; $cachekey = (string)$year; // Try to get value from cache. @@ -939,7 +936,7 @@ public function get_events_due_by_month(int $year, bool $cache=true): array { $events = $data->events; } else { // Not valid cache data. $modules = $this->get_process_modules(); - list($insql, $params) = $DB->get_in_or_equal($modules); + [$insql, $params] = $DB->get_in_or_equal($modules); $params[] = $year; $sql = "SELECT s.endmonth, COUNT(s.id) as count FROM {local_assessfreq_site} s @@ -978,9 +975,9 @@ public function get_events_due_by_month(int $year, bool $cache=true): array { * @param bool $cache Fetch events from cache. * @return array $events The events. */ - public function get_events_due_monthly_by_user(int $year, bool $cache=true): array { + public function get_events_due_monthly_by_user(int $year, bool $cache = true): array { global $DB; - $events = array(); + $events = []; $cachekey = (string)$year; // Try to get value from cache. @@ -991,7 +988,7 @@ public function get_events_due_monthly_by_user(int $year, bool $cache=true): arr $events = $data->events; } else { // Not valid cache data. $modules = $this->get_process_modules(); - list($insql, $params) = $DB->get_in_or_equal($modules); + [$insql, $params] = $DB->get_in_or_equal($modules); $params[] = $year; $sql = "SELECT s.endmonth, COUNT(u.id) as count FROM {local_assessfreq_site} s @@ -1031,9 +1028,9 @@ public function get_events_due_monthly_by_user(int $year, bool $cache=true): arr * @param bool $cache Fetch events from cache. * @return array $events The events. */ - public function get_events_due_by_activity(int $year, bool $cache=true): array { + public function get_events_due_by_activity(int $year, bool $cache = true): array { global $DB; - $events = array(); + $events = []; $cachekey = (string)$year . '_activity'; // Try to get value from cache. @@ -1043,7 +1040,7 @@ public function get_events_due_by_activity(int $year, bool $cache=true): array { if ($data && (time() < $data->expiry) && $cache) { // Valid cache data. $events = $data->events; } else { // Not valid cache data. - $params = array($year); + $params = [$year]; $sql = 'SELECT s.module, COUNT(s.id) as count FROM {local_assessfreq_site} s LEFT JOIN {course} c ON s.courseid = c.id @@ -1079,9 +1076,9 @@ public function get_events_due_by_activity(int $year, bool $cache=true): array { * @param bool $cache Fetch events from cache. * @return array $years The years with events. */ - public function get_years_has_events(bool $cache=true): array { + public function get_years_has_events(bool $cache = true): array { global $DB; - $years = array(); + $years = []; $cachekey = 'yearevents'; // Try to get value from cache. @@ -1117,10 +1114,10 @@ public function get_years_has_events(bool $cache=true): array { * @return array $dayevents The list of events that day. */ public function get_day_events(string $date, array $modules): array { - $dayevents = array(); + $dayevents = []; if (empty($modules)) { - $modules = array('all'); + $modules = ['all']; } // Get the raw events. @@ -1150,7 +1147,7 @@ public function get_day_events(string $date, array $modules): array { ($event->timelimit == 0) ? get_string('na', 'local_assessfreq') : round(($event->timelimit / 60)); if ($event->module == 'quiz') { - $dashurl = new \moodle_url('/local/assessfreq/dashboard_quiz.php', array('id' => $event->instanceid)); + $dashurl = new \moodle_url('/local/assessfreq/dashboard_quiz.php', ['id' => $event->instanceid]); $event->dashurl = $dashurl->out(); } @@ -1166,11 +1163,11 @@ public function get_day_events(string $date, array $modules): array { // Sort results if we have more than one. if (count($dayevents) > 1) { - $sorton = array( + $sorton = [ 'timestart' => 'ASC', 'courseshortname' => 'ASC', - 'name' => 'ASC' - ); + 'name' => 'ASC', + ]; $dayevents = \local_assessfreq\utils::multi_sort($dayevents, $sorton); $dayevents = array_values($dayevents); @@ -1189,9 +1186,9 @@ public function get_day_events(string $date, array $modules): array { * @param array $modules List of modules to get events for. * @return array $freqarray The array of even frequencies. */ - public function get_frequency_array(int $year, string $metric, array $modules) : array { - $freqarray = array(); - $events = array(); + public function get_frequency_array(int $year, string $metric, array $modules): array { + $freqarray = []; + $events = []; $from = mktime(0, 0, 0, 1, 1, $year); $to = mktime(23, 59, 59, 12, 31, $year); $userfreqarraycache = cache::make('local_assessfreq', 'usereventsallfrequencyarray'); @@ -1210,7 +1207,7 @@ public function get_frequency_array(int $year, string $metric, array $modules) : } if (empty($modules)) { - $modules = array('all'); + $modules = ['all']; } // Get the raw events. @@ -1234,7 +1231,7 @@ public function get_frequency_array(int $year, string $metric, array $modules) : // Construct the multidimensional array. if (empty($freqarray[$year][$month][$day])) { - $freqarray[$year][$month][$day] = array('number' => 1); + $freqarray[$year][$month][$day] = ['number' => 1]; } else { $freqarray[$year][$month][$day]['number']++; } @@ -1272,11 +1269,11 @@ public function get_frequency_array(int $year, string $metric, array $modules) : * @param array $modules The modules to get. * @return array $data The data for the download file. */ - public function get_download_data(int $year, string $metric, array $modules) : array { + public function get_download_data(int $year, string $metric, array $modules): array { global $DB; - $data = array(); - $events = array(); + $data = []; + $events = []; $from = mktime(0, 0, 0, 1, 1, $year); $to = mktime(23, 59, 59, 12, 31, $year); @@ -1287,7 +1284,7 @@ public function get_download_data(int $year, string $metric, array $modules) : a } if (empty($modules)) { - $modules = array('all'); + $modules = ['all']; } // Get the raw events. @@ -1306,7 +1303,7 @@ public function get_download_data(int $year, string $metric, array $modules) : a // Format the data ready for download. foreach ($events as $event) { - $row = array(); + $row = []; // Catch exception when context does not exist because assessfreq tables are out of sync. try { @@ -1323,7 +1320,7 @@ public function get_download_data(int $year, string $metric, array $modules) : a if ($metric == 'assess') { $usercount = count($this->get_event_users($event->contextid, $event->module)); - $row = array($startdate, $duedate, $activity, $name, $url, $usercount); + $row = [$startdate, $duedate, $activity, $name, $url, $usercount]; } else if ($metric == 'students') { $extrafields = \core_user\fields::for_identity($context, false); $selects = $extrafields->get_sql()->selects; @@ -1334,7 +1331,7 @@ public function get_download_data(int $year, string $metric, array $modules) : a $params = [$event->userid]; $userfields = $DB->get_record_sql($sql, $params); - $row = array($startdate, $duedate, $activity, $name, $url); + $row = [$startdate, $duedate, $activity, $name, $url]; foreach ($userfields as $userfield) { $row[] = $userfield; @@ -1354,14 +1351,14 @@ public function get_download_data(int $year, string $metric, array $modules) : a public function get_heat_colors(): array { $config = get_config('local_assessfreq'); - $heatcolors = array( + $heatcolors = [ 1 => $config->heat1, 2 => $config->heat2, 3 => $config->heat3, 4 => $config->heat4, 5 => $config->heat5, - 6 => $config->heat6 - ); + 6 => $config->heat6, + ]; return $heatcolors; } @@ -1376,7 +1373,7 @@ public static function purge_caches($name): void { global $CFG; // Get plugin cache definitions. - $definitions = array(); + $definitions = []; include($CFG->dirroot . '/local/assessfreq/db/caches.php'); $definitionnames = array_keys($definitions); @@ -1393,9 +1390,9 @@ public static function purge_caches($name): void { * @param int $now The timestamp to get the conflicts for. * @return array $conflicts The conflict data. */ - private function get_conflicts(int $now) : array { + private function get_conflicts(int $now): array { global $DB; - $conflicts = array(); + $conflicts = []; // A conflict is an overlapping date range for two or more quizzes where the quiz has at least one common student. $eventsql = 'SELECT lasa.id as eventid, lasb.id as conflictid @@ -1406,7 +1403,7 @@ private function get_conflicts(int $now) : array { WHERE lasa.module = ? AND lasb.module = ? AND lasa.timestart > ?'; - $eventparams = array('quiz', 'quiz', $now, $now); + $eventparams = ['quiz', 'quiz', $now, $now]; $recordset = $DB->get_recordset_sql($eventsql, $eventparams); foreach ($recordset as $record) { @@ -1416,7 +1413,7 @@ private function get_conflicts(int $now) : array { WHERE laua.eventid = ? AND laub.eventid = ?'; - $userparams = array($record->eventid, $record->conflictid); + $userparams = [$record->eventid, $record->conflictid]; $users = $DB->get_fieldset_sql($usersql, $userparams); if (!empty($users)) { @@ -1438,21 +1435,20 @@ private function get_conflicts(int $now) : array { * * @return array $conflicts Conflict data. */ - public function process_conflicts() : array { + public function process_conflicts(): array { // Final result should look like this. - $conflicts['eventid'] = array( - array( + $conflicts['eventid'] = [ + [ 'conflicteventid' => 123, - 'effecteduserids' => array(1, 2, 3) - ), - array( + 'effecteduserids' => [1, 2, 3], + ], + [ 'conflicteventid' => 456, - 'effecteduserids' => array(4, 5, 6) - ), - ); + 'effecteduserids' => [4, 5, 6], + ], + ]; return $conflicts; } - } diff --git a/classes/output/all_participants_inprogress.php b/classes/output/all_participants_inprogress.php index 534cdccc..6c1d746f 100644 --- a/classes/output/all_participants_inprogress.php +++ b/classes/output/all_participants_inprogress.php @@ -26,8 +26,6 @@ use local_assessfreq\quiz; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for all participant summary card. * @@ -36,7 +34,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class all_participants_inprogress { - /** * Generate the markup for the summary chart, * used in the in progress quizzes dashboard. @@ -80,10 +77,9 @@ public function get_all_participants_inprogress_chart(int $now, int $hoursahead $inprogress += $quizobj->tracking->inprogress; $finished += $quizobj->tracking->finished; } - } - $result = array(); + $result = []; if (($notloggedin == 0) && ($loggedin == 0) && ($inprogress == 0) && ($finished == 0)) { $result['hasdata'] = false; @@ -91,26 +87,26 @@ public function get_all_participants_inprogress_chart(int $now, int $hoursahead } else { $result['hasdata'] = true; - $seriesdata = array( + $seriesdata = [ $notloggedin, $loggedin, $inprogress, - $finished - ); + $finished, + ]; - $labels = array( + $labels = [ get_string('notloggedin', 'local_assessfreq'), get_string('loggedin', 'local_assessfreq'), get_string('inprogress', 'local_assessfreq'), - get_string('finished', 'local_assessfreq') - ); + get_string('finished', 'local_assessfreq'), + ]; - $colors = array( + $colors = [ get_config('local_assessfreq', 'notloggedincolor'), get_config('local_assessfreq', 'loggedincolor'), get_config('local_assessfreq', 'inprogresscolor'), - get_config('local_assessfreq', 'finishedcolor') - ); + get_config('local_assessfreq', 'finishedcolor'), + ]; // Create chart object. $chart = new \core\chart_pie(); diff --git a/classes/output/assess_by_activity.php b/classes/output/assess_by_activity.php index 78585742..c867d866 100644 --- a/classes/output/assess_by_activity.php +++ b/classes/output/assess_by_activity.php @@ -26,8 +26,6 @@ use local_assessfreq\frequency; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for assessments by activity card. * @@ -36,7 +34,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class assess_by_activity { - /** * Generate the markup for the process summary chart, * used in the smart media dashboard. @@ -50,10 +47,10 @@ public function get_assess_by_activity_chart(int $year): array { $frequency = new frequency(); $modules = $frequency->get_process_modules(); $activitydata = $frequency->get_events_due_by_activity($year); - $seriesdata = array(); - $labels = array(); + $seriesdata = []; + $labels = []; $charttitle = get_string('assessbyactivity', 'local_assessfreq'); - $result = array(); + $result = []; if (empty($modules[0])) { $result['hasdata'] = false; diff --git a/classes/output/assess_by_month.php b/classes/output/assess_by_month.php index 229cc7e5..46f61aba 100644 --- a/classes/output/assess_by_month.php +++ b/classes/output/assess_by_month.php @@ -26,8 +26,6 @@ use local_assessfreq\frequency; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for assessments due by month card. * @@ -36,6 +34,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class assess_by_month { + use generate_assess_by_month_chart; /** * Generate the markup for the process summary chart, @@ -49,44 +48,7 @@ public function get_assess_by_month_chart(int $year): array { // Get events for the supplied year. $frequency = new frequency(); $yeardata = $frequency->get_events_due_by_month($year); - $seriesdata = array(); $charttitle = get_string('assessbymonth', 'local_assessfreq'); - $result = array(); - - // There is always 12 months in a year, - // even if we don't have data for them all. - for ($i = 1; $i <= 12; $i++) { - if (!empty($yeardata[$i])) { - $seriesdata[] = $yeardata[$i]->count; - } else { - $seriesdata[] = 0; - } - } - - // Create chart object. - $events = new \core\chart_series($charttitle, $seriesdata); - $labels = array( - get_string('jan', 'local_assessfreq'), - get_string('feb', 'local_assessfreq'), - get_string('mar', 'local_assessfreq'), - get_string('apr', 'local_assessfreq'), - get_string('may', 'local_assessfreq'), - get_string('jun', 'local_assessfreq'), - get_string('jul', 'local_assessfreq'), - get_string('aug', 'local_assessfreq'), - get_string('sep', 'local_assessfreq'), - get_string('oct', 'local_assessfreq'), - get_string('nov', 'local_assessfreq'), - get_string('dec', 'local_assessfreq'), - ); - - $chart = new \core\chart_bar(); - $chart->add_series($events); - $chart->set_labels($labels); - - $result['hasdata'] = true; - $result['chart'] = $chart; - - return $result; + return $this->generate_chart($yeardata, $charttitle); } } diff --git a/classes/output/assess_by_month_student.php b/classes/output/assess_by_month_student.php index d6e8042f..11dea159 100644 --- a/classes/output/assess_by_month_student.php +++ b/classes/output/assess_by_month_student.php @@ -26,8 +26,6 @@ use local_assessfreq\frequency; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for assessments due by month student card. * @@ -36,6 +34,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class assess_by_month_student { + use generate_assess_by_month_chart; /** * Generate the markup for the process summary chart, @@ -49,44 +48,8 @@ public function get_assess_by_month_student_chart(int $year): array { // Get events for the supplied year. $frequency = new frequency(); $yeardata = $frequency->get_events_due_monthly_by_user($year); - $seriesdata = array(); $charttitle = get_string('assessbymonthstudents', 'local_assessfreq'); - $result = array(); - - // There is always 12 months in a year, - // even if we don't have data for them all. - for ($i = 1; $i <= 12; $i++) { - if (!empty($yeardata[$i])) { - $seriesdata[] = $yeardata[$i]->count; - } else { - $seriesdata[] = 0; - } - } - - // Create chart object. - $events = new \core\chart_series($charttitle, $seriesdata); - $labels = array( - get_string('jan', 'local_assessfreq'), - get_string('feb', 'local_assessfreq'), - get_string('mar', 'local_assessfreq'), - get_string('apr', 'local_assessfreq'), - get_string('may', 'local_assessfreq'), - get_string('jun', 'local_assessfreq'), - get_string('jul', 'local_assessfreq'), - get_string('aug', 'local_assessfreq'), - get_string('sep', 'local_assessfreq'), - get_string('oct', 'local_assessfreq'), - get_string('nov', 'local_assessfreq'), - get_string('dec', 'local_assessfreq'), - ); - - $chart = new \core\chart_bar(); - $chart->add_series($events); - $chart->set_labels($labels); - - $result['hasdata'] = true; - $result['chart'] = $chart; - return $result; + return $this->generate_chart($yeardata, $charttitle); } } diff --git a/classes/output/dashboard_table.php b/classes/output/dashboard_table.php new file mode 100644 index 00000000..4eaa7ffb --- /dev/null +++ b/classes/output/dashboard_table.php @@ -0,0 +1,201 @@ +<?php +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see <http://www.gnu.org/licenses/>. +namespace local_assessfreq\output; + +/** + * Common code for outputting dashboard tables + * + * @package local_assessfreq + * @copyright 2024 onwards Catalyst IT EU {@link https://catalyst-eu.net} + * @author Mark Johnson <mark.johnson@catalyst-eu.net> + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +trait dashboard_table { + /** + * Get content for title column. + * + * @param \stdClass $row + * @return string html used to display the video field. + * @throws \moodle_exception + */ + public function col_fullname($row): string { + global $OUTPUT; + + return $OUTPUT->user_picture($row, ['size' => 35, 'includefullname' => true]); + } + + /** + * Get content for time start column. + * Displays the user attempt start time. + * + * @param \stdClass $row + * @return string html used to display the field. + */ + public function col_timestart($row) { + if ($row->timestart == 0) { + $content = \html_writer::span(get_string('na', 'local_assessfreq')); + } else { + $datetime = userdate($row->timestart, get_string('trenddatetime', 'local_assessfreq')); + $content = \html_writer::span($datetime); + } + + return $content; + } + + /** + * Get content for time finish column. + * Displays the user attempt finish time. + * + * @param \stdClass $row + * @return string html used to display the field. + */ + public function col_timefinish($row) { + if ($row->timefinish == 0 && $row->timestart == 0) { + $content = \html_writer::span(get_string('na', 'local_assessfreq')); + } else if ($row->timefinish == 0 && $row->timestart > 0) { + $time = $row->timestart + $row->timelimit; + $datetime = userdate($time, get_string('trenddatetime', 'local_assessfreq')); + $content = \html_writer::span($datetime, 'local-assessfreq-disabled'); + } else { + $datetime = userdate($row->timefinish, get_string('trenddatetime', 'local_assessfreq')); + $content = \html_writer::span($datetime); + } + + return $content; + } + + /** + * Get content for state column. + * Displays the users state in the quiz. + * + * @param \stdClass $row + * @return string html used to display the field. + */ + public function col_state($row) { + if ($row->state == 'notloggedin') { + $color = 'background: ' . get_config('local_assessfreq', 'notloggedincolor'); + } else if ($row->state == 'loggedin') { + $color = 'background: ' . get_config('local_assessfreq', 'loggedincolor'); + } else if ($row->state == 'inprogress') { + $color = 'background: ' . get_config('local_assessfreq', 'inprogresscolor'); + } else if ($row->state == 'uploadpending') { + $color = 'background: ' . get_config('local_assessfreq', 'inprogresscolor'); + } else if ($row->state == 'finished') { + $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); + } else if ($row->state == 'abandoned') { + $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); + } else if ($row->state == 'overdue') { + $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); + } + + $content = \html_writer::span('', 'local-assessfreq-status-icon', ['style' => $color]); + $content .= get_string($row->state, 'local_assessfreq'); + + return $content; + } + + /** + * Return an array of headers common across dashboard tables. + * + * @return array + */ + protected function get_common_headers(): array { + return [ + get_string('quiztimeopen', 'local_assessfreq'), + get_string('quiztimeclose', 'local_assessfreq'), + get_string('quiztimelimit', 'local_assessfreq'), + get_string('quiztimestart', 'local_assessfreq'), + get_string('quiztimefinish', 'local_assessfreq'), + get_string('status', 'local_assessfreq'), + get_string('actions', 'local_assessfreq'), + ]; + } + + /** + * Return an array of columns common across dashboard tables. + * + * @return array + */ + protected function get_common_columns(): array { + return [ + 'timeopen', + 'timeclose', + 'timelimit', + 'timestart', + 'timefinish', + 'state', + 'actions', + ]; + } + + /** + * Return HTML for common column actions. + * + * @param \stdClass $row + * @return string + */ + protected function get_common_column_actions(\stdClass $row): string { + global $OUTPUT; + $actions = ''; + if ( + $row->state == 'finished' + || $row->state == 'inprogress' + || $row->state == 'uploadpending' + || $row->state == 'abandoned' + || $row->state == 'overdue' + ) { + $classes = 'action-icon'; + $attempturl = new \moodle_url('/mod/quiz/review.php', ['attempt' => $row->attemptid]); + $attributes = [ + 'class' => $classes, + 'id' => 'tool-assessfreq-attempt-' . $row->id, + 'data-toggle' => 'tooltip', + 'data-placement' => 'top', + 'title' => get_string('userattempt', 'local_assessfreq'), + ]; + } else { + $classes = 'action-icon disabled'; + $attempturl = '#'; + $attributes = [ + 'class' => $classes, + 'id' => 'tool-assessfreq-attempt-' . $row->id, + ]; + } + $icon = $OUTPUT->render(new \pix_icon('i/search', '')); + $actions .= \html_writer::link($attempturl, $icon, $attributes); + + $profileurl = new \moodle_url('/user/profile.php', ['id' => $row->id]); + $icon = $OUTPUT->render(new \pix_icon('i/completion_self', '')); + $actions .= \html_writer::link($profileurl, $icon, [ + 'class' => 'action-icon', + 'id' => 'tool-assessfreq-profile-' . $row->id, + 'data-toggle' => 'tooltip', + 'data-placement' => 'top', + 'title' => get_string('userprofile', 'local_assessfreq'), + ]); + + $logurl = new \moodle_url('/report/log/user.php', ['id' => $row->id, 'course' => 1, 'mode' => 'all']); + $icon = $OUTPUT->render(new \pix_icon('i/report', '')); + $actions .= \html_writer::link($logurl, $icon, [ + 'class' => 'action-icon', + 'id' => 'tool-assessfreq-log-' . $row->id, + 'data-toggle' => 'tooltip', + 'data-placement' => 'top', + 'title' => get_string('userlogs', 'local_assessfreq'), + ]); + return $actions; + } +} diff --git a/classes/output/generate_assess_by_month_chart.php b/classes/output/generate_assess_by_month_chart.php new file mode 100644 index 00000000..5ce61edd --- /dev/null +++ b/classes/output/generate_assess_by_month_chart.php @@ -0,0 +1,75 @@ +<?php +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see <http://www.gnu.org/licenses/>. +namespace local_assessfreq\output; + +/** + * Common code for generating charts of assessments by month + * + * @package local_assessfreq + * @copyright 2024 onwards Catalyst IT EU {@link https://catalyst-eu.net} + * @author Mark Johnson <mark.johnson@catalyst-eu.net> + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +trait generate_assess_by_month_chart { + /** + * Generate chart markup from monthly events for a year. + * + * @param array $yeardata + * @param string $charttitle + * @return array + */ + protected function generate_chart($yeardata, $charttitle): array { + $result = []; + $seriesdata = []; + + // There is always 12 months in a year, + // even if we don't have data for them all. + for ($i = 1; $i <= 12; $i++) { + if (!empty($yeardata[$i])) { + $seriesdata[] = $yeardata[$i]->count; + } else { + $seriesdata[] = 0; + } + } + + // Create chart object. + $events = new \core\chart_series($charttitle, $seriesdata); + $labels = [ + get_string('jan', 'local_assessfreq'), + get_string('feb', 'local_assessfreq'), + get_string('mar', 'local_assessfreq'), + get_string('apr', 'local_assessfreq'), + get_string('may', 'local_assessfreq'), + get_string('jun', 'local_assessfreq'), + get_string('jul', 'local_assessfreq'), + get_string('aug', 'local_assessfreq'), + get_string('sep', 'local_assessfreq'), + get_string('oct', 'local_assessfreq'), + get_string('nov', 'local_assessfreq'), + get_string('dec', 'local_assessfreq'), + ]; + + $chart = new \core\chart_bar(); + $chart->add_series($events); + $chart->set_labels($labels); + + $result['hasdata'] = true; + $result['chart'] = $chart; + + return $result; + } + +} diff --git a/classes/output/inprogress_participant_summary.php b/classes/output/inprogress_participant_summary.php index d4ad6bbe..c27ec8b1 100644 --- a/classes/output/inprogress_participant_summary.php +++ b/classes/output/inprogress_participant_summary.php @@ -24,8 +24,6 @@ namespace local_assessfreq\output; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for participant summary card. * @@ -34,7 +32,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class inprogress_participant_summary { - /** * Generate the markup for the summary chart, * used in the quiz dashboard. @@ -44,26 +41,26 @@ class inprogress_participant_summary { */ public function get_inprogress_participant_summary_chart(\stdClass $participants): \core\chart_pie { - $seriesdata = array( + $seriesdata = [ $participants->notloggedin, $participants->loggedin, $participants->inprogress, - $participants->finished - ); + $participants->finished, + ]; - $labels = array( + $labels = [ get_string('notloggedin', 'local_assessfreq'), get_string('loggedin', 'local_assessfreq'), get_string('inprogress', 'local_assessfreq'), - get_string('finished', 'local_assessfreq') - ); + get_string('finished', 'local_assessfreq'), + ]; - $colors = array( + $colors = [ get_config('local_assessfreq', 'notloggedincolor'), get_config('local_assessfreq', 'loggedincolor'), get_config('local_assessfreq', 'inprogresscolor'), - get_config('local_assessfreq', 'finishedcolor') - ); + get_config('local_assessfreq', 'finishedcolor'), + ]; // Create chart object. $chart = new \core\chart_pie(); diff --git a/classes/output/participant_summary.php b/classes/output/participant_summary.php index 65b1360f..18687aac 100644 --- a/classes/output/participant_summary.php +++ b/classes/output/participant_summary.php @@ -26,8 +26,6 @@ use local_assessfreq\quiz; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for participant summary card. * @@ -36,7 +34,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class participant_summary { - /** * Generate the markup for the summary chart, * used in the quiz dashboard. @@ -49,7 +46,7 @@ public function get_participant_summary_chart(int $quizid): array { $quizdata = new quiz(); $allparticipantdata = $quizdata->get_quiz_tracking($quizid); $participantdata = array_pop($allparticipantdata); - $result = array(); + $result = []; if (empty($participantdata)) { $result['hasdata'] = false; @@ -57,26 +54,26 @@ public function get_participant_summary_chart(int $quizid): array { } else { $result['hasdata'] = true; - $seriesdata = array( + $seriesdata = [ $participantdata->notloggedin, $participantdata->loggedin, $participantdata->inprogress, - $participantdata->finished - ); + $participantdata->finished, + ]; - $labels = array( + $labels = [ get_string('notloggedin', 'local_assessfreq'), get_string('loggedin', 'local_assessfreq'), get_string('inprogress', 'local_assessfreq'), - get_string('finished', 'local_assessfreq') - ); + get_string('finished', 'local_assessfreq'), + ]; - $colors = array( + $colors = [ get_config('local_assessfreq', 'notloggedincolor'), get_config('local_assessfreq', 'loggedincolor'), get_config('local_assessfreq', 'inprogresscolor'), - get_config('local_assessfreq', 'finishedcolor') - ); + get_config('local_assessfreq', 'finishedcolor'), + ]; // Create chart object. $chart = new \core\chart_pie(); diff --git a/classes/output/participant_trend.php b/classes/output/participant_trend.php index db9e1705..5aa37a76 100644 --- a/classes/output/participant_trend.php +++ b/classes/output/participant_trend.php @@ -26,8 +26,6 @@ use local_assessfreq\quiz; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for participant trend card. * @@ -36,7 +34,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class participant_trend { - /** * Generate the markup for the trend chart, * used in the quiz dashboard. @@ -48,12 +45,12 @@ public function get_participant_trend_chart(int $quizid): array { $quizdata = new quiz(); $allparticipantdata = $quizdata->get_quiz_tracking($quizid); - $notloggedin = array(); - $loggedin = array(); - $inprogress = array(); - $finished = array(); - $labels = array(); - $result = array(); + $notloggedin = []; + $loggedin = []; + $inprogress = []; + $finished = []; + $labels = []; + $result = []; if (empty($allparticipantdata)) { $result['hasdata'] = false; diff --git a/classes/output/quiz_user_table.php b/classes/output/quiz_user_table.php index 75017781..9c8f44b5 100644 --- a/classes/output/quiz_user_table.php +++ b/classes/output/quiz_user_table.php @@ -28,8 +28,8 @@ require_once($CFG->libdir . '/tablelib.php'); -use \table_sql; -use \renderable; +use table_sql; +use renderable; /** * Renderable table for quiz dashboard users. @@ -39,6 +39,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class quiz_user_table extends table_sql implements renderable { + use dashboard_table; /** * @var integer $quizid The ID of the braodcast to get the acknowledgements for. @@ -85,7 +86,7 @@ public function __construct(string $baseurl, int $quizid, int $contextid, string $this->downloadable = false; $this->define_baseurl($baseurl); - $quizrecord = $DB->get_record('quiz', array('id' => $this->quizid), 'timeopen, timeclose, timelimit'); + $quizrecord = $DB->get_record('quiz', ['id' => $this->quizid], 'timeopen, timeclose, timelimit'); $this->timeopen = $quizrecord->timeopen; $this->timeclose = $quizrecord->timeclose; $this->timelimit = $quizrecord->timelimit; @@ -105,49 +106,14 @@ public function __construct(string $baseurl, int $quizid, int $contextid, string $columns[] = $field; } - $headers[] = get_string('quiztimeopen', 'local_assessfreq'); - $columns[] = 'timeopen'; - - $headers[] = get_string('quiztimeclose', 'local_assessfreq'); - $columns[] = 'timeclose'; - - $headers[] = get_string('quiztimelimit', 'local_assessfreq'); - $columns[] = 'timelimit'; - - $headers[] = get_string('quiztimestart', 'local_assessfreq'); - $columns[] = 'timestart'; - - $headers[] = get_string('quiztimefinish', 'local_assessfreq'); - $columns[] = 'timefinish'; - - $headers[] = get_string('status', 'local_assessfreq'); - $columns[] = 'state'; - - $headers[] = get_string('actions', 'local_assessfreq'); - $columns[] = 'actions'; - - $this->define_columns($columns); - $this->define_headers($headers); + $this->define_columns(array_merge($columns, $this->get_common_columns())); + $this->define_headers(array_merge($headers, $this->get_common_headers())); $this->extrafields = $extrafields; // Setup pagination. $this->currpage = $page; $this->sortable(true); - $this->column_nosort = array('actions'); - - } - - /** - * Get content for title column. - * - * @param \stdClass $row - * @return string html used to display the video field. - * @throws \moodle_exception - */ - public function col_fullname($row) { - global $OUTPUT; - - return $OUTPUT->user_picture($row, array('size' => 35, 'includefullname' => true)); + $this->column_nosort = ['actions']; } /** @@ -227,76 +193,6 @@ public function col_timelimit($row) { return $content; } - /** - * Get content for time start column. - * Displays the user attempt start time. - * - * @param \stdClass $row - * @return string html used to display the field. - */ - public function col_timestart($row) { - if ($row->timestart == 0) { - $content = \html_writer::span(get_string('na', 'local_assessfreq')); - } else { - $datetime = userdate($row->timestart, get_string('trenddatetime', 'local_assessfreq')); - $content = \html_writer::span($datetime); - } - - return $content; - } - - /** - * Get content for time finish column. - * Displays the user attempt finish time. - * - * @param \stdClass $row - * @return string html used to display the field. - */ - public function col_timefinish($row) { - if ($row->timefinish == 0 && $row->timestart == 0) { - $content = \html_writer::span(get_string('na', 'local_assessfreq')); - } else if ($row->timefinish == 0 && $row->timestart > 0) { - $time = $row->timestart + $row->timelimit; - $datetime = userdate($time, get_string('trenddatetime', 'local_assessfreq')); - $content = \html_writer::span($datetime, 'local-assessfreq-disabled'); - } else { - $datetime = userdate($row->timefinish, get_string('trenddatetime', 'local_assessfreq')); - $content = \html_writer::span($datetime); - } - - return $content; - } - - /** - * Get content for state column. - * Displays the users state in the quiz. - * - * @param \stdClass $row - * @return string html used to display the field. - */ - public function col_state($row) { - if ($row->state == 'notloggedin') { - $color = 'background: ' . get_config('local_assessfreq', 'notloggedincolor'); - } else if ($row->state == 'loggedin') { - $color = 'background: ' . get_config('local_assessfreq', 'loggedincolor'); - } else if ($row->state == 'inprogress') { - $color = 'background: ' . get_config('local_assessfreq', 'inprogresscolor'); - } else if ($row->state == 'uploadpending') { - $color = 'background: ' . get_config('local_assessfreq', 'inprogresscolor'); - } else if ($row->state == 'finished') { - $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); - } else if ($row->state == 'abandoned') { - $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); - } else if ($row->state == 'overdue') { - $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); - } - - $content = \html_writer::span('', 'local-assessfreq-status-icon', array('style' => $color)); - $content .= get_string($row->state, 'local_assessfreq'); - - return $content; - } - /** * Get content for actions column. * Displays the actions for the user. @@ -310,58 +206,15 @@ public function col_actions($row) { $manage = ''; $icon = $OUTPUT->render(new \pix_icon('i/duration', '')); - $manage .= \html_writer::link('#', $icon, array( + $manage .= \html_writer::link('#', $icon, [ 'class' => 'action-icon override', 'id' => 'tool-assessfreq-override-' . $row->id, 'data-toggle' => 'tooltip', 'data-placement' => 'top', - 'title' => get_string('useroverride', 'local_assessfreq') - )); - - if ($row->state == 'finished' - || $row->state == 'inprogress' - || $row->state == 'uploadpending' - || $row->state == 'abandoned' - || $row->state == 'overdue') { - $classes = 'action-icon'; - $attempturl = new \moodle_url('/mod/quiz/review.php', array('attempt' => $row->attemptid)); - $attributes = array( - 'class' => $classes, - 'id' => 'tool-assessfreq-attempt-' . $row->id, - 'data-toggle' => 'tooltip', - 'data-placement' => 'top', - 'title' => get_string('userattempt', 'local_assessfreq') - ); - } else { - $classes = 'action-icon disabled'; - $attempturl = '#'; - $attributes = array( - 'class' => $classes, - 'id' => 'tool-assessfreq-attempt-' . $row->id, - ); - } - $icon = $OUTPUT->render(new \pix_icon('i/search', '')); - $manage .= \html_writer::link($attempturl, $icon, $attributes); - - $profileurl = new \moodle_url('/user/profile.php', array('id' => $row->id)); - $icon = $OUTPUT->render(new \pix_icon('i/completion_self', '')); - $manage .= \html_writer::link($profileurl, $icon, array( - 'class' => 'action-icon', - 'id' => 'tool-assessfreq-profile-' . $row->id, - 'data-toggle' => 'tooltip', - 'data-placement' => 'top', - 'title' => get_string('userprofile', 'local_assessfreq') - )); - - $logurl = new \moodle_url('/report/log/user.php', array('id' => $row->id, 'course' => 1, 'mode' => 'all')); - $icon = $OUTPUT->render(new \pix_icon('i/report', '')); - $manage .= \html_writer::link($logurl, $icon, array( - 'class' => 'action-icon', - 'id' => 'tool-assessfreq-log-' . $row->id, - 'data-toggle' => 'tooltip', - 'data-placement' => 'top', - 'title' => get_string('userlogs', 'local_assessfreq') - )); + 'title' => get_string('useroverride', 'local_assessfreq'), + ]); + + $manage .= $this->get_common_column_actions($row); return $manage; } @@ -388,7 +241,7 @@ public function query_db($pagesize, $useinitialsbar = false) { $capabilities = $frequency->get_module_capabilities('quiz'); $context = $quiz->get_quiz_context($this->quizid); - list($joins, $wheres, $params) = $frequency->generate_enrolled_wheres_joins_params($context, $capabilities); + [$joins, $wheres, $params] = $frequency->generate_enrolled_wheres_joins_params($context, $capabilities); $attemptsql = 'SELECT qa_a.userid, qa_a.state, qa_a.quiz, qa_a.id as attemptid, qa_a.timestart as timestart, qa_a.timefinish as timefinish FROM {quiz_attempts} qa_a @@ -435,7 +288,7 @@ public function query_db($pagesize, $useinitialsbar = false) { } $records = $DB->get_recordset_sql($sql, $params); - $data = array(); + $data = []; $offset = $this->currpage * $pagesize; $offsetcount = 0; $recordcount = 0; @@ -446,14 +299,13 @@ public function query_db($pagesize, $useinitialsbar = false) { // Because we are using COALESE and CASE for state we can't use SQL WHERE so we need to filter in PHP land. // Also because we need to do some filtering in PHP land, we'll do it all here. $searchcount = -1; - $searchfields = array_merge($this->extrafields, array('firstname', 'lastname', 'state')); + $searchfields = array_merge($this->extrafields, ['firstname', 'lastname', 'state']); foreach ($searchfields as $searchfield) { if (stripos($record->{$searchfield}, $this->search) !== false) { $searchcount++; } } - } if ($searchcount > -1 && $offsetcount >= $offset && $recordcount < $pagesize) { @@ -465,9 +317,8 @@ public function query_db($pagesize, $useinitialsbar = false) { } if ($searchcount > -1) { - $offsetcount ++; + $offsetcount++; } - } $records->close(); diff --git a/classes/output/renderer.php b/classes/output/renderer.php index ead4d4c9..a89d0365 100644 --- a/classes/output/renderer.php +++ b/classes/output/renderer.php @@ -24,9 +24,6 @@ namespace local_assessfreq\output; use local_assessfreq\quiz; - -defined('MOODLE_INTERNAL') || die; - use plugin_renderer_base; use local_assessfreq\frequency; @@ -38,7 +35,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class renderer extends plugin_renderer_base { - /** * Render the html for the report cards. * Most content is loaded by ajax @@ -54,7 +50,7 @@ public function render_report_cards(): string { $years = $frequency->get_years_has_events(); if (empty($years)) { - $years = array($currentyear); + $years = [$currentyear]; } // Add current year to the selection of years if missing. @@ -62,18 +58,18 @@ public function render_report_cards(): string { $years[] = $currentyear; } - $context = array('years' => array(), 'currentyear' => $preferenceyear); + $context = ['years' => [], 'currentyear' => $preferenceyear]; if (!empty($years)) { foreach ($years as $year) { if ($year == $preferenceyear) { - $context['years'][] = array('year' => array('val' => $year, 'active' => 'true')); + $context['years'][] = ['year' => ['val' => $year, 'active' => 'true']]; } else { - $context['years'][] = array('year' => array('val' => $year)); + $context['years'][] = ['year' => ['val' => $year]]; } } } else { - $context['years'][] = array('year' => array('val' => $preferenceyear, 'active' => 'true')); + $context['years'][] = ['year' => ['val' => $preferenceyear, 'active' => 'true']]; } return $this->render_from_template('local_assessfreq/report-cards', $context); @@ -113,7 +109,14 @@ public function render_student_table(string $baseurl, int $quizid, int $contexti * @return string $output HTML for the table. */ public function render_student_search_table( - string $baseurl, int $contextid, string $search, int $hoursahead, int $hoursbehind, int $now, int $page=0): string { + string $baseurl, + int $contextid, + string $search, + int $hoursahead, + int $hoursbehind, + int $now, + int $page = 0 + ): string { $renderable = new student_search_table($baseurl, $contextid, $search, $hoursahead, $hoursbehind, $now, $page); $perpage = 50; @@ -139,8 +142,14 @@ public function render_student_search_table( * @param int $hoursbehind Amount of time in hours to look behind for quizzes starting. * @return string $output HTML for the table. */ - public function render_quizzes_inprogress_table(string $search, int $page, string $sorton, string $direction, - int $hoursahead = 0, int $hoursbehind = 0): string { + public function render_quizzes_inprogress_table( + string $search, + int $page, + string $sorton, + string $direction, + int $hoursahead = 0, + int $hoursbehind = 0 + ): string { $context = \context_system::instance(); // TODO: pass the actual context in from the caller. $now = time(); $quiz = new quiz($hoursahead, $hoursbehind); @@ -163,18 +172,18 @@ public function render_quizzes_inprogress_table(string $search, int $page, strin } } - list($filtered, $totalrows) = $quiz->filter_quizzes($inprogressquizzes, $search, $page, $pagesize); + [$filtered, $totalrows] = $quiz->filter_quizzes($inprogressquizzes, $search, $page, $pagesize); $sortedquizzes = \local_assessfreq\utils::sort($filtered, $sorton, $direction); $pagingbar = new \paging_bar($totalrows, $page, $pagesize, '/'); $pagingoutput = $this->render($pagingbar); - $context = array( + $context = [ 'quizzes' => array_values($sortedquizzes), 'quizids' => json_encode(array_keys($sortedquizzes)), 'context' => $context->id, - 'pagingbar' => $pagingoutput - ); + 'pagingbar' => $pagingoutput, + ]; $output = $this->render_from_template('local_assessfreq/quiz-inprogress-summary', $context); @@ -195,20 +204,20 @@ public function render_report_heatmap(): string { $frequency = new frequency(); // Initial context setup. - $context = array( - 'years' => array(), + $context = [ + 'years' => [], 'currentyear' => $preferenceyear, - 'modules' => array(), - 'metrics' => array(), + 'modules' => [], + 'metrics' => [], 'sesskey' => sesskey(), - 'downloadmetric' => $preferencemetric - ); + 'downloadmetric' => $preferencemetric, + ]; // Get years that have events and load into context. $years = $frequency->get_years_has_events(); if (empty($years)) { - $years = array($currentyear); + $years = [$currentyear]; } // Add current year to the selection of years if missing. @@ -219,38 +228,38 @@ public function render_report_heatmap(): string { if (!empty($years)) { foreach ($years as $year) { if ($year == $preferenceyear) { - $context['years'][] = array('year' => array('val' => $year, 'active' => 'true')); + $context['years'][] = ['year' => ['val' => $year, 'active' => 'true']]; $context['downloadyear'] = $year; } else { - $context['years'][] = array('year' => array('val' => $year)); + $context['years'][] = ['year' => ['val' => $year]]; } } } else { - $context['years'][] = array('year' => array('val' => $preferenceyear, 'active' => 'true')); + $context['years'][] = ['year' => ['val' => $preferenceyear, 'active' => 'true']]; $context['downloadyear'] = $preferenceyear; } // Get modules for filters and load into context. $modules = $frequency->get_process_modules(); - if (empty($preferencemodules) || $preferencemodules === array('all')) { - $context['modules'][] = array('module' => array('val' => 'all', 'name' => get_string('all'), 'active' => 'true')); + if (empty($preferencemodules) || $preferencemodules === ['all']) { + $context['modules'][] = ['module' => ['val' => 'all', 'name' => get_string('all'), 'active' => 'true']]; } else { - $context['modules'][] = array('module' => array('val' => 'all', 'name' => get_string('all'))); + $context['modules'][] = ['module' => ['val' => 'all', 'name' => get_string('all')]]; } if (!empty($modules[0])) { foreach ($modules as $module) { $modulename = get_string('modulename', $module); if (in_array($module, $preferencemodules)) { - $context['modules'][] = array('module' => array('val' => $module, 'name' => $modulename, 'active' => 'true')); + $context['modules'][] = ['module' => ['val' => $module, 'name' => $modulename, 'active' => 'true']]; } else { - $context['modules'][] = array('module' => array('val' => $module, 'name' => $modulename)); + $context['modules'][] = ['module' => ['val' => $module, 'name' => $modulename]]; } } } // Get metric details and load into context. - $context['metrics'] = array($preferencemetric => 'true'); + $context['metrics'] = [$preferencemetric => 'true']; return $this->render_from_template('local_assessfreq/report-heatmap', $context); } @@ -261,7 +270,7 @@ public function render_report_heatmap(): string { * @param string $baseurl the base url to render this report on. * @return string $html the html to display. */ - public function render_dashboard_assessment(string $baseurl) : string { + public function render_dashboard_assessment(string $baseurl): string { $html = ''; $html .= $this->header(); $html .= $this->render_report_cards(); @@ -278,18 +287,18 @@ public function render_dashboard_assessment(string $baseurl) : string { */ private function render_quiz_select_refresh_button(): string { $preferencerefresh = get_user_preferences('local_assessfreq_quiz_refresh_preference', 60); - $refreshminutes = array( + $refreshminutes = [ 60 => 'minuteone', 120 => 'minutetwo', 300 => 'minutefive', 600 => 'minuteten', - ); + ]; - $context = array( + $context = [ 'refreshinitial' => get_string($refreshminutes[$preferencerefresh], 'local_assessfreq'), - 'refresh' => array($refreshminutes[$preferencerefresh] => 'true'), - 'hide' => true - ); + 'refresh' => [$refreshminutes[$preferencerefresh] => 'true'], + 'hide' => true, + ]; return $this->render_from_template('local_assessfreq/quiz-dashboard-controls', $context); } @@ -304,26 +313,26 @@ private function render_quiz_refresh_button(): string { $preferencehoursahead = get_user_preferences('local_assessfreq_quizzes_inprogress_table_hoursahead_preference', 0); $preferencehoursbehind = get_user_preferences('local_assessfreq_quizzes_inprogress_table_hoursbehind_preference', 0); - $refreshminutes = array( + $refreshminutes = [ 60 => 'minuteone', 120 => 'minutetwo', 300 => 'minutefive', 600 => 'minuteten', - ); + ]; - $hours = array( + $hours = [ 0 => 'hours0', 1 => 'hours1', 4 => 'hours4', 8 => 'hours8', - ); + ]; - $context = array( + $context = [ 'refreshinitial' => get_string($refreshminutes[$preferencerefresh], 'local_assessfreq'), - 'refresh' => array($refreshminutes[$preferencerefresh] => 'true'), - 'hoursahead' => array($hours[$preferencehoursahead] => 'true'), - 'hoursbehind' => array($hours[$preferencehoursbehind] => 'true'), - ); + 'refresh' => [$refreshminutes[$preferencerefresh] => 'true'], + 'hoursahead' => [$hours[$preferencehoursahead] => 'true'], + 'hoursbehind' => [$hours[$preferencehoursbehind] => 'true'], + ]; return $this->render_from_template('local_assessfreq/quiz-dashboard-inprogress-controls', $context); } @@ -335,15 +344,15 @@ private function render_quiz_refresh_button(): string { */ private function render_quiz_dashboard_cards(): string { $preferencerows = get_user_preferences('local_assessfreq_quiz_table_rows_preference', 20); - $rows = array( + $rows = [ 20 => 'rows20', 50 => 'rows50', 100 => 'rows100', - ); + ]; - $context = array( - 'rows' => array($rows[$preferencerows] => 'true'), - ); + $context = [ + 'rows' => [$rows[$preferencerows] => 'true'], + ]; return $this->render_from_template('local_assessfreq/quiz-dashboard-cards', $context); } @@ -356,16 +365,16 @@ private function render_quiz_dashboard_cards(): string { private function render_quiz_dashboard_inprogress_cards(): string { $preferencerows = get_user_preferences('local_assessfreq_quiz_table_inprogress_preference', 10); $preferencesort = get_user_preferences('local_assessfreq_quiz_table_inprogress_sort_preference', 'name_asc'); - $rows = array( + $rows = [ 5 => 'rows5', 10 => 'rows10', 20 => 'rows20', - ); + ]; - $context = array( - 'rows' => array($rows[$preferencerows] => 'true'), - 'sort' => array($preferencesort => 'true') - ); + $context = [ + 'rows' => [$rows[$preferencerows] => 'true'], + 'sort' => [$preferencesort => 'true'], + ]; return $this->render_from_template('local_assessfreq/quiz-dashboard-inprogress-cards', $context); } @@ -381,41 +390,41 @@ private function render_student_table_cards(): string { $preferencehoursbehind = get_user_preferences('local_assessfreq_student_search_table_hoursbehind_preference', 1); $preferencerefresh = get_user_preferences('local_assessfreq_quiz_refresh_preference', 60); - $refreshminutes = array( + $refreshminutes = [ 60 => 'minuteone', 120 => 'minutetwo', 300 => 'minutefive', 600 => 'minuteten', - ); + ]; - $rows = array( + $rows = [ 20 => 'rows20', 50 => 'rows50', 100 => 'rows100', - ); + ]; - $hours = array( + $hours = [ 0 => 'hours0', 1 => 'hours1', 4 => 'hours4', 8 => 'hours8', - ); + ]; $preferencerefresh = get_user_preferences('local_assessfreq_quiz_refresh_preference', 60); - $refreshminutes = array( + $refreshminutes = [ 60 => 'minuteone', 120 => 'minutetwo', 300 => 'minutefive', 600 => 'minuteten', - ); + ]; - $context = array( - 'rows' => array($rows[$preferencerows] => 'true'), - 'hoursahead' => array($hours[$preferencehoursahead] => 'true'), - 'hoursbehind' => array($hours[$preferencehoursbehind] => 'true'), + $context = [ + 'rows' => [$rows[$preferencerows] => 'true'], + 'hoursahead' => [$hours[$preferencehoursahead] => 'true'], + 'hoursbehind' => [$hours[$preferencehoursbehind] => 'true'], 'refreshinitial' => get_string($refreshminutes[$preferencerefresh], 'local_assessfreq'), - 'refresh' => array($refreshminutes[$preferencerefresh] => 'true') - ); + 'refresh' => [$refreshminutes[$preferencerefresh] => 'true'], + ]; return $this->render_from_template('local_assessfreq/student-search', $context); } @@ -426,7 +435,7 @@ private function render_student_table_cards(): string { * @param string $baseurl the base url to render this report on. * @return string $html the html to display. */ - public function render_dashboard_quiz(string $baseurl) : string { + public function render_dashboard_quiz(string $baseurl): string { $html = ''; $html .= $this->header(); $html .= $this->render_quiz_select_refresh_button(); @@ -442,7 +451,7 @@ public function render_dashboard_quiz(string $baseurl) : string { * @param string $baseurl the base url to render this report on. * @return string $html the html to display. */ - public function render_dashboard_quiz_inprogress(string $baseurl) : string { + public function render_dashboard_quiz_inprogress(string $baseurl): string { $html = ''; $html .= $this->header(); $html .= $this->render_quiz_refresh_button(); @@ -457,7 +466,7 @@ public function render_dashboard_quiz_inprogress(string $baseurl) : string { * * @return string $html the html to display. */ - public function render_student_search() : string { + public function render_student_search(): string { $html = ''; $html .= $this->header(); $html .= $this->render_student_table_cards(); diff --git a/classes/output/student_search_table.php b/classes/output/student_search_table.php index f517457e..9e761202 100644 --- a/classes/output/student_search_table.php +++ b/classes/output/student_search_table.php @@ -28,8 +28,8 @@ require_once($CFG->libdir . '/tablelib.php'); -use \table_sql; -use \renderable; +use table_sql; +use renderable; /** * Renderable table for quiz dashboard users. @@ -39,6 +39,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class student_search_table extends table_sql implements renderable { + use dashboard_table; /** * Ammount of time in hours for lookahead values. @@ -86,7 +87,14 @@ class student_search_table extends table_sql implements renderable { * @throws \coding_exception */ public function __construct( - string $baseurl, int $contextid, string $search, int $hoursahead, int $hoursbehind, int $now, int $page=0) { + string $baseurl, + int $contextid, + string $search, + int $hoursahead, + int $hoursbehind, + int $now, + int $page = 0 + ) { parent::__construct('local_assessfreq_student_search_table'); $this->search = $search; @@ -116,36 +124,14 @@ public function __construct( $headers[] = get_string('quiz', 'local_assessfreq'); $columns[] = 'quizname'; - $headers[] = get_string('quiztimeopen', 'local_assessfreq'); - $columns[] = 'timeopen'; - - $headers[] = get_string('quiztimeclose', 'local_assessfreq'); - $columns[] = 'timeclose'; - - $headers[] = get_string('quiztimelimit', 'local_assessfreq'); - $columns[] = 'timelimit'; - - $headers[] = get_string('quiztimestart', 'local_assessfreq'); - $columns[] = 'timestart'; - - $headers[] = get_string('quiztimefinish', 'local_assessfreq'); - $columns[] = 'timefinish'; - - $headers[] = get_string('status', 'local_assessfreq'); - $columns[] = 'state'; - - $headers[] = get_string('actions', 'local_assessfreq'); - $columns[] = 'actions'; - - $this->define_columns($columns); - $this->define_headers($headers); + $this->define_columns(array_merge($columns, $this->get_common_columns())); + $this->define_headers(array_merge($headers, $this->get_common_headers())); $this->extrafields = $extrafields; // Setup pagination. $this->currpage = $page; $this->sortable(true); - $this->column_nosort = array('actions'); - + $this->column_nosort = ['actions']; } /** @@ -158,7 +144,7 @@ public function __construct( public function col_fullname($row) { global $OUTPUT; - return $OUTPUT->user_picture($row, array('size' => 35, 'includefullname' => true)); + return $OUTPUT->user_picture($row, ['size' => 35, 'includefullname' => true]); } /** @@ -189,7 +175,7 @@ public function other_cols($colname, $data) { */ public function col_quizname($row) { - $quizurl = new \moodle_url('/mod/quiz/view.php', array('id' => $row->quizinstance)); + $quizurl = new \moodle_url('/mod/quiz/view.php', ['id' => $row->quizinstance]); $quizlink = \html_writer::link($quizurl, format_string($row->quizname, true)); return $quizlink; @@ -252,76 +238,6 @@ public function col_timelimit($row) { return $content; } - /** - * Get content for time start column. - * Displays the user attempt start time. - * - * @param \stdClass $row - * @return string html used to display the field. - */ - public function col_timestart($row) { - if ($row->timestart == 0) { - $content = \html_writer::span(get_string('na', 'local_assessfreq')); - } else { - $datetime = userdate($row->timestart, get_string('trenddatetime', 'local_assessfreq')); - $content = \html_writer::span($datetime); - } - - return $content; - } - - /** - * Get content for time finish column. - * Displays the user attempt finish time. - * - * @param \stdClass $row - * @return string html used to display the field. - */ - public function col_timefinish($row) { - if ($row->timefinish == 0 && $row->timestart == 0) { - $content = \html_writer::span(get_string('na', 'local_assessfreq')); - } else if ($row->timefinish == 0 && $row->timestart > 0) { - $time = $row->timestart + $row->timelimit; - $datetime = userdate($time, get_string('trenddatetime', 'local_assessfreq')); - $content = \html_writer::span($datetime, 'local-assessfreq-disabled'); - } else { - $datetime = userdate($row->timefinish, get_string('trenddatetime', 'local_assessfreq')); - $content = \html_writer::span($datetime); - } - - return $content; - } - - /** - * Get content for state column. - * Displays the users state in the quiz. - * - * @param \stdClass $row - * @return string html used to display the field. - */ - public function col_state($row) { - if ($row->state == 'notloggedin') { - $color = 'background: ' . get_config('local_assessfreq', 'notloggedincolor'); - } else if ($row->state == 'loggedin') { - $color = 'background: ' . get_config('local_assessfreq', 'loggedincolor'); - } else if ($row->state == 'inprogress') { - $color = 'background: ' . get_config('local_assessfreq', 'inprogresscolor'); - } else if ($row->state == 'uploadpending') { - $color = 'background: ' . get_config('local_assessfreq', 'inprogresscolor'); - } else if ($row->state == 'finished') { - $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); - } else if ($row->state == 'abandoned') { - $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); - } else if ($row->state == 'overdue') { - $color = 'background: ' . get_config('local_assessfreq', 'finishedcolor'); - } - - $content = \html_writer::span('', 'local-assessfreq-status-icon', array('style' => $color)); - $content .= get_string($row->state, 'local_assessfreq'); - - return $content; - } - /** * Get content for actions column. * Displays the actions for the user. @@ -335,58 +251,15 @@ public function col_actions($row) { $manage = ''; $icon = $OUTPUT->render(new \pix_icon('i/duration', '')); - $manage .= \html_writer::link('#', $icon, array( + $manage .= \html_writer::link('#', $icon, [ 'class' => 'action-icon override', 'id' => 'tool-assessfreq-override-' . $row->id . '-' . $row->quiz, 'data-toggle' => 'tooltip', 'data-placement' => 'top', - 'title' => get_string('useroverride', 'local_assessfreq') - )); - - if ($row->state == 'finished' - || $row->state == 'inprogress' - || $row->state == 'uploadpending' - || $row->state == 'abandoned' - || $row->state == 'overdue') { - $classes = 'action-icon'; - $attempturl = new \moodle_url('/mod/quiz/review.php', array('attempt' => $row->attemptid)); - $attributes = array( - 'class' => $classes, - 'id' => 'tool-assessfreq-attempt-' . $row->id, - 'data-toggle' => 'tooltip', - 'data-placement' => 'top', - 'title' => get_string('userattempt', 'local_assessfreq') - ); - } else { - $classes = 'action-icon disabled'; - $attempturl = '#'; - $attributes = array( - 'class' => $classes, - 'id' => 'tool-assessfreq-attempt-' . $row->id, - ); - } - $icon = $OUTPUT->render(new \pix_icon('i/search', '')); - $manage .= \html_writer::link($attempturl, $icon, $attributes); - - $profileurl = new \moodle_url('/user/profile.php', array('id' => $row->id)); - $icon = $OUTPUT->render(new \pix_icon('i/completion_self', '')); - $manage .= \html_writer::link($profileurl, $icon, array( - 'class' => 'action-icon', - 'id' => 'tool-assessfreq-profile-' . $row->id, - 'data-toggle' => 'tooltip', - 'data-placement' => 'top', - 'title' => get_string('userprofile', 'local_assessfreq') - )); - - $logurl = new \moodle_url('/report/log/user.php', array('id' => $row->id, 'course' => 1, 'mode' => 'all')); - $icon = $OUTPUT->render(new \pix_icon('i/report', '')); - $manage .= \html_writer::link($logurl, $icon, array( - 'class' => 'action-icon', - 'id' => 'tool-assessfreq-log-' . $row->id, - 'data-toggle' => 'tooltip', - 'data-placement' => 'top', - 'title' => get_string('userlogs', 'local_assessfreq') - )); + 'title' => get_string('useroverride', 'local_assessfreq'), + ]); + + $manage .= $this->get_common_column_actions($row); return $manage; } @@ -397,9 +270,9 @@ public function col_actions($row) { * @param array $quizzes Array of quizzes to sort. * @return array $quizzes the sorted quizzes. */ - public function sort_quizzes(array $quizzes):array { + public function sort_quizzes(array $quizzes): array { // Comparisons are performed according to PHP's usual type comparison rules. - uasort($quizzes, function($a, $b) { + uasort($quizzes, function ($a, $b) { $sort = $this->get_sql_sort(); $sortobj = explode(' ', $sort); @@ -423,7 +296,6 @@ public function sort_quizzes(array $quizzes):array { return $b->{$sorton} <=> $a->{$sorton}; } } - }); return $quizzes; @@ -452,8 +324,8 @@ public function query_db($pagesize, $useinitialsbar = false) { $allquizzes = $quiz->get_quiz_summaries($this->now); $inprogressquizzes = $allquizzes['inprogress']; - $upcommingquizzes = array(); - $finishedquizzes = array(); + $upcommingquizzes = []; + $finishedquizzes = []; foreach ($allquizzes['upcomming'] as $upcomming) { foreach ($upcomming as $quizobj) { @@ -469,12 +341,12 @@ public function query_db($pagesize, $useinitialsbar = false) { $quizzes = array_merge($inprogressquizzes, $upcommingquizzes, $finishedquizzes); - $allrecords = array(); + $allrecords = []; foreach ($quizzes as $quizobj) { $context = $quiz->get_quiz_context($quizobj->assessid); - list($joins, $wheres, $params) = $frequency->generate_enrolled_wheres_joins_params($context, $capabilities); + [$joins, $wheres, $params] = $frequency->generate_enrolled_wheres_joins_params($context, $capabilities); $attemptsql = 'SELECT qa_a.userid, qa_a.state, qa_a.quiz, qa_a.id as attemptid, qa_a.timestart as timestart, qa_a.timefinish as timefinish FROM {quiz_attempts} qa_a @@ -501,40 +373,52 @@ public function query_db($pagesize, $useinitialsbar = false) { // If a quiz has overrides, get only students that are in the window time. if ($quizobj->isoverride) { - $userids = array(); + $userids = []; foreach ($quizobj->overrides as $override) { $userids[] = $override->userid; } - list($insql, $inparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'usr'); + [$insql, $inparams] = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'usr'); $finaljoin->wheres = $finaljoin->wheres . " AND u.id " . $insql; $params = array_merge($params, $inparams); - } $sql = "SELECT u.*, - COALESCE(qo.timeopen, $quizobj->timestampopen) AS timeopen, - COALESCE(qo.timeclose, $quizobj->timestampclose) AS timeclose, - COALESCE(qo.timelimit, $quizobj->timestamplimit) AS timelimit, - COALESCE(qa.state, (CASE - WHEN us.userid > 0 THEN 'loggedin' - ELSE 'notloggedin' - END)) AS state, + qo.timeopen AS timeopen, + qo.timeclose AS timeclose, + qo.timelimit AS timelimit, + COALESCE( + qa.state, + ( + CASE + WHEN us.userid > 0 THEN 'loggedin' + ELSE 'notloggedin' + END + ) + ) AS state, qa.attemptid, qa.timestart, - qa.timefinish, - $quizobj->assessid AS quiz, - $context->instanceid as quizinstance, - $quizobj->timestampopen AS quiztimeopen, - $quizobj->timestampclose AS quiztimeclose, - $quizobj->timestamplimit AS quiztimelimit, - '$quizobj->name' AS quizname + qa.timefinish FROM {user} u $finaljoin->joins WHERE $finaljoin->wheres"; - $records = $DB->get_records_sql($sql, $params); - $allrecords = array_merge($allrecords, $records); + $records = $DB->get_records_sql($sql, $params); + $quizdata = [ + 'quiz' => $quizobj->assessid, + 'quizinstance' => $context->instanceid, + 'quiztimeopen' => $quizobj->timestampopen, + 'quiztimeclose' => $quizobj->timestampclose, + 'quiztimelimit' => $quizobj->timestamplimit, + 'quizname' => $quizobj->name, + ]; + foreach ($records as &$record) { + $record->timeopen ??= $quizobj->timestampopen; + $record->timeclose ??= $quizobj->timestampclose; + $record->timelimit ??= $quizobj->timestampopen; + $record = (object)array_merge((array)$record, $quizdata); + } + $allrecords = array_merge($allrecords, $records); } if (!empty($this->get_sql_sort())) { @@ -542,7 +426,7 @@ public function query_db($pagesize, $useinitialsbar = false) { } $pagesize = get_user_preferences('local_assessfreq_student_search_table_rows_preference', 20); - $data = array(); + $data = []; $offset = $this->currpage * $pagesize; $offsetcount = 0; $recordcount = 0; @@ -553,14 +437,13 @@ public function query_db($pagesize, $useinitialsbar = false) { // Because we are using COALESCE and CASE for state we can't use SQL WHERE so we need to filter in PHP land. // Also because we need to do some filtering in PHP land, we'll do it all here. $searchcount = -1; - $searchfields = array_merge($this->extrafields, array('firstname', 'lastname', 'state', 'quiz')); + $searchfields = array_merge($this->extrafields, ['firstname', 'lastname', 'state', 'quiz']); foreach ($searchfields as $searchfield) { if (stripos($record->{$searchfield}, $this->search) !== false) { $searchcount++; } } - } if ($searchcount > -1 && $offsetcount >= $offset && $recordcount < $pagesize) { @@ -572,9 +455,8 @@ public function query_db($pagesize, $useinitialsbar = false) { } if ($searchcount > -1) { - $offsetcount ++; + $offsetcount++; } - } $this->pagesize($pagesize, $offsetcount); diff --git a/classes/output/upcomming_quizzes.php b/classes/output/upcomming_quizzes.php index f07da54f..d8925917 100644 --- a/classes/output/upcomming_quizzes.php +++ b/classes/output/upcomming_quizzes.php @@ -26,8 +26,6 @@ use local_assessfreq\quiz; -defined('MOODLE_INTERNAL') || die; - /** * Renderable for upcomming quizzes card. * @@ -36,7 +34,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class upcomming_quizzes { - /** * Generate the markup for the upcomming quizzes chart, * used in the in progress quizzes dashboard. @@ -50,14 +47,14 @@ public function get_upcomming_quizzes_chart(int $now): array { $quiz = new quiz(); $quizzes = $quiz->get_quiz_summaries($now); - $labels = array(); + $labels = []; $quizseriestitle = get_string('quizzes', 'local_assessfreq'); $participantseries = get_string('students', 'local_assessfreq'); - $result = array(); + $result = []; $result['hasdata'] = true; - $quizseriesdata = array(); - $participantseriesdata = array(); + $quizseriesdata = []; + $participantseriesdata = []; foreach ($quizzes['upcomming'] as $timestamp => $upcomming) { $quizcount = 0; diff --git a/classes/privacy/provider.php b/classes/privacy/provider.php index 16b44b77..3d44b2cd 100644 --- a/classes/privacy/provider.php +++ b/classes/privacy/provider.php @@ -24,8 +24,6 @@ namespace local_assessfreq\privacy; -defined('MOODLE_INTERNAL') || die(); - use core_privacy\local\metadata\collection; use core_privacy\local\request\contextlist; use core_privacy\local\request\approved_contextlist; @@ -40,17 +38,14 @@ * @copyright 2020 Matt Porritt <mattp@catalyst-au.net> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class provider implements -\core_privacy\local\metadata\provider, -\core_privacy\local\request\data_provider { - +class provider implements \core_privacy\local\request\data_provider, \core_privacy\local\metadata\provider { /** * Returns metadata about this plugin's privacy policy. * * @param collection $collection The initialised collection to add items to. * @return collection A listing of user data stored through this system. */ - public static function get_metadata(collection $collection) : collection { + public static function get_metadata(collection $collection): collection { $collection->add_database_table( 'local_assessfreq_user', [ @@ -59,7 +54,7 @@ public static function get_metadata(collection $collection) : collection { 'eventid' => 'privacy:metadata:local_assessfreq_user:eventid', ], 'privacy:metadata:local_assessfreq_user' - ); + ); $collection->add_database_table( 'local_assessfreq_conf_user', [ @@ -68,7 +63,7 @@ public static function get_metadata(collection $collection) : collection { 'conflictid' => 'privacy:metadata:local_assessfreq_conf_user:conflictid', ], 'privacy:metadata:local_assessfreq_conf_user' - ); + ); return $collection; } @@ -79,7 +74,7 @@ public static function get_metadata(collection $collection) : collection { * @param int $userid the userid to search. * @return contextlist the contexts in which data is contained. */ - public static function get_contexts_for_userid(int $userid) : contextlist { + public static function get_contexts_for_userid(int $userid): contextlist { $contextlist = new \core_privacy\local\request\contextlist(); $contextlist->add_user_context($userid); $contextlist->add_system_context(); @@ -98,12 +93,12 @@ public static function get_users_in_context(userlist $userlist) { $sql = " SELECT * FROM {local_assessfreq_user}"; - $userlist->add_from_sql('userid', $sql, array()); + $userlist->add_from_sql('userid', $sql, []); $sql = " SELECT * FROM {local_assessfreq_conf_user}"; - $userlist->add_from_sql('userid', $sql, array()); + $userlist->add_from_sql('userid', $sql, []); } } @@ -116,14 +111,12 @@ public static function export_user_data(approved_contextlist $contextlist) { global $DB; $userid = $contextlist->get_user()->id; foreach ($contextlist as $context) { - // If not in system context, exit loop. if ($context->contextlevel == CONTEXT_SYSTEM) { - - $parentclass = array(); + $parentclass = []; // Get records for user ID. - $rows = $DB->get_records('local_assessfreq_user', array('userid' => $userid)); + $rows = $DB->get_records('local_assessfreq_user', ['userid' => $userid]); if (count($rows) > 0) { $i = 0; @@ -134,7 +127,7 @@ public static function export_user_data(approved_contextlist $contextlist) { } } - $rows = $DB->get_records('local_assessfreq_conf_user', array('userid' => $userid)); + $rows = $DB->get_records('local_assessfreq_conf_user', ['userid' => $userid]); if (count($rows) > 0) { foreach ($rows as $row) { @@ -146,7 +139,8 @@ public static function export_user_data(approved_contextlist $contextlist) { writer::with_context($context)->export_data( [get_string('privacy:metadata:local_assessfreq', 'local_assessfreq')], - (object) $parentclass); + (object) $parentclass + ); } } } @@ -187,13 +181,13 @@ public static function delete_data_for_user(approved_contextlist $contextlist) { FROM {local_assessfreq_user} mfa WHERE mfa.userid = :userid"; - $DB->execute($sql, array('userid' => $userid)); + $DB->execute($sql, ['userid' => $userid]); $sql = "DELETE FROM {local_assessfreq_conf_user} mfa WHERE mfa.userid = :userid"; - $DB->execute($sql, array('userid' => $userid)); + $DB->execute($sql, ['userid' => $userid]); } } } @@ -207,7 +201,7 @@ public static function delete_data_for_users(approved_userlist $userlist) { $users = $userlist->get_users(); foreach ($users as $user) { // Create contextlist. - $contextlist = new approved_contextlist($user, 'local_assessfreq', array(CONTEXT_SYSTEM)); + $contextlist = new approved_contextlist($user, 'local_assessfreq', [CONTEXT_SYSTEM]); // Call delete data. self::delete_data_for_user($contextlist); } diff --git a/classes/quiz.php b/classes/quiz.php index 57405d4b..b85488a8 100644 --- a/classes/quiz.php +++ b/classes/quiz.php @@ -26,8 +26,6 @@ use mod_quiz\question\bank\qbank_helper; -defined('MOODLE_INTERNAL') || die(); - /** * Quiz data class. * @@ -38,7 +36,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class quiz { - /** * Ammount of time in hours for lookahead values. * Defaults to 12. @@ -75,7 +72,7 @@ class quiz { * @param int $hoursahead * @param int $hoursbehind */ - public function __construct(int $hoursahead=12, int $hoursbehind=1) { + public function __construct(int $hoursahead = 12, int $hoursbehind = 1) { $this->hoursahead = $hoursahead; $this->hoursbehind = $hoursbehind; } @@ -89,7 +86,7 @@ public function __construct(int $hoursahead=12, int $hoursbehind=1) { public function get_quiz_context(int $quizid): \context_module { global $DB; - $params = array('module' => 'quiz', 'quiz' => $quizid); + $params = ['module' => 'quiz', 'quiz' => $quizid]; $sql = 'SELECT cm.id FROM {course_modules} cm INNER JOIN {modules} m ON cm.module = m.id @@ -100,7 +97,6 @@ public function get_quiz_context(int $quizid): \context_module { $context = \context_module::instance($cmid); return $context; - } /** @@ -117,20 +113,19 @@ public function get_quiz_context(int $quizid): \context_module { private function get_quiz_override_info(int $quizid, \context_module $context): \stdClass { global $DB; - $capabilities = array('mod/quiz:attempt', 'mod/quiz:view'); + $capabilities = ['mod/quiz:attempt', 'mod/quiz:view']; $overrideinfo = new \stdClass(); - $users = array(); + $users = []; $start = 0; $end = 0; $sql = 'SELECT id, userid, COALESCE(timeopen, 0) AS timeopen, COALESCE(timeclose, 0) AS timeclose FROM {quiz_overrides} WHERE quiz = ?'; - $params = array($quizid); + $params = [$quizid]; $overrides = $DB->get_records_sql($sql, $params); foreach ($overrides as $override) { - if (!has_all_capabilities($capabilities, $context, $override->userid)) { continue; // Don't count users who can't access the quiz. } @@ -170,7 +165,7 @@ private function get_quiz_override_info(int $quizid, \context_module $context): private function get_quiz_questions(int $quizid): \stdClass { global $DB; $questions = new \stdClass(); - $types = array(); + $types = []; $questioncount = 0; $context = $this->get_quiz_context($quizid); @@ -181,9 +176,9 @@ private function get_quiz_questions(int $quizid): \stdClass { $questioncount++; } - $typeswithcounts = array(); + $typeswithcounts = []; foreach (array_count_values($types) as $type => $count) { - $typeswithcounts[] = array('type' => $type, 'count' => $count); + $typeswithcounts[] = ['type' => $type, 'count' => $count]; } $questions->types = $typeswithcounts; @@ -216,9 +211,9 @@ public function get_quiz_data(int $quizid): \stdClass { $quizdata = new \stdClass(); $context = $this->get_quiz_context($quizid); - $quizrecord = $DB->get_record('quiz', array('id' => $quizid), 'name, timeopen, timeclose, timelimit, course'); + $quizrecord = $DB->get_record('quiz', ['id' => $quizid], 'name, timeopen, timeclose, timelimit, course'); $course = get_course($quizrecord->course); - $courseurl = new \moodle_url('/course/view.php', array('id' => $quizrecord->course)); + $courseurl = new \moodle_url('/course/view.php', ['id' => $quizrecord->course]); $overrideinfo = $this->get_quiz_override_info($quizid, $context); $questions = $this->get_quiz_questions($quizid); @@ -263,13 +258,13 @@ public function get_quiz_data(int $quizid): \stdClass { } // Quiz result link. - $resultlink = new \moodle_url('/mod/quiz/report.php', array('id' => $context->instanceid, 'mode' => 'overview')); + $resultlink = new \moodle_url('/mod/quiz/report.php', ['id' => $context->instanceid, 'mode' => 'overview']); // Override link. - $overrridelink = new \moodle_url('/mod/quiz/overrides.php', array('cmid' => $context->instanceid, 'mode' => 'user')); + $overrridelink = new \moodle_url('/mod/quiz/overrides.php', ['cmid' => $context->instanceid, 'mode' => 'user']); // Participant link. - $participantlink = new \moodle_url('/user/index.php', array('id' => $quizrecord->course)); + $participantlink = new \moodle_url('/user/index.php', ['id' => $quizrecord->course]); // Dashboard link. - $dashboardlink = new \moodle_url('/local/assessfreq/dashboard_quiz.php', array('id' => $quizid)); + $dashboardlink = new \moodle_url('/local/assessfreq/dashboard_quiz.php', ['id' => $quizid]); $quizdata->name = format_string($quizrecord->name, true, ["context" => $context, "escape" => true]); $quizdata->timeopen = $timesopen; @@ -317,11 +312,11 @@ private function get_tracked_overrides(int $now, int $lookahead, int $lookbehind FROM {quiz_overrides} WHERE (timeopen > 0 AND timeopen < :starttime) AND (timeclose > :endtime OR timeclose > :now)'; - $params = array( + $params = [ 'starttime' => $starttime, 'endtime' => $endtime, - 'now' => $now - ); + 'now' => $now, + ]; $quizzes = $DB->get_records_sql($sql, $params); @@ -348,11 +343,11 @@ private function get_tracked_quizzes(int $now, int $lookahead, int $lookbehind): FROM {quiz} WHERE (timeopen > 0 AND timeopen < :starttime) AND (timeclose > :endtime OR timeclose > :now)'; - $params = array( + $params = [ 'starttime' => $starttime, 'endtime' => $endtime, - 'now' => $now - ); + 'now' => $now, + ]; $quizzes = $DB->get_records_sql($sql, $params); @@ -369,7 +364,7 @@ private function get_tracked_quizzes(int $now, int $lookahead, int $lookbehind): * @param int $lookbehind The number of seconds from the provided now value to look behind when getting quizzes. * @return array $quizzes The quizzes. */ - private function get_tracked_quizzes_with_overrides(int $now, int $lookahead=HOURSECS, int $lookbehind=HOURSECS): array { + private function get_tracked_quizzes_with_overrides(int $now, int $lookahead = HOURSECS, int $lookbehind = HOURSECS): array { global $DB; $quizzes = $this->get_tracked_quizzes($now, $lookahead, $lookbehind); @@ -380,9 +375,9 @@ private function get_tracked_quizzes_with_overrides(int $now, int $lookahead=HOU $sql = 'SELECT id, timeopen, timeclose, timelimit FROM {quiz} WHERE id = :id'; - $params = array( + $params = [ 'id' => $override->quiz, - ); + ]; $quizzesoverride = $DB->get_record_sql($sql, $params); @@ -416,10 +411,10 @@ public function get_inprogress_counts(int $now): array { // Get tracked quizzes. $trackedquizzes = $this->get_tracked_quizzes_with_overrides($now, 0, 0); - $counts = array( + $counts = [ 'assessments' => 0, 'participants' => 0, - ); + ]; foreach ($trackedquizzes as $quiz) { $counts['assessments']++; @@ -448,21 +443,21 @@ public function get_quiz_summaries(int $now): array { $trackedquizzes = $this->get_tracked_quizzes_with_overrides($now, $lookahead, $lookbehind); // Set up array to hold quizzes and data. - $quizzes = array( - 'finished' => array(), - 'inprogress' => array(), - 'upcomming' => array(), - ); + $quizzes = [ + 'finished' => [], + 'inprogress' => [], + 'upcomming' => [], + ]; // Itterate through the hours, processing in progress and upcomming quizzes. for ($hour = 0; $hour <= $this->hoursahead; $hour++) { $time = $now + (HOURSECS * $hour); if ($hour == 0) { - $quizzes['inprogress'] = array(); + $quizzes['inprogress'] = []; } - $quizzes['upcomming'][$time] = array(); + $quizzes['upcomming'][$time] = []; // Seperate out inprogress and upcomming quizzes, then get data for each quiz. foreach ($trackedquizzes as $quiz) { @@ -521,14 +516,13 @@ public function get_quiz_summaries(int $now): array { } } } - } // Iterate through the hours, processing finished quizzes. for ($hour = 1; $hour <= $this->hoursbehind; $hour++) { $time = $now - (HOURSECS * $hour); - $quizzes['finished'][$time] = array(); + $quizzes['finished'][$time] = []; // Get data for each finished quiz. foreach ($trackedquizzes as $quiz) { @@ -551,7 +545,6 @@ public function get_quiz_summaries(int $now): array { unset($trackedquizzes[$quiz->id]); } } - } return $quizzes; @@ -573,11 +566,11 @@ private function get_loggedin_users(array $userids): \stdClass { $loggedin = 0; // Count of logged in users. $loggedout = 0; // Count of not loggedin users. - $loggedinusers = array(); - $loggedoutusers = array(); + $loggedinusers = []; + $loggedoutusers = []; foreach ($userchunks as $userchunk) { - list($insql, $inparams) = $DB->get_in_or_equal($userchunk); + [$insql, $inparams] = $DB->get_in_or_equal($userchunk); $inparams[] = $timedout; $sql = "SELECT DISTINCT(userid) @@ -600,7 +593,6 @@ private function get_loggedin_users(array $userids): \stdClass { $usercounts->loggedoutusers = $loggedoutusers; return $usercounts; - } /** @@ -614,8 +606,8 @@ private function get_quiz_attempts(int $quizid): \stdClass { $inprogress = 0; $finished = 0; - $inprogressusers = array(); - $finishedusers = array(); + $inprogressusers = []; + $finishedusers = []; $sql = 'SELECT userid, state FROM {quiz_attempts} qa @@ -627,7 +619,7 @@ private function get_quiz_attempts(int $quizid): \stdClass { AS qb ON qa.id = qb.id'; - $params = array($quizid); + $params = [$quizid]; $usersattempts = $DB->get_records_sql($sql, $params); @@ -648,7 +640,6 @@ private function get_quiz_attempts(int $quizid): \stdClass { $attemptcounts->finishedusers = $finishedusers; return $attemptcounts; - } /** @@ -730,7 +721,7 @@ public function process_quiz_tracking(int $now): int { public function get_quiz_tracking(int $quizid): array { global $DB; - $tracking = $DB->get_records('local_assessfreq_trend', array('assessid' => $quizid), 'timecreated ASC'); + $tracking = $DB->get_records('local_assessfreq_trend', ['assessid' => $quizid], 'timecreated ASC'); return $tracking; } @@ -745,8 +736,8 @@ public function get_quiz_tracking(int $quizid): array { * @return array $result Array containing list of filtered quizzes and total of how many quizzes matched the filter. */ public function filter_quizzes(array $quizzes, string $search, int $page, int $pagesize): array { - $filtered = array(); - $searchfields = array('name', 'coursefullname'); + $filtered = []; + $searchfields = ['name', 'coursefullname']; $offset = $page * $pagesize; $offsetcount = 0; $recordcount = 0; @@ -771,11 +762,11 @@ public function filter_quizzes(array $quizzes, string $search, int $page, int $p } if ($searchcount > -1) { - $offsetcount ++; + $offsetcount++; } } - $result = array($filtered, $offsetcount); + $result = [$filtered, $offsetcount]; return $result; } diff --git a/classes/task/data_process.php b/classes/task/data_process.php index a6981331..73eb05ab 100644 --- a/classes/task/data_process.php +++ b/classes/task/data_process.php @@ -25,8 +25,6 @@ use core\task\scheduled_task; -defined('MOODLE_INTERNAL') || die(); - /** * A scheduled task to generate data used in plugin reports. * @@ -35,7 +33,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class data_process extends scheduled_task { - /** * Get a descriptive name for this task (shown to admins). * @@ -67,10 +64,10 @@ public function execute() { $actionstart = time(); $frequency->delete_events($now); // Delete event records greaer than now. $actionduration = time() - $actionstart; - $event = \local_assessfreq\event\event_processed::create(array( + $event = \local_assessfreq\event\event_processed::create([ 'context' => $context, - 'other' => array('action' => 'delete', 'duration' => $actionduration) - )); + 'other' => ['action' => 'delete', 'duration' => $actionduration], + ]); $event->trigger(); mtrace('local_assessfreq: Deleting old event data finished in: ' . $actionduration . ' seconds'); @@ -78,10 +75,10 @@ public function execute() { $actionstart = time(); $frequency->process_site_events($now); // Process records in the future. $actionduration = time() - $actionstart; - $event = \local_assessfreq\event\event_processed::create(array( + $event = \local_assessfreq\event\event_processed::create([ 'context' => $context, - 'other' => array('action' => 'site', 'duration' => $actionduration) - )); + 'other' => ['action' => 'site', 'duration' => $actionduration], + ]); $event->trigger(); mtrace('local_assessfreq: Processing site events finished in: ' . $actionduration . ' seconds'); @@ -89,10 +86,10 @@ public function execute() { $actionstart = time(); $frequency->process_user_events($now); // Process user events. $actionduration = time() - $actionstart; - $event = \local_assessfreq\event\event_processed::create(array( + $event = \local_assessfreq\event\event_processed::create([ 'context' => $context, - 'other' => array('action' => 'user', 'duration' => $actionduration) - )); + 'other' => ['action' => 'user', 'duration' => $actionduration], + ]); $event->trigger(); mtrace('local_assessfreq: Processing user events finished in: ' . $actionduration . ' seconds'); } diff --git a/classes/task/history_process.php b/classes/task/history_process.php index 65a7724f..5cbcb513 100644 --- a/classes/task/history_process.php +++ b/classes/task/history_process.php @@ -25,8 +25,6 @@ use core\task\adhoc_task; -defined('MOODLE_INTERNAL') || die(); - /** * Adhoc task to process historical data used in plugin. * @@ -35,7 +33,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class history_process extends adhoc_task { - /** * Do the job. * Throw exceptions on errors (the job will be retried). @@ -57,10 +54,10 @@ public function execute() { $actionstart = time(); $frequency->delete_events(0); // Delete ALL event records. $actionduration = time() - $actionstart; - $event = \local_assessfreq\event\event_processed::create(array( + $event = \local_assessfreq\event\event_processed::create([ 'context' => $context, - 'other' => array('action' => 'delete', 'duration' => $actionduration) - )); + 'other' => ['action' => 'delete', 'duration' => $actionduration], + ]); $event->trigger(); mtrace('local_assessfreq: Deleting old event data finished in: ' . $actionduration . ' seconds'); @@ -68,10 +65,10 @@ public function execute() { $actionstart = time(); $frequency->process_site_events(1); // Process ALL records. $actionduration = time() - $actionstart; - $event = \local_assessfreq\event\event_processed::create(array( + $event = \local_assessfreq\event\event_processed::create([ 'context' => $context, - 'other' => array('action' => 'site', 'duration' => $actionduration) - )); + 'other' => ['action' => 'site', 'duration' => $actionduration], + ]); $event->trigger(); mtrace('local_assessfreq: Processing site events finished in: ' . $actionduration . ' seconds'); @@ -79,10 +76,10 @@ public function execute() { $actionstart = time(); $frequency->process_user_events(1); // Process ALL user events. $actionduration = time() - $actionstart; - $event = \local_assessfreq\event\event_processed::create(array( + $event = \local_assessfreq\event\event_processed::create([ 'context' => $context, - 'other' => array('action' => 'user', 'duration' => $actionduration) - )); + 'other' => ['action' => 'user', 'duration' => $actionduration], + ]); $event->trigger(); mtrace('local_assessfreq: Processing user events finished in: ' . $actionduration . ' seconds'); } diff --git a/classes/task/quiz_tracking.php b/classes/task/quiz_tracking.php index 15e2625a..0c7a21f3 100644 --- a/classes/task/quiz_tracking.php +++ b/classes/task/quiz_tracking.php @@ -25,8 +25,6 @@ use core\task\scheduled_task; -defined('MOODLE_INTERNAL') || die(); - /** * A scheduled task to track the process of quizzes in the system. * @@ -35,7 +33,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class quiz_tracking extends scheduled_task { - /** * Get a descriptive name for this task (shown to admins). * diff --git a/classes/utils.php b/classes/utils.php index d11b6005..11d096ae 100644 --- a/classes/utils.php +++ b/classes/utils.php @@ -24,8 +24,6 @@ namespace local_assessfreq; -defined('MOODLE_INTERNAL') || die(); - /** * Utils class. * @@ -44,9 +42,9 @@ class utils { * @param string $direction The direction to sort in. * @return array $inputarray the sorted arrays. */ - public static function sort(array $inputarray, string $sorton, string $direction):array { + public static function sort(array $inputarray, string $sorton, string $direction): array { - uasort($inputarray, function($a, $b) use ($direction, $sorton) { + uasort($inputarray, function ($a, $b) use ($direction, $sorton) { if ($direction == 'asc') { if (gettype($a->{$sorton}) == 'string') { return strcasecmp($a->{$sorton}, $b->{$sorton}); @@ -64,7 +62,6 @@ public static function sort(array $inputarray, string $sorton, string $direction return $b->{$sorton} <=> $a->{$sorton}; } } - }); return $inputarray; @@ -77,11 +74,11 @@ public static function sort(array $inputarray, string $sorton, string $direction * @param array $sorton Associative array to sort by in the format field => direction. * @return array $inputarray the sorted array. */ - public static function multi_sort(array $inputarray, array $sorton):array { + public static function multi_sort(array $inputarray, array $sorton): array { // Convert to an array of arrays if required. $element = reset($inputarray); if (gettype($element) == 'object') { - $makearray = array(); + $makearray = []; foreach ($inputarray as $object) { $makearray[] = (array)$object; } @@ -89,7 +86,7 @@ public static function multi_sort(array $inputarray, array $sorton):array { } // Take sort on array and format it for passing to array_multisort. - $sortvariables = array(); + $sortvariables = []; foreach ($sorton as $sort => $direction) { $sortvariables[] = array_column($inputarray, $sort); @@ -109,7 +106,7 @@ public static function multi_sort(array $inputarray, array $sorton):array { // Convert back to an array of objects if needed. if (gettype($element) == 'object') { - $makeobject = array(); + $makeobject = []; foreach ($inputarray as $object) { $makeobject[] = (object)$object; } diff --git a/dashboard_assessment.php b/dashboard_assessment.php index 8fc3d19b..7c211437 100644 --- a/dashboard_assessment.php +++ b/dashboard_assessment.php @@ -27,8 +27,13 @@ $baseurl = $CFG->wwwroot . "/local/assessfreq/dashboard_assessment.php"; // Calls require_login and performs permissions checks for admin pages. -admin_externalpage_setup('local_assessfreq_assessment', '', null, '', - array('pagelayout' => 'admin')); +admin_externalpage_setup( + 'local_assessfreq_assessment', + '', + null, + '', + ['pagelayout' => 'admin'] +); $title = get_string('dashboard:assessment', 'local_assessfreq'); $url = new moodle_url($baseurl); @@ -38,7 +43,7 @@ $PAGE->set_context($context); $PAGE->set_title($title); $PAGE->set_heading($title); -$PAGE->requires->js_call_amd('local_assessfreq/dashboard_assessment', 'init', array($context->id)); +$PAGE->requires->js_call_amd('local_assessfreq/dashboard_assessment', 'init', [$context->id]); $output = $PAGE->get_renderer('local_assessfreq'); diff --git a/dashboard_quiz.php b/dashboard_quiz.php index 652e40b8..66a62d2a 100644 --- a/dashboard_quiz.php +++ b/dashboard_quiz.php @@ -29,8 +29,13 @@ $baseurl = $CFG->wwwroot . "/local/assessfreq/dashboard_quiz.php"; // Calls require_login and performs permissions checks for admin pages. -admin_externalpage_setup('local_assessfreq_quiz', '', null, '', - array('pagelayout' => 'admin')); +admin_externalpage_setup( + 'local_assessfreq_quiz', + '', + null, + '', + ['pagelayout' => 'admin'] +); $title = get_string('dashboard:quiz', 'local_assessfreq'); $url = new moodle_url($baseurl); @@ -40,7 +45,7 @@ $PAGE->set_context($context); $PAGE->set_title($title); $PAGE->set_heading($title); -$PAGE->requires->js_call_amd('local_assessfreq/dashboard_quiz', 'init', array($context->id, $quizid)); +$PAGE->requires->js_call_amd('local_assessfreq/dashboard_quiz', 'init', [$context->id, $quizid]); $output = $PAGE->get_renderer('local_assessfreq'); diff --git a/dashboard_quiz_inprogress.php b/dashboard_quiz_inprogress.php index b2255b79..18cdacd4 100644 --- a/dashboard_quiz_inprogress.php +++ b/dashboard_quiz_inprogress.php @@ -27,8 +27,13 @@ $baseurl = $CFG->wwwroot . "/local/assessfreq/dashboard_quiz_inprogress.php"; // Calls require_login and performs permissions checks for admin pages. -admin_externalpage_setup('local_assessfreq_quiz', '', null, '', - array('pagelayout' => 'admin')); +admin_externalpage_setup( + 'local_assessfreq_quiz', + '', + null, + '', + ['pagelayout' => 'admin'] +); $title = get_string('dashboard:quiz_inprogress', 'local_assessfreq'); $url = new moodle_url($baseurl); @@ -38,7 +43,7 @@ $PAGE->set_context($context); $PAGE->set_title($title); $PAGE->set_heading($title); -$PAGE->requires->js_call_amd('local_assessfreq/dashboard_quiz_inprogress', 'init', array($context->id)); +$PAGE->requires->js_call_amd('local_assessfreq/dashboard_quiz_inprogress', 'init', [$context->id]); $output = $PAGE->get_renderer('local_assessfreq'); diff --git a/db/caches.php b/db/caches.php index b5ce897f..84144f59 100644 --- a/db/caches.php +++ b/db/caches.php @@ -30,55 +30,54 @@ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'courseevents' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'userevents' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'usereventsallfrequencyarray' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'eventsduemonth' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'yearevents' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'eventsdueactivity' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'monthlyuser' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], 'eventusers' => [ 'mode' => cache_store::MODE_APPLICATION, 'staticacceleration' => true, 'simplekeys' => true, - 'simpledata' => false + 'simpledata' => false, ], ]; - diff --git a/db/install.php b/db/install.php index 3e59e451..a81c96ab 100644 --- a/db/install.php +++ b/db/install.php @@ -22,8 +22,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -defined('MOODLE_INTERNAL') || die(); - /** * Generate ad-hoc task on install. */ diff --git a/db/services.php b/db/services.php index ab1fdeaa..afac4f83 100644 --- a/db/services.php +++ b/db/services.php @@ -25,96 +25,96 @@ defined('MOODLE_INTERNAL') || die(); // Define the web service functions to install. -$functions = array( - 'local_assessfreq_get_frequency' => array( +$functions = [ + 'local_assessfreq_get_frequency' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_frequency', 'classpath' => '', 'description' => 'Returns event frequency map.', 'type' => 'read', - 'ajax' => true - ), - 'local_assessfreq_get_heat_colors' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_heat_colors' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_heat_colors', 'classpath' => '', 'description' => 'Returns event heat map colors.', 'type' => 'read', 'loginrequired' => false, - 'ajax' => true - ), - 'local_assessfreq_get_process_modules' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_process_modules' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_process_modules', 'classpath' => '', 'description' => 'Returns modules we are processing .', 'type' => 'read', 'loginrequired' => false, - 'ajax' => true - ), - 'local_assessfreq_get_day_events' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_day_events' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_day_events', 'classpath' => '', 'description' => 'Gets day event info for use in heatmap.', 'type' => 'read', - 'ajax' => true - ), - 'local_assessfreq_get_courses' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_courses' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_courses', 'classpath' => '', 'description' => 'Gets courses.', 'type' => 'read', - 'ajax' => true - ), - 'local_assessfreq_get_quizzes' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_quizzes' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_quizzes', 'classpath' => '', 'description' => 'Gets quizzes.', 'type' => 'read', - 'ajax' => true - ), - 'local_assessfreq_get_quiz_data' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_quiz_data' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_quiz_data', 'classpath' => '', 'description' => 'Gets quiz data.', 'type' => 'read', - 'ajax' => true - ), - 'local_assessfreq_set_table_preference' => array( + 'ajax' => true, + ], + 'local_assessfreq_set_table_preference' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'set_table_preference', 'classpath' => '', 'description' => 'Sets a table preference.', 'type' => 'write', - 'ajax' => true - ), - 'local_assessfreq_process_override_form' => array( + 'ajax' => true, + ], + 'local_assessfreq_process_override_form' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'process_override_form', 'classpath' => '', 'description' => 'Process the override form.', 'type' => 'write', - 'ajax' => true - ), - 'local_assessfreq_get_system_timezone' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_system_timezone' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_system_timezone', 'classpath' => '', 'description' => 'Returns system (not user) timezone.', 'type' => 'read', 'loginrequired' => false, - 'ajax' => true - ), - 'local_assessfreq_get_inprogress_counts' => array( + 'ajax' => true, + ], + 'local_assessfreq_get_inprogress_counts' => [ 'classname' => 'local_assessfreq_external', 'methodname' => 'get_inprogress_counts', 'classpath' => '', 'description' => 'Get counts for inprogress assessments.', 'type' => 'read', - 'ajax' => true - ), -); + 'ajax' => true, + ], +]; diff --git a/db/tasks.php b/db/tasks.php index f571dc55..6e9893c3 100644 --- a/db/tasks.php +++ b/db/tasks.php @@ -27,23 +27,23 @@ /* List of handlers */ -$tasks = array( - array( +$tasks = [ + [ 'classname' => 'local_assessfreq\task\data_process', 'blocking' => 0, 'minute' => '*/15', 'hour' => '*', 'day' => '*', 'dayofweek' => '*', - 'month' => '*' - ), - array( + 'month' => '*', + ], + [ 'classname' => 'local_assessfreq\task\quiz_tracking', 'blocking' => 0, 'minute' => '*', 'hour' => '*', 'day' => '*', 'dayofweek' => '*', - 'month' => '*' - ), -); + 'month' => '*', + ], +]; diff --git a/download.php b/download.php index e02cd2da..d51d6fd3 100644 --- a/download.php +++ b/download.php @@ -35,13 +35,13 @@ require_capability('moodle/site:config', $context); $dataformat = 'csv'; -$fields = array( +$fields = [ get_string('quiztimeopen', 'local_assessfreq'), get_string('duedate', 'local_assessfreq'), get_string('activity', 'local_assessfreq'), get_string('title', 'local_assessfreq'), - get_string('url', 'local_assessfreq') -); + get_string('url', 'local_assessfreq'), +]; if ($metric == 'students') { $extrafields = \core_user\fields::get_identity_fields($context, false); diff --git a/history.php b/history.php index beb7e593..d5f241a4 100644 --- a/history.php +++ b/history.php @@ -37,21 +37,21 @@ echo $OUTPUT->heading(get_string('clearhistory', 'local_assessfreq')); // Page content. (This feels like the lazy way to do things). -$url = new \moodle_url('/local/assessfreq/history.php', array('action' => 'deleteall')); +$url = new \moodle_url('/local/assessfreq/history.php', ['action' => 'deleteall']); if ($action === null) { echo $OUTPUT->box_start(); echo $OUTPUT->container(get_string('reprocessall_desc', 'local_assessfreq')); echo $OUTPUT->single_button($url, get_string('reprocessall', 'local_assessfreq'), 'get'); echo $OUTPUT->box_end(); - } else if ($action == 'deleteall') { - $actionurl = new moodle_url('/local/assessfreq/history.php', array('action' => 'confirmed')); + $actionurl = new moodle_url('/local/assessfreq/history.php', ['action' => 'confirmed']); $cancelurl = new moodle_url('/local/assessfreq/history.php'); - echo $OUTPUT->confirm(get_string('confirmreprocess', 'local_assessfreq'), + echo $OUTPUT->confirm( + get_string('confirmreprocess', 'local_assessfreq'), new single_button($actionurl, get_string('continue'), 'post', single_button::BUTTON_SECONDARY), - new single_button($cancelurl, get_string('cancel'), 'get')); - + new single_button($cancelurl, get_string('cancel'), 'get') + ); } else if ($action == 'confirmed') { // Create an adhoc task that will process all historical event data. $task = new \local_assessfreq\task\history_process(); diff --git a/lib.php b/lib.php index efd6f297..1258ad3a 100644 --- a/lib.php +++ b/lib.php @@ -22,9 +22,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -defined('MOODLE_INTERNAL') || die(); - - /** * Returns the name of the user preferences as well as the details this plugin uses. * @@ -32,83 +29,83 @@ */ function local_assessfreq_user_preferences() { - $preferences['local_assessfreq_overview_year_preference'] = array( + $preferences['local_assessfreq_overview_year_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => date('Y'), - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_heatmap_year_preference'] = array( + $preferences['local_assessfreq_heatmap_year_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => date('Y'), - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_heatmap_metric_preference'] = array( + $preferences['local_assessfreq_heatmap_metric_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 'assess', - 'type' => PARAM_ALPHA - ); + 'type' => PARAM_ALPHA, + ]; - $preferences['local_assessfreq_heatmap_modules_preference'] = array( + $preferences['local_assessfreq_heatmap_modules_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => '[]', - 'type' => PARAM_RAW - ); + 'type' => PARAM_RAW, + ]; - $preferences['local_assessfreq_quiz_refresh_preference'] = array( + $preferences['local_assessfreq_quiz_refresh_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 60, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_quiz_table_rows_preference'] = array( + $preferences['local_assessfreq_quiz_table_rows_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 20, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_student_search_table_rows_preference'] = array( + $preferences['local_assessfreq_student_search_table_rows_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 20, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_student_search_table_hoursahead_preference'] = array( + $preferences['local_assessfreq_student_search_table_hoursahead_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 4, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_student_search_table_hoursbehind_preference'] = array( + $preferences['local_assessfreq_student_search_table_hoursbehind_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 1, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_quizzes_inprogress_table_hoursahead_preference'] = array( + $preferences['local_assessfreq_quizzes_inprogress_table_hoursahead_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 0, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_quizzes_inprogress_table_hoursbehind_preference'] = array( + $preferences['local_assessfreq_quizzes_inprogress_table_hoursbehind_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 0, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_quiz_table_inprogress_preference'] = array( + $preferences['local_assessfreq_quiz_table_inprogress_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 20, - 'type' => PARAM_INT - ); + 'type' => PARAM_INT, + ]; - $preferences['local_assessfreq_quiz_table_inprogress_sort_preference'] = array( + $preferences['local_assessfreq_quiz_table_inprogress_sort_preference'] = [ 'null' => NULL_NOT_ALLOWED, 'default' => 'name_asc', - 'type' => PARAM_ALPHAEXT - ); + 'type' => PARAM_ALPHAEXT, + ]; return $preferences; } @@ -120,11 +117,11 @@ function local_assessfreq_user_preferences() { * @return string $chartdata The generated chart. */ function local_assessfreq_output_fragment_get_chart($args): string { - $allowedcalls = array( + $allowedcalls = [ 'assess_by_month', 'assess_by_activity', - 'assess_by_month_student' - ); + 'assess_by_month_student', + ]; $context = $args['context']; has_capability('moodle/site:config', $context); @@ -151,10 +148,10 @@ function local_assessfreq_output_fragment_get_chart($args): string { * @return string $chartdata The generated chart. */ function local_assessfreq_output_fragment_get_quiz_chart($args): string { - $allowedcalls = array( + $allowedcalls = [ 'participant_summary', - 'participant_trend' - ); + 'participant_trend', + ]; $context = $args['context']; has_capability('moodle/site:config', $context); @@ -181,10 +178,10 @@ function local_assessfreq_output_fragment_get_quiz_chart($args): string { * @return string $chartdata The generated chart. */ function local_assessfreq_output_fragment_get_quiz_inprogress_chart($args): string { - $allowedcalls = array( + $allowedcalls = [ 'upcomming_quizzes', - 'all_participants_inprogress' - ); + 'all_participants_inprogress', + ]; $context = $args['context']; has_capability('moodle/site:config', $context); @@ -221,7 +218,7 @@ function local_assessfreq_output_fragment_new_base_form($args): string { $context = $args['context']; has_capability('moodle/site:config', $context); - $mform = new \local_assessfreq\form\quiz_search_form(null, null, 'post', '', array('class' => 'ignoredirty')); + $mform = new \local_assessfreq\form\quiz_search_form(null, null, 'post', '', ['class' => 'ignoredirty']); ob_start(); $mform->display(); @@ -320,7 +317,7 @@ function local_assessfreq_output_fragment_new_override_form($args): string { $serialiseddata = json_decode($args['jsonformdata'], true); - $formdata = array(); + $formdata = []; if (!empty($serialiseddata)) { parse_str($serialiseddata, $formdata); @@ -330,12 +327,12 @@ function local_assessfreq_output_fragment_new_override_form($args): string { $quizid = $args['quizid']; $quizdata = new \local_assessfreq\quiz(); $quizcontext = $quizdata->get_quiz_context($quizid); - $quiz = $DB->get_record('quiz', array('id' => $quizid), '*', MUST_EXIST); + $quiz = $DB->get_record('quiz', ['id' => $quizid], '*', MUST_EXIST); $cm = get_course_and_cm_from_cmid($quizcontext->instanceid, 'quiz')[1]; // Check if we have an existing override for this user. - $override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $args['userid'])); + $override = $DB->get_record('quiz_overrides', ['quiz' => $quiz->id, 'userid' => $args['userid']]); if ($override) { $data = clone $override; diff --git a/settings.php b/settings.php index 9d859f8a..9e88f695 100644 --- a/settings.php +++ b/settings.php @@ -35,36 +35,51 @@ $historysettings = new admin_externalpage( 'local_assessfreq_history', get_string('clearhistory', 'local_assessfreq'), - new moodle_url('/local/assessfreq/history.php')); + new moodle_url('/local/assessfreq/history.php') +); // New report category. $ADMIN->add('reports', new admin_category('local_assessfreq_reports', get_string('reports', 'local_assessfreq'))); // Assessment dashboard link. -$ADMIN->add('local_assessfreq_reports', new admin_externalpage('local_assessfreq_assessment', - get_string('dashboard:assessment', 'local_assessfreq'), "$CFG->wwwroot/local/assessfreq/dashboard_assessment.php")); +$ADMIN->add('local_assessfreq_reports', new admin_externalpage( + 'local_assessfreq_assessment', + get_string('dashboard:assessment', 'local_assessfreq'), + "$CFG->wwwroot/local/assessfreq/dashboard_assessment.php" +)); // Quiz dashboard link. -$ADMIN->add('local_assessfreq_reports', new admin_externalpage('local_assessfreq_quiz', - get_string('dashboard:quiz', 'local_assessfreq'), "$CFG->wwwroot/local/assessfreq/dashboard_quiz.php")); +$ADMIN->add('local_assessfreq_reports', new admin_externalpage( + 'local_assessfreq_quiz', + get_string('dashboard:quiz', 'local_assessfreq'), + "$CFG->wwwroot/local/assessfreq/dashboard_quiz.php" +)); // Quiz inprogress dashboard link. -$ADMIN->add('local_assessfreq_reports', new admin_externalpage('local_assessfreq_quiz_inprogress', - get_string('dashboard:quiz_inprogress', 'local_assessfreq'), "$CFG->wwwroot/local/assessfreq/dashboard_quiz_inprogress.php")); +$ADMIN->add('local_assessfreq_reports', new admin_externalpage( + 'local_assessfreq_quiz_inprogress', + get_string('dashboard:quiz_inprogress', 'local_assessfreq'), + "$CFG->wwwroot/local/assessfreq/dashboard_quiz_inprogress.php" +)); // Quiz student search link. -$ADMIN->add('local_assessfreq_reports', new admin_externalpage('local_assessfreq_student_search', - get_string('student_search', 'local_assessfreq'), "$CFG->wwwroot/local/assessfreq/student_search.php")); +$ADMIN->add('local_assessfreq_reports', new admin_externalpage( + 'local_assessfreq_student_search', + get_string('student_search', 'local_assessfreq'), + "$CFG->wwwroot/local/assessfreq/student_search.php" +)); // Module settings. -$sitesettings->add(new admin_setting_heading('local_assessfreq/moduleheading', +$sitesettings->add(new admin_setting_heading( + 'local_assessfreq/moduleheading', get_string('settings:moduleheading', 'local_assessfreq'), - get_string('settings:moduleheading_desc', 'local_assessfreq'))); + get_string('settings:moduleheading_desc', 'local_assessfreq') +)); $frequency = new \local_assessfreq\frequency(); $modules = $frequency->get_modules(); $enabledmodules = $frequency->get_enabled_modules(); -$modarray = array(); +$modarray = []; foreach ($modules as $module) { if ($enabledmodules[$module] == 1) { @@ -74,82 +89,124 @@ } } -$setting = new admin_setting_configmulticheckbox('local_assessfreq/modules', +$setting = new admin_setting_configmulticheckbox( + 'local_assessfreq/modules', get_string('settings:modules', 'local_assessfreq'), get_string('settings:modules_desc', 'local_assessfreq'), $modules, - $modarray); + $modarray +); $setting->set_updatedcallback('\local_assessfreq\frequency::purge_caches'); $sitesettings->add($setting); // Include disabled modules. -$setting = new admin_setting_configcheckbox('local_assessfreq/disabledmodules', +$setting = new admin_setting_configcheckbox( + 'local_assessfreq/disabledmodules', get_string('settings:disabledmodules', 'local_assessfreq'), get_string('settings:disabledmodules_desc', 'local_assessfreq'), - 1); + 1 +); $setting->set_updatedcallback('\local_assessfreq\frequency::purge_caches'); $sitesettings->add($setting); // Include hidden courses. -$setting = new admin_setting_configcheckbox('local_assessfreq/hiddencourses', +$setting = new admin_setting_configcheckbox( + 'local_assessfreq/hiddencourses', get_string('settings:hiddencourses', 'local_assessfreq'), get_string('settings:hiddencourses_desc', 'local_assessfreq'), - 0); + 0 +); $setting->set_updatedcallback('\local_assessfreq\frequency::purge_caches'); $sitesettings->add($setting); // Heat settings. -$sitesettings->add(new admin_setting_heading('local_assessfreq/heatheading', +$sitesettings->add(new admin_setting_heading( + 'local_assessfreq/heatheading', get_string('settings:heatheading', 'local_assessfreq'), - get_string('settings:heatheading_desc', 'local_assessfreq'))); + get_string('settings:heatheading_desc', 'local_assessfreq') +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/heat1', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/heat1', get_string('settings:heat1', 'local_assessfreq'), - get_string('settings:heat1_desc', 'local_assessfreq'), '#FDF9CD')); + get_string('settings:heat1_desc', 'local_assessfreq'), + '#FDF9CD' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/heat2', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/heat2', get_string('settings:heat2', 'local_assessfreq'), - get_string('settings:heat2_desc', 'local_assessfreq'), '#A2DAB5')); + get_string('settings:heat2_desc', 'local_assessfreq'), + '#A2DAB5' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/heat3', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/heat3', get_string('settings:heat3', 'local_assessfreq'), - get_string('settings:heat3_desc', 'local_assessfreq'), '#41B7C5')); + get_string('settings:heat3_desc', 'local_assessfreq'), + '#41B7C5' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/heat4', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/heat4', get_string('settings:heat4', 'local_assessfreq'), - get_string('settings:heat4_desc', 'local_assessfreq'), '#4D7FB9')); + get_string('settings:heat4_desc', 'local_assessfreq'), + '#4D7FB9' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/heat5', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/heat5', get_string('settings:heat5', 'local_assessfreq'), - get_string('settings:heat5_desc', 'local_assessfreq'), '#283B94')); + get_string('settings:heat5_desc', 'local_assessfreq'), + '#283B94' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/heat6', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/heat6', get_string('settings:heat6', 'local_assessfreq'), - get_string('settings:heat6_desc', 'local_assessfreq'), '#8C0010')); + get_string('settings:heat6_desc', 'local_assessfreq'), + '#8C0010' +)); // Chart color settings. -$sitesettings->add(new admin_setting_heading('local_assessfreq/chartheading', +$sitesettings->add(new admin_setting_heading( + 'local_assessfreq/chartheading', get_string('settings:chartheading', 'local_assessfreq'), - get_string('settings:chartheading_desc', 'local_assessfreq'))); + get_string('settings:chartheading_desc', 'local_assessfreq') +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/notloggedincolor', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/notloggedincolor', get_string('settings:notloggedincolor', 'local_assessfreq'), - get_string('settings:notloggedincolor_desc', 'local_assessfreq'), '#8C0010')); + get_string('settings:notloggedincolor_desc', 'local_assessfreq'), + '#8C0010' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/loggedincolor', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/loggedincolor', get_string('settings:loggedincolor', 'local_assessfreq'), - get_string('settings:loggedincolor_desc', 'local_assessfreq'), '#FA8900')); + get_string('settings:loggedincolor_desc', 'local_assessfreq'), + '#FA8900' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/inprogresscolor', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/inprogresscolor', get_string('settings:inprogresscolor', 'local_assessfreq'), - get_string('settings:inprogresscolor_desc', 'local_assessfreq'), '#875692')); + get_string('settings:inprogresscolor_desc', 'local_assessfreq'), + '#875692' +)); -$sitesettings->add(new admin_setting_configcolourpicker('local_assessfreq/finishedcolor', +$sitesettings->add(new admin_setting_configcolourpicker( + 'local_assessfreq/finishedcolor', get_string('settings:finishedcolor', 'local_assessfreq'), - get_string('settings:finishedcolor_desc', 'local_assessfreq'), '#1B8700')); + get_string('settings:finishedcolor_desc', 'local_assessfreq'), + '#1B8700' +)); // Build the admin menu tree. -$ADMIN->add('localplugins', new admin_category('local_assessfreq_settings', - get_string('pluginname', 'local_assessfreq'))); +$ADMIN->add('localplugins', new admin_category( + 'local_assessfreq_settings', + get_string('pluginname', 'local_assessfreq') +)); $ADMIN->add('local_assessfreq_settings', $sitesettings); $ADMIN->add('local_assessfreq_settings', $historysettings); diff --git a/student_search.php b/student_search.php index b5e0bc30..8577fac5 100644 --- a/student_search.php +++ b/student_search.php @@ -27,8 +27,13 @@ $baseurl = $CFG->wwwroot . "/local/assessfreq/student_search.php"; // Calls require_login and performs permissions checks for admin pages. -admin_externalpage_setup('local_assessfreq_student_search', '', null, '', - array('pagelayout' => 'admin')); +admin_externalpage_setup( + 'local_assessfreq_student_search', + '', + null, + '', + ['pagelayout' => 'admin'] +); $title = get_string('student_search', 'local_assessfreq'); $url = new moodle_url($baseurl); @@ -38,7 +43,7 @@ $PAGE->set_context($context); $PAGE->set_title($title); $PAGE->set_heading($title); -$PAGE->requires->js_call_amd('local_assessfreq/student_search', 'init', array($context->id)); +$PAGE->requires->js_call_amd('local_assessfreq/student_search', 'init', [$context->id]); $output = $PAGE->get_renderer('local_assessfreq'); diff --git a/styles.css b/styles.css index 1e12ab42..bf24a5aa 100644 --- a/styles.css +++ b/styles.css @@ -32,7 +32,7 @@ #local-assessfreq-report-summary .local-assessfreq-zoom, #local-assessfreq-quiz-dashboard-cards-deck .local-assessfreq-zoom, #local-assessfreq-quiz-dashboard-participant-trend-deck .local-assessfreq-zoom, -#local-assessfreq-quiz-dashboard-inprogress-cards .local-assessfreq-zoom { +#local-assessfreq-quiz-dashboard-inprogress-cards .local-assessfreq-zoom { margin-left: auto; } @@ -48,7 +48,7 @@ #local-assessfreq-quiz-dashboard-cards-deck .local-assessfreq-zoom i:hover, #local-assessfreq-quiz-summary-trend .local-assessfreq-zoom i:hover, #local-assessfreq-quiz-dashboard-inprogress-cards .local-assessfreq-zoom i:hover { - color: #111111; + color: #111; cursor: pointer; } @@ -79,13 +79,12 @@ .local-assessfreq-day-period { height: 40px; - background-color: #875692; display: flex; justify-content: space-between; border-radius: 3px; - box-shadow: 0 3px 4px rgba(0,0,0,.3); + box-shadow: 0 3px 4px rgba(0, 0, 0, .3); border-top: 1px solid #ab72ac; - background: linear-gradient(#a66db3;, #875692); + background: #875692 linear-gradient(#a66db3, #875692); } .local-assessfreq-flex-row { @@ -134,12 +133,12 @@ margin-right: 5px; margin-top: 2px; border-radius: 3px; - box-shadow: 0 3px 4px rgba(0,0,0,.3); + box-shadow: 0 3px 4px rgba(0, 0, 0, .3); } .local-assessfreq-override-status { font-weight: 600; - text-shadow: 0 1px 1px rgba(0,0,0,.3); + text-shadow: 0 1px 1px rgba(0, 0, 0, .3); } .local-assessfreq-disabled { @@ -178,4 +177,4 @@ height: 210px; padding-top: 25px; padding-right: 10px; -} \ No newline at end of file +} diff --git a/templates/assess-by-activity.mustache b/templates/assess-by-activity.mustache index 10992eb3..d978742a 100644 --- a/templates/assess-by-activity.mustache +++ b/templates/assess-by-activity.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/assess-by-activity Report Summary template. @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-assess-by-activity" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/assess-due-month-student.mustache b/templates/assess-due-month-student.mustache index 3fff33b0..56733f6f 100644 --- a/templates/assess-due-month-student.mustache +++ b/templates/assess-due-month-student.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/assess-due-month-student Report Summary template. @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-assess-due-month-student" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/assess-due-month.mustache b/templates/assess-due-month.mustache index 0312afa1..6d0dd33d 100644 --- a/templates/assess-due-month.mustache +++ b/templates/assess-due-month.mustache @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-assess-due-month" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/chart.mustache b/templates/chart.mustache index 90638b99..1b283a6e 100644 --- a/templates/chart.mustache +++ b/templates/chart.mustache @@ -22,7 +22,7 @@ Example context (json): { "withtable": true, - "chartdata": "null" + "chartdata": "null", "aspect": true } }} @@ -47,7 +47,8 @@ require([ 'core/chart_builder', 'local_assessfreq/chart_output_chartjs', 'core/chart_output_htmltable', -], function($, Builder, Output, OutputTable) { + 'core/notification', +], function($, Builder, Output, OutputTable, Notification) { var data = {{{chartdata}}}, uniqid = "{{uniqid}}", chartArea = $('#chart-area-' + uniqid), @@ -55,11 +56,12 @@ require([ chartTable = chartArea.find('.chart-table-data'), chartLink = chartArea.find('.chart-table-expand a'), aspect = (chartImage.attr('data-aspect') === 'true'), - rtLegendoptions = {{{legend}}} {{^legend}}''{{/legend}}; + rtLegendoptions = {{{legend}}}{{^legend}}''{{/legend}}; Builder.make(data).then(function(ChartInst) { new Output.init(chartImage, ChartInst, aspect, rtLegendoptions); new OutputTable(chartTable, ChartInst); - }); + return ChartInst; + }).catch(Notification.exception); chartLink.on('click', function(e) { e.preventDefault(); diff --git a/templates/nav-assess-metric-filter.mustache b/templates/nav-assess-metric-filter.mustache index a576c0a3..794ac4b7 100644 --- a/templates/nav-assess-metric-filter.mustache +++ b/templates/nav-assess-metric-filter.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-assess-metric-filter This template renders the day range selector for the timeline view. diff --git a/templates/nav-assess-type-filter.mustache b/templates/nav-assess-type-filter.mustache index 5c42d7dd..448e9455 100644 --- a/templates/nav-assess-type-filter.mustache +++ b/templates/nav-assess-type-filter.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-assess-type-filter This template renders the day range selector for the timeline view. @@ -25,7 +25,7 @@ <div id="local-assessfreq-heatmap-modules" data-region="year-filter" class="dropdown"> <button type="button" class="btn btn-secondary dropdown-toggle icon-no-margin" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" - aria-label="{{strselect}}" aria-controls="menudayfilter"> + aria-label="{{strselect}}" aria-controls="local-assessfreq-heatmap-modules-filter"> {{#pix}} i/checked {{/pix}} {{# str }} selectassessment, local_assessfreq {{/ str }} <span class="sr-only" data-active-item-text> {{#modules}} diff --git a/templates/nav-inprogress-table-sort.mustache b/templates/nav-inprogress-table-sort.mustache index 239c3b5a..dc7c52fa 100644 --- a/templates/nav-inprogress-table-sort.mustache +++ b/templates/nav-inprogress-table-sort.mustache @@ -15,12 +15,18 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-inprogress-table-sort This template renders the day range selector for the timeline view. Example context (json): - {} + { + "rows": { + "rows5": true, + "rows10": false, + "rows20": false + } + } }} <div id="local-assessfreq-inprogress-table-sort" data-region="sort-filter" class="mr-3"> <button type="button" class="btn btn-secondary dropdown-toggle icon-no-margin" diff --git a/templates/nav-quiz-table-hoursahead-filter.mustache b/templates/nav-quiz-table-hoursahead-filter.mustache index f908cd66..95395904 100644 --- a/templates/nav-quiz-table-hoursahead-filter.mustache +++ b/templates/nav-quiz-table-hoursahead-filter.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-quiz-table-hoursahead-filter This template renders the day range selector for the timeline view. diff --git a/templates/nav-quiz-table-hoursbehind-filter.mustache b/templates/nav-quiz-table-hoursbehind-filter.mustache index 61e16ece..478a08d6 100644 --- a/templates/nav-quiz-table-hoursbehind-filter.mustache +++ b/templates/nav-quiz-table-hoursbehind-filter.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-quiz-table-hoursbehind-filter This template renders the day range selector for the timeline view. diff --git a/templates/nav-quiz-table-inprogress-row-filter.mustache b/templates/nav-quiz-table-inprogress-row-filter.mustache index ebfb274c..ebf2594e 100644 --- a/templates/nav-quiz-table-inprogress-row-filter.mustache +++ b/templates/nav-quiz-table-inprogress-row-filter.mustache @@ -15,12 +15,18 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-quiz-table-inprogress-row-filter This template renders the day range selector for the timeline view. Example context (json): - {} + { + "rows": { + "rows5": true, + "rows10": false, + "rows20": false + } + } }} <div id="local-assessfreq-quiz-inprogress-table-rows" data-region="rows-filter"> <button type="button" class="btn btn-secondary dropdown-toggle icon-no-margin" diff --git a/templates/nav-quiz-table-row-filter.mustache b/templates/nav-quiz-table-row-filter.mustache index ffce735e..c87eb1c9 100644 --- a/templates/nav-quiz-table-row-filter.mustache +++ b/templates/nav-quiz-table-row-filter.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-quiz-table-row-filter This template renders the day range selector for the timeline view. diff --git a/templates/nav-year-heat-filter.mustache b/templates/nav-year-heat-filter.mustache index 985617bf..caf72c6a 100644 --- a/templates/nav-year-heat-filter.mustache +++ b/templates/nav-year-heat-filter.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/nav-year-filter + @template local_assessfreq/nav-year-heat-filter This template renders the day range selector for the timeline view. diff --git a/templates/quiz-dashboard-cards.mustache b/templates/quiz-dashboard-cards.mustache index cac5d6c9..22da4c96 100644 --- a/templates/quiz-dashboard-cards.mustache +++ b/templates/quiz-dashboard-cards.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/report-cards + @template local_assessfreq/quiz-dashboard-cards Report Summary template. diff --git a/templates/quiz-dashboard-inprogress-cards.mustache b/templates/quiz-dashboard-inprogress-cards.mustache index 8647c547..9d60dc9e 100644 --- a/templates/quiz-dashboard-inprogress-cards.mustache +++ b/templates/quiz-dashboard-inprogress-cards.mustache @@ -15,13 +15,17 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/report-cards + @template local_assessfreq/quiz-dashboard-inprogress-cards Report Summary template. Example context (json): { - + "rows": { + "rows5": true, + "rows10": false, + "rows20": false + } } }} diff --git a/templates/quiz-dashboard-inprogress-controls.mustache b/templates/quiz-dashboard-inprogress-controls.mustache index 01b750cb..164254e8 100644 --- a/templates/quiz-dashboard-inprogress-controls.mustache +++ b/templates/quiz-dashboard-inprogress-controls.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/quiz-dashboard-inprogress-summary + @template local_assessfreq/quiz-dashboard-inprogress-controls Report Summary template. diff --git a/templates/quiz-dashboard-inprogress-summary-card-content.mustache b/templates/quiz-dashboard-inprogress-summary-card-content.mustache index 6ce8e592..496f2739 100644 --- a/templates/quiz-dashboard-inprogress-summary-card-content.mustache +++ b/templates/quiz-dashboard-inprogress-summary-card-content.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-dashboard-inprogress-summary-card-content Report Summary template. diff --git a/templates/quiz-dashboard-inprogress-summary-card.mustache b/templates/quiz-dashboard-inprogress-summary-card.mustache index b699ba98..409c0f46 100644 --- a/templates/quiz-dashboard-inprogress-summary-card.mustache +++ b/templates/quiz-dashboard-inprogress-summary-card.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-dashboard-inprogress-summary-card Report Summary template. @@ -27,7 +27,7 @@ <div id="local-assessfreq-quiz-dashboard-inprogress-summary-card" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/quiz-inprogress-summary.mustache b/templates/quiz-inprogress-summary.mustache index fb648e67..2b04bbe9 100644 --- a/templates/quiz-inprogress-summary.mustache +++ b/templates/quiz-inprogress-summary.mustache @@ -15,13 +15,14 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/report-cards + @template local_assessfreq/quiz-inprogress-summary Report Summary template. Example context (json): { - + "quizids": 1, + "context": 1 } }} <div id="local-assessfreq-quiz-inprogress-table-paging-top"> @@ -38,7 +39,7 @@ <td> <a href='{{{url}}}'>{{{name}}}</a> - | <a href='{{{dashboardlink}}}' + | <a href='{{{dashboardlink}}}' data-toggle="tooltip" title="{{#str}} dashboard:assessment, local_assessfreq {{/str}}"> {{#pix}} i/report, core{{/pix}} </a> diff --git a/templates/quiz-summary-card.mustache b/templates/quiz-summary-card.mustache index e38fab93..c0ebc992 100644 --- a/templates/quiz-summary-card.mustache +++ b/templates/quiz-summary-card.mustache @@ -15,9 +15,9 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-card - Report Summary template. + Report Summary template.quiz-dashboard-cards.mustache Example context (json): { @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-quiz-summary-card" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/quiz-summary-graph.mustache b/templates/quiz-summary-graph.mustache index dd2505c4..c296a4ae 100644 --- a/templates/quiz-summary-graph.mustache +++ b/templates/quiz-summary-graph.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-graph Report Summary template. @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-quiz-summary-graph" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/quiz-summary-inprogress-graph.mustache b/templates/quiz-summary-inprogress-graph.mustache index 5713d939..7039dd3c 100644 --- a/templates/quiz-summary-inprogress-graph.mustache +++ b/templates/quiz-summary-inprogress-graph.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-inprogress-graph Report Summary template. @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-quiz-summary-inprogress-graph" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/quiz-summary-inprogress-table.mustache b/templates/quiz-summary-inprogress-table.mustache index 68032117..bdf461ee 100644 --- a/templates/quiz-summary-inprogress-table.mustache +++ b/templates/quiz-summary-inprogress-table.mustache @@ -15,13 +15,17 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-inprogress-table Report Summary template. Example context (json): { - + "rows": { + "rows5": true, + "rows10": false, + "rows20": false + } } }} @@ -35,7 +39,7 @@ <div class="input-group"> <input id="local-assessfreq-quiz-inprogress-table-search" type="text" class="form-control" placeholder="{{# str }} entersearchquiz, local_assessfreq {{/ str }}" - aria-label="{{# str }} entersearchquiz, local_assessfreq {{/ str }}" aria-describedby="basic-addon2"> + aria-label="{{# str }} entersearchquiz, local_assessfreq {{/ str }}"> <div class="input-group-append"> <button id="local-assessfreq-quiz-inprogress-table-search-reset" class="btn btn-secondary" type="button"> @@ -51,7 +55,7 @@ </div> </div> <div class="table-container"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> <div class="table-body"> diff --git a/templates/quiz-summary-student-table.mustache b/templates/quiz-summary-student-table.mustache index ac700abd..feda2317 100644 --- a/templates/quiz-summary-student-table.mustache +++ b/templates/quiz-summary-student-table.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-student-table Report Summary template. @@ -35,7 +35,7 @@ <div class="input-group"> <input id="local-assessfreq-quiz-student-table-search" type="text" class="form-control" placeholder="{{# str }} entersearch, local_assessfreq {{/ str }}" - aria-label="{{# str }} entersearch, local_assessfreq {{/ str }}" aria-describedby="basic-addon2"> + aria-label="{{# str }} entersearch, local_assessfreq {{/ str }}"> <div class="input-group-append"> <button id="local-assessfreq-quiz-student-table-search-reset" class="btn btn-secondary" type="button"> @@ -49,7 +49,7 @@ </div> </div> <div class="table-container"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> <div class="table-body"> diff --git a/templates/quiz-summary-trend-graph.mustache b/templates/quiz-summary-trend-graph.mustache index 8960536c..5fa95891 100644 --- a/templates/quiz-summary-trend-graph.mustache +++ b/templates/quiz-summary-trend-graph.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-trend-graph Report Summary template. @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-quiz-summary-trend" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/quiz-summary-upcomming-card.mustache b/templates/quiz-summary-upcomming-card.mustache index 020d746c..8273f072 100644 --- a/templates/quiz-summary-upcomming-card.mustache +++ b/templates/quiz-summary-upcomming-card.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-upcomming-card Report Summary template. @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-quiz-summary-upcomming-card" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/quiz-summary-upcomming-graph.mustache b/templates/quiz-summary-upcomming-graph.mustache index 01993f54..4397ca0c 100644 --- a/templates/quiz-summary-upcomming-graph.mustache +++ b/templates/quiz-summary-upcomming-graph.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/quiz-summary-upcomming-graph Report Summary template. @@ -26,7 +26,7 @@ }} <div id="local-assessfreq-quiz-summary-upcomming-graph" class="card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> diff --git a/templates/report-cards.mustache b/templates/report-cards.mustache index c5f9872c..dc48625f 100644 --- a/templates/report-cards.mustache +++ b/templates/report-cards.mustache @@ -33,7 +33,7 @@ </div> <div class="col-sm d-flex justify-content-end"> <button id="local-assessfreq-hide-report-btn" class="btn btn-secondary" type="button" data-toggle="collapse" - data-target=".local-assessfreq-report-overview" aria-expanded="true" aria-controls="collapseOverview"> + data-target=".local-assessfreq-report-overview" aria-expanded="true" aria-controls="local-assessfreq-report-overview"> {{#pix}} t/expanded {{/pix}} {{# str }} toggleoverview, local_assessfreq {{/ str }} </button> </div> diff --git a/templates/report-heatmap.mustache b/templates/report-heatmap.mustache index d74f3fc1..7731cfc5 100644 --- a/templates/report-heatmap.mustache +++ b/templates/report-heatmap.mustache @@ -55,7 +55,7 @@ </div> </div> <div id="local-assessfreq-report-heatmap-card" class="local-assessfreq-report-heatmap card"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> <div class="row no-gutters m-2"> diff --git a/templates/scheduler_form_element.mustache b/templates/scheduler_form_element.mustache index 8cd29dc3..fa4ed2b6 100644 --- a/templates/scheduler_form_element.mustache +++ b/templates/scheduler_form_element.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template core_form/element-static + @template core_form/scheduler_form_element Static form element template. A static form element is an element that just outputs raw HTML. diff --git a/templates/student-search-table.mustache b/templates/student-search-table.mustache index 2315ef3c..8f4c6a38 100644 --- a/templates/student-search-table.mustache +++ b/templates/student-search-table.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/assess-due-month + @template local_assessfreq/student-search-table Report Summary template. @@ -35,7 +35,7 @@ <div class="input-group"> <input id="local-assessfreq-quiz-student-table-search" type="text" class="form-control" placeholder="{{# str }} entersearch, local_assessfreq {{/ str }}" - aria-label="{{# str }} entersearch, local_assessfreq {{/ str }}" aria-describedby="basic-addon2"> + aria-label="{{# str }} entersearch, local_assessfreq {{/ str }}"> <div class="input-group-append"> <button id="local-assessfreq-quiz-student-table-search-reset" class="btn btn-secondary" type="button"> @@ -51,7 +51,7 @@ </div> </div> <div class="table-container"> - <span id="local-assessfreq-spinner-{{uniqid}}" class="overlay-icon-container" data-region="overlay-icon-container"> + <span class="overlay-icon-container" data-region="overlay-icon-container"> <span class="loading-icon icon-no-margin">{{#pix}} i/loading, core, {{#str}} loading {{/str}} {{/pix}}</span> </span> <div class="table-body"> diff --git a/templates/student-search.mustache b/templates/student-search.mustache index 880327aa..9a04cc04 100644 --- a/templates/student-search.mustache +++ b/templates/student-search.mustache @@ -15,7 +15,7 @@ along with Moodle. If not, see <http://www.gnu.org/licenses/>. }} {{! - @template local_assessfreq/report-cards + @template local_assessfreq/student-search Report Summary template. diff --git a/tests/behat/assessmentfreq.feature b/tests/behat/assessmentfreq.feature index 5678965b..35cee4c2 100644 --- a/tests/behat/assessmentfreq.feature +++ b/tests/behat/assessmentfreq.feature @@ -99,5 +99,5 @@ Feature: Assessment frequency | Forum: Test forum 1 | | Lesson: Test lesson 1 | | Quiz: Test quiz 1 | - | SCORM package: test scorm 1 | + | SCORM package: Test scorm 1 | | Workshop: Test workshop 1 | diff --git a/tests/external_test.php b/tests/external_test.php index 632f53a1..fd2c9027 100644 --- a/tests/external_test.php +++ b/tests/external_test.php @@ -24,8 +24,6 @@ namespace local_assessfreq; -defined('MOODLE_INTERNAL') || die(); - use assign; use context_module; use external_api; @@ -44,7 +42,6 @@ * @runTestsInSeparateProcesses */ class external_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -119,40 +116,41 @@ public function setUp(): void { $generator = $this->getDataGenerator(); $layout = '1,2,0,3,4,0,5,6,0'; $course = $generator->create_course( - array('fullname' => 'blue course', 'format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); - $assignrow1 = $generator->create_module('assign', array( + ['fullname' => 'blue course', 'format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); + $assignrow1 = $generator->create_module('assign', [ 'course' => $course->id, - 'duedate' => 1585359375 - )); - $assignrow2 = $generator->create_module('assign', array( + 'duedate' => 1585359375, + ]); + $assignrow2 = $generator->create_module('assign', [ 'course' => $course->id, - 'duedate' => 1585445775 - )); + 'duedate' => 1585445775, + ]); $this->assign1 = new assign(context_module::instance($assignrow1->cmid), false, false); $this->assign2 = new assign(context_module::instance($assignrow2->cmid), false, false); $this->course = $course; - $this->quiz1 = $generator->create_module('quiz', array( + $this->quiz1 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593910800, 'timeclose' => 1593914400, 'timelimit' => 3600, - 'layout' => $layout - )); - $this->quiz2 = $generator->create_module('quiz', array( + 'layout' => $layout, + ]); + $this->quiz2 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593997200, 'timeclose' => 1594004400, - 'timelimit' => 7200 - )); - $this->quiz3 = $generator->create_module('quiz', array( + 'timelimit' => 7200, + ]); + $this->quiz3 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => null, 'timeclose' => null, - 'timelimit' => 7200 - )); + 'timelimit' => 7200, + ]); // Create some users. $user1 = $generator->create_user(); @@ -183,7 +181,6 @@ public function setUp(): void { if ($slot % 2 == 0) { $question = $questiongenerator->create_question('shortanswer', null, ['category' => $cat->id]); - } else { $question = $questiongenerator->create_question('essay', null, ['category' => $cat->id]); } @@ -213,7 +210,7 @@ public function setUp(): void { $override3->timeclose = null; $override3->timelimit = 7200; - $overriderecords = array($override1, $override2); + $overriderecords = [$override1, $override2]; $DB->insert_records('quiz_overrides', $overriderecords); $this->user1 = $user1; @@ -228,14 +225,14 @@ public function setUp(): void { /** * Test ajax getting of event data. */ - public function test_get_frequency() { + public function test_get_frequency(): void { $this->setAdminUser(); $duedate = 0; - $data = new stdClass; + $data = new stdClass(); $data->year = 2020; $data->metric = 'assess'; // Can be assess or students. - $data->modules = array('all'); + $data->modules = ['all']; $jsondata = json_encode($data); @@ -269,11 +266,11 @@ public function test_get_frequency() { /** * Test ajax getting of event data. */ - public function test_get_process_modules() { + public function test_get_process_modules(): void { global $DB; - $DB->set_field('modules', 'visible', '0', array('name' => 'scorm')); - $DB->set_field('modules', 'visible', '0', array('name' => 'choice')); + $DB->set_field('modules', 'visible', '0', ['name' => 'scorm']); + $DB->set_field('modules', 'visible', '0', ['name' => 'choice']); set_config('modules', 'quiz,assign,scorm,choice', 'local_assessfreq'); set_config('disabledmodules', '0', 'local_assessfreq'); @@ -296,22 +293,21 @@ public function test_get_process_modules() { $this->assertArrayHasKey('assign', $eventarr); $this->assertArrayHasKey('scorm', $eventarr); $this->assertArrayHasKey('choice', $eventarr); - } /** * Test ajax getting of day event data. */ - public function test_get_day_events() { + public function test_get_day_events(): void { $this->setAdminUser(); $frequency = new frequency(); $frequency->process_site_events(0); $frequency->process_user_events(0); - $data = new stdClass; + $data = new stdClass(); $data->date = '2020-03-28'; - $data->modules = array('all'); + $data->modules = ['all']; $jsondata = json_encode($data); @@ -329,7 +325,7 @@ public function test_get_day_events() { /** * Test ajax getting of course names. */ - public function test_get_courses() { + public function test_get_courses(): void { $this->setAdminUser(); $query = 'blu'; @@ -344,16 +340,16 @@ public function test_get_courses() { /** * Test ajax getting of quiz names. */ - public function test_get_quizzes() { + public function test_get_quizzes(): void { $this->setAdminUser(); $generator = $this->getDataGenerator(); - $generator->create_module('quiz', array( - 'course' => $this->course->id - )); - $generator->create_module('quiz', array( - 'course' => $this->course->id - )); + $generator->create_module('quiz', [ + 'course' => $this->course->id, + ]); + $generator->create_module('quiz', [ + 'course' => $this->course->id, + ]); $query = $this->course->id; @@ -367,7 +363,7 @@ public function test_get_quizzes() { /** * Test ajax getting of quiz names. */ - public function test_get_quiz_data() { + public function test_get_quiz_data(): void { $this->setAdminUser(); $quizid = $this->quiz1->id; @@ -388,7 +384,7 @@ public function test_get_quiz_data() { /** * Test getting of quiz data with dates not available. */ - public function test_get_quiz_data_dates_na() { + public function test_get_quiz_data_dates_na(): void { $this->setAdminUser(); $quizid = $this->quiz3->id; @@ -404,7 +400,7 @@ public function test_get_quiz_data_dates_na() { /** * Test getting of quiz data with dates not available. */ - public function test_get_quiz_data_overrides_na() { + public function test_get_quiz_data_overrides_na(): void { $this->setAdminUser(); $quizid = $this->quiz3->id; @@ -420,7 +416,7 @@ public function test_get_quiz_data_overrides_na() { /** * Test setting table preferences. */ - public function test_set_table_preference() { + public function test_set_table_preference(): void { global $SESSION; $this->setAdminUser(); @@ -436,13 +432,12 @@ public function test_set_table_preference() { $this->assertEquals(1, $SESSION->flextable[$tableid]['collapse']['username']); $this->assertEquals(0, $SESSION->flextable[$tableid]['collapse']['idnumber']); $this->assertEquals(0, $SESSION->flextable[$tableid]['collapse']['email']); - } /** * Test ajax getting of in progress quiz counts. */ - public function test_get_inprogress_counts() { + public function test_get_inprogress_counts(): void { $this->setAdminUser(); $returnvalue = local_assessfreq_external::get_inprogress_counts(); @@ -452,5 +447,4 @@ public function test_get_inprogress_counts() { $this->assertEquals(0, $returnarr['assessments']); $this->assertEquals(0, $returnarr['participants']); } - } diff --git a/tests/frequency_test.php b/tests/frequency_test.php index 1d43e8a0..128165b4 100644 --- a/tests/frequency_test.php +++ b/tests/frequency_test.php @@ -44,7 +44,6 @@ * @covers \local_assessfreq\frequency */ class frequency_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -86,17 +85,18 @@ public function setUp(): void { // Create a course with activity. $generator = $this->getDataGenerator(); $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); - $assignrow1 = $generator->create_module('assign', array( + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); + $assignrow1 = $generator->create_module('assign', [ 'course' => $course->id, - 'duedate' => 1585359375 - )); - $assignrow2 = $generator->create_module('assign', array( + 'duedate' => 1585359375, + ]); + $assignrow2 = $generator->create_module('assign', [ 'course' => $course->id, - 'duedate' => 1585445775 - )); + 'duedate' => 1585445775, + ]); $this->assign1 = new assign(context_module::instance($assignrow1->cmid), false, false); $this->assign2 = new assign(context_module::instance($assignrow2->cmid), false, false); $this->assign1->cmid = $assignrow1->cmid; @@ -120,7 +120,7 @@ public function setUp(): void { /** * Test getting a modules events. */ - public function test_get_module_events() { + public function test_get_module_events(): void { $sql = 'SELECT cm.id, cm.course, m.name, cm.instance, c.id as contextid, a.duedate FROM {course_modules} cm INNER JOIN {modules} m ON cm.module = m.id @@ -132,7 +132,7 @@ public function test_get_module_events() { AND a.duedate > ? AND cm.visible = ? AND course.visible = ?'; - $params = array('assign', CONTEXT_MODULE, 0, 1, 1); + $params = ['assign', CONTEXT_MODULE, 0, 1, 1]; $frequency = new frequency(); @@ -141,7 +141,7 @@ public function test_get_module_events() { $method->setAccessible(true); // Allow accessing of private method. $result = $method->invoke($frequency, $sql, $params); - $contextids = array($this->assign1->get_context()->id, $this->assign2->get_context()->id); + $contextids = [$this->assign1->get_context()->id, $this->assign2->get_context()->id]; foreach ($result as $record) { $this->assertEquals($this->course->id, $record->course); @@ -149,13 +149,12 @@ public function test_get_module_events() { $this->assertEquals('assign', $record->name); } $result->close(); - } /** * Test format time method. */ - public function test_format_time() { + public function test_format_time(): void { $frequency = new frequency(); $timestamp = 1585445775; @@ -173,7 +172,7 @@ public function test_format_time() { /** * Test process module events method. */ - public function test_process_module_events() { + public function test_process_module_events(): void { global $DB; $frequency = new frequency(); @@ -189,7 +188,7 @@ public function test_process_module_events() { AND a.duedate > ? AND cm.visible = ? AND course.visible = ?'; - $params = array('assign', CONTEXT_MODULE, 0, 1, 1); + $params = ['assign', CONTEXT_MODULE, 0, 1, 1]; // We're testing a private method, so we need to setup reflector magic. $method = new ReflectionMethod('\local_assessfreq\frequency', 'get_module_events'); @@ -205,8 +204,8 @@ public function test_process_module_events() { $this->assertEquals(2, $result); // Check the expected number of records inserted. // Check actual records in the DB. - $record1 = $DB->get_record('local_assessfreq_site', array('instanceid' => $this->assign1->get_course_module()->instance)); - $record2 = $DB->get_record('local_assessfreq_site', array('instanceid' => $this->assign2->get_course_module()->instance)); + $record1 = $DB->get_record('local_assessfreq_site', ['instanceid' => $this->assign1->get_course_module()->instance]); + $record2 = $DB->get_record('local_assessfreq_site', ['instanceid' => $this->assign2->get_course_module()->instance]); $this->assertEquals(28, $record1->endday); $this->assertEquals(29, $record2->endday); @@ -216,13 +215,12 @@ public function test_process_module_events() { // In this case the cleanup task won't have deleted the records so we need to test it at process/update time. $recordset = $method->invoke($frequency, $sql, $params); $result = $method2->invoke($frequency, $recordset); - } /** * Test process site events method. */ - public function test_process_site_events() { + public function test_process_site_events(): void { global $DB; $now = 1585359400; @@ -232,14 +230,14 @@ public function test_process_site_events() { $this->assertEquals(1, $result); // Check actual records in the DB. - $record = $DB->get_record('local_assessfreq_site', array('instanceid' => $this->assign2->get_course_module()->instance)); + $record = $DB->get_record('local_assessfreq_site', ['instanceid' => $this->assign2->get_course_module()->instance]); $this->assertEquals(29, $record->endday); } /** * Test process site events method. */ - public function test_delete_events() { + public function test_delete_events(): void { global $DB; $duedate = 0; @@ -274,20 +272,19 @@ public function test_delete_events() { /** * Test process getting raw users for an event. */ - public function test_get_event_users_raw() { + public function test_get_event_users_raw(): void { $frequency = new frequency(); $result = $frequency->get_event_users_raw($this->assign1->get_context()->id, 'assign'); $this->assertEquals($this->user1->id, $result[$this->user1->id]->id); $this->assertEquals($this->user2->id, $result[$this->user2->id]->id); - } /** * Test process getting users for an event. */ - public function test_get_event_users() { + public function test_get_event_users(): void { $duedate = 0; $frequency = new frequency(); $frequency->process_site_events($duedate); @@ -308,13 +305,12 @@ public function test_get_event_users() { $data = $eventuserscache->get($cachekey); $this->assertCount(2, $data->users); - } /** * Test process processing user events. */ - public function test_process_user_events() { + public function test_process_user_events(): void { global $DB; $duedate = 0; @@ -326,8 +322,8 @@ public function test_process_user_events() { $this->assertEquals(4, $result); // Check the reocrds in the database. - $count1 = $DB->count_records('local_assessfreq_user', array('userid' => $this->user1->id)); - $count2 = $DB->count_records('local_assessfreq_user', array('userid' => $this->user2->id)); + $count1 = $DB->count_records('local_assessfreq_user', ['userid' => $this->user1->id]); + $count2 = $DB->count_records('local_assessfreq_user', ['userid' => $this->user2->id]); $this->assertEquals(2, $count1); $this->assertEquals(2, $count2); @@ -336,7 +332,7 @@ public function test_process_user_events() { /** * Test filtering event by dater events. */ - public function test_filter_event_data() { + public function test_filter_event_data(): void { global $DB; $duedate = 0; @@ -365,7 +361,7 @@ public function test_filter_event_data() { /** * Test getting site events and cache. */ - public function test_get_site_events() { + public function test_get_site_events(): void { global $DB; $duedate = 0; @@ -390,7 +386,7 @@ public function test_get_site_events() { $this->assertEmpty($data); $this->course->visible = 0; - $DB->set_field('course', 'visible', 0, array('id' => $this->course->id)); + $DB->set_field('course', 'visible', 0, ['id' => $this->course->id]); $result = $frequency->get_site_events('all', 0, 0, false); $this->assertEmpty($result); @@ -398,13 +394,12 @@ public function test_get_site_events() { set_config('hiddencourses', '1', 'local_assessfreq'); $result = $frequency->get_site_events('all', 0, 0, false); $this->assertCount(2, $result); - } /** * Test getting course events and cache. */ - public function test_get_course_events() { + public function test_get_course_events(): void { $duedate = 0; $frequency = new frequency(); $frequency->process_site_events($duedate); @@ -433,7 +428,7 @@ public function test_get_course_events() { /** * Test getting user events and cache. */ - public function test_get_user_events() { + public function test_get_user_events(): void { global $DB; $duedate = 0; @@ -462,7 +457,7 @@ public function test_get_user_events() { $this->assertEmpty($data); $this->course->visible = 0; - $DB->set_field('course', 'visible', 0, array('id' => $this->course->id)); + $DB->set_field('course', 'visible', 0, ['id' => $this->course->id]); $result = $frequency->get_user_events($this->user1->id, 'all', 0, 0, false); $this->assertEmpty($result); @@ -475,7 +470,7 @@ public function test_get_user_events() { /** * Test getting all user events and cache. */ - public function test_get_user_events_all() { + public function test_get_user_events_all(): void { global $DB; $duedate = 0; @@ -490,7 +485,7 @@ public function test_get_user_events_all() { $this->assertEmpty($result); $this->course->visible = 0; - $DB->set_field('course', 'visible', 0, array('id' => $this->course->id)); + $DB->set_field('course', 'visible', 0, ['id' => $this->course->id]); $result = iterator_to_array($frequency->get_user_events_all('all', 0, 0, false)); $this->assertEmpty($result); @@ -503,7 +498,7 @@ public function test_get_user_events_all() { /** * Test getting conflict data. */ - public function test_get_conflicts() { + public function test_get_conflicts(): void { global $DB; // Setup records in DB. @@ -593,9 +588,9 @@ public function test_get_conflicts() { // Record 7 should not have any conflicts because it has no users. // Insert records in to database. - $records = array($lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4, $lasrecord5, $lasrecord6, $lasrecord7); - $userids = array(234, 456, 789); - $eventarray = array(); + $records = [$lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4, $lasrecord5, $lasrecord6, $lasrecord7]; + $userids = [234, 456, 789]; + $eventarray = []; foreach ($records as $record) { $eventid = $DB->insert_record('local_assessfreq_site', $record); $eventarray[$record->instanceid] = $eventid; @@ -610,7 +605,6 @@ public function test_get_conflicts() { $DB->insert_record('local_assessfreq_user', $userrecord); } } - } $frequency = new frequency(); @@ -638,18 +632,17 @@ public function test_get_conflicts() { /** * Test getting course events and cache. */ - public function test_get_events_due_by_month() { + public function test_get_events_due_by_month(): void { global $DB; $year = 2020; // Make some records to put in the database; // Every even month should have two entries and every odd month one entry. - $records = array(); + $records = []; $month = 1; for ($i = 1; $i <= 24; $i++) { - if ($i > 12 && ($month % 2 != 0)) { - $month ++; + $month++; continue; } @@ -669,7 +662,7 @@ public function test_get_events_due_by_month() { if ($month == 12) { $month = 0; } - $month ++; + $month++; } $DB->insert_records('local_assessfreq_site', $records); @@ -691,7 +684,7 @@ public function test_get_events_due_by_month() { $this->assertCount(12, $data->events); $this->course->visible = 0; - $DB->set_field('course', 'visible', 0, array('id' => $this->course->id)); + $DB->set_field('course', 'visible', 0, ['id' => $this->course->id]); $result = $frequency->get_events_due_by_month($year, false); $this->assertEmpty($result); @@ -705,7 +698,7 @@ public function test_get_events_due_by_month() { * Test getting course events and cache. * Check behavior if there is no data. */ - public function test_get_events_due_by_month_no_data() { + public function test_get_events_due_by_month_no_data(): void { $year = 2020; // Cache should be initially empty. @@ -726,12 +719,12 @@ public function test_get_events_due_by_month_no_data() { /** * Test years that have events. */ - public function test_get_years_has_events() { + public function test_get_years_has_events(): void { global $DB; // Make some records to put in the database; // Every even month should have two entries and every odd month one entry. - $records = array(); + $records = []; $lasrecord1 = new stdClass(); $lasrecord1->module = 'quiz'; @@ -777,7 +770,7 @@ public function test_get_years_has_events() { $lasrecord4->endmonth = 4; $lasrecord4->endday = 6; - $records = array($lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4); + $records = [$lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4]; $DB->insert_records('local_assessfreq_site', $records); @@ -803,7 +796,7 @@ public function test_get_years_has_events() { * Test years that have events. * Check behavior if there is no data. */ - public function test_get_years_has_events_no_data() { + public function test_get_years_has_events_no_data(): void { // Cache should be initially empty. $yeareventscache = cache::make('local_assessfreq', 'yearevents'); $cachekey = 'yearevents'; @@ -822,13 +815,13 @@ public function test_get_years_has_events_no_data() { /** * Test getting activities that have events. */ - public function test_get_events_due_by_activity() { + public function test_get_events_due_by_activity(): void { global $DB; $year = 2020; // Make some records to put in the database; // Every even month should have two entries and every odd month one entry. - $records = array(); + $records = []; $lasrecord1 = new stdClass(); $lasrecord1->module = 'quiz'; @@ -885,7 +878,7 @@ public function test_get_events_due_by_activity() { $lasrecord5->endmonth = 4; $lasrecord5->endday = 6; - $records = array($lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4, $lasrecord5); + $records = [$lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4, $lasrecord5]; $DB->insert_records('local_assessfreq_site', $records); @@ -907,7 +900,7 @@ public function test_get_events_due_by_activity() { $this->assertCount(3, $data->events); $this->course->visible = 0; - $DB->set_field('course', 'visible', 0, array('id' => $this->course->id)); + $DB->set_field('course', 'visible', 0, ['id' => $this->course->id]); $result = $frequency->get_events_due_by_activity($year, false); $this->assertEmpty($result); @@ -920,7 +913,7 @@ public function test_get_events_due_by_activity() { /** * Test getting user events and cache. */ - public function test_get_events_due_monthly_by_user() { + public function test_get_events_due_monthly_by_user(): void { global $DB; $year = 2020; @@ -947,7 +940,6 @@ public function test_get_events_due_monthly_by_user() { $DB->insert_record('local_assessfreq_user', $userrecord, true); } - } // Cache should be initially empty. @@ -972,7 +964,7 @@ public function test_get_events_due_monthly_by_user() { $this->assertCount(12, $data->events); $this->course->visible = 0; - $DB->set_field('course', 'visible', 0, array('id' => $this->course->id)); + $DB->set_field('course', 'visible', 0, ['id' => $this->course->id]); $result = $frequency->get_events_due_monthly_by_user($year, false); $this->assertEmpty($result); @@ -985,10 +977,10 @@ public function test_get_events_due_monthly_by_user() { /** * Test getting the frequency array. */ - public function test_get_frequency_array() { + public function test_get_frequency_array(): void { $year = 2020; $metric = 'assess'; // Can be assess or students. - $modules = array('all'); + $modules = ['all']; $duedate = 0; $frequency = new frequency(); @@ -1018,16 +1010,15 @@ public function test_get_frequency_array() { $this->assertEquals(2, $data[2020][3][28]['number']); $this->assertEquals(2, $data[2020][3][29]['assign']); $this->assertEquals(2, $data[2020][3][28]['assign']); - } /** * Test getting the download data. */ - public function test_get_download_data() { + public function test_get_download_data(): void { $year = 2020; $metric = 'assess'; // Can be assess or students. - $modules = array('all'); + $modules = ['all']; $duedate = 0; $frequency = new frequency(); @@ -1047,7 +1038,7 @@ public function test_get_download_data() { /** * Test getting heat colors. */ - public function test_get_heat_colors() { + public function test_get_heat_colors(): void { $frequency = new frequency(); $result = $frequency->get_heat_colors(); @@ -1066,11 +1057,11 @@ public function test_get_heat_colors() { /** * Test getting modules to process. */ - public function test_get_process_modules() { + public function test_get_process_modules(): void { global $DB; - $DB->set_field('modules', 'visible', '0', array('name' => 'scorm')); - $DB->set_field('modules', 'visible', '0', array('name' => 'choice')); + $DB->set_field('modules', 'visible', '0', ['name' => 'scorm']); + $DB->set_field('modules', 'visible', '0', ['name' => 'choice']); set_config('modules', 'quiz,assign,scorm,choice', 'local_assessfreq'); set_config('disabledmodules', '0', 'local_assessfreq'); @@ -1084,7 +1075,8 @@ public function test_get_process_modules() { $this->assertNotContains('choice', $result); set_config('disabledmodules', '1', 'local_assessfreq'); - $result = $frequency->get_process_modules();; + $result = $frequency->get_process_modules(); + ; $this->assertContains('quiz', $result); $this->assertContains('assign', $result); @@ -1095,9 +1087,9 @@ public function test_get_process_modules() { /** * Test getting day event information. */ - public function test_get_day_events() { + public function test_get_day_events(): void { $date = '2020-3-28'; - $modules = array('all'); + $modules = ['all']; $frequency = new frequency(); $frequency->process_site_events(0); @@ -1110,15 +1102,14 @@ public function test_get_day_events() { $this->assertEquals(2020, $result[0]->endyear); $this->assertEquals(3, $result[0]->endmonth); $this->assertEquals(28, $result[0]->endday); - } /** * Test getting day event information with the case that an event has been deleted since the data was gathered. */ - public function test_get_day_events_deleted() { + public function test_get_day_events_deleted(): void { $date = '2020-3-28'; - $modules = array('all'); + $modules = ['all']; $frequency = new frequency(); $frequency->process_site_events(0); @@ -1128,42 +1119,42 @@ public function test_get_day_events_deleted() { $result = $frequency->get_day_events($date, $modules); $this->assertEmpty($result); - } /** * Test getting sorted day event information. */ - public function test_get_day_events_sorting() { + public function test_get_day_events_sorting(): void { // Create some extra data to sort. $generator = $this->getDataGenerator(); $course2 = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, 'enablecompletion' => 1, 'shortname' => 'zzz'), - array('createsections' => true)); - $assignrow3 = $generator->create_module('assign', array( + ['format' => 'topics', 'numsections' => 3, 'enablecompletion' => 1, 'shortname' => 'zzz'], + ['createsections' => true] + ); + $assignrow3 = $generator->create_module('assign', [ 'course' => $this->course->id, 'duedate' => 1585359375, 'allowsubmissionsfromdate' => 100, - 'name' => 'zzzz assign' - )); - $assignrow4 = $generator->create_module('assign', array( + 'name' => 'zzzz assign', + ]); + $assignrow4 = $generator->create_module('assign', [ 'course' => $course2->id, 'duedate' => 1585359375, - 'allowsubmissionsfromdate' => 100 - )); - $assignrow5 = $generator->create_module('assign', array( + 'allowsubmissionsfromdate' => 100, + ]); + $assignrow5 = $generator->create_module('assign', [ 'course' => $course2->id, 'duedate' => 1585359375, 'allowsubmissionsfromdate' => 100, - 'name' => 'zzzz assign' - )); + 'name' => 'zzzz assign', + ]); $assign3 = new assign(context_module::instance($assignrow3->cmid), false, false); $assign4 = new assign(context_module::instance($assignrow4->cmid), false, false); new assign(context_module::instance($assignrow5->cmid), false, false); $date = '2020-3-28'; - $modules = array('all'); + $modules = ['all']; $frequency = new frequency(); $frequency->process_site_events(0); diff --git a/tests/output/all_participants_inprogress_test.php b/tests/output/all_participants_inprogress_test.php index 88afbaa0..4b1ce520 100644 --- a/tests/output/all_participants_inprogress_test.php +++ b/tests/output/all_participants_inprogress_test.php @@ -35,7 +35,6 @@ * @covers \local_assessfreq\output\all_participants_inprogress */ class all_participants_inprogress_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -121,49 +120,50 @@ public function setUp(): void { $generator = $this->getDataGenerator(); $layout = '1,2,0,3,4,0,5,6,0'; $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); // Start is more than one hour in the past, but end is in the future. (Should return). - $this->quiz3 = $generator->create_module('quiz', array( + $this->quiz3 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 2)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the past, but end is in the future. (Should return). - $this->quiz4 = $generator->create_module('quiz', array( + $this->quiz4 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 0.5)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is more than one hour in the future. (Should return). - $this->quiz5 = $generator->create_module('quiz', array( + $this->quiz5 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.5)), 'timeclose' => ($now + (3600 * 2)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is less that one hour in the future. (Should return). - $this->quiz6 = $generator->create_module('quiz', array( + $this->quiz6 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.25)), 'timeclose' => ($now + (3600 * 0.75)), - 'timelimit' => 1800 - )); + 'timelimit' => 1800, + ]); // Start is more than one hour in the future, end is more than one hour in the future. (Should not return). - $this->quiz7 = $generator->create_module('quiz', array( + $this->quiz7 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 2)), 'timeclose' => ($now + (3600 * 3)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Create some users. $user1 = $generator->create_user(); @@ -196,7 +196,7 @@ public function setUp(): void { $override2->timeclose = 1594005000; // End late. $override2->timelimit = 7200; - $overriderecords = array($override1, $override2); + $overriderecords = [$override1, $override2]; $DB->insert_records('quiz_overrides', $overriderecords); @@ -206,7 +206,6 @@ public function setUp(): void { $this->user4 = $user4; $this->user5 = $user5; $this->user6 = $user6; - } /** @@ -259,7 +258,7 @@ public function setup_quiz_tracking(int $now, int $quizid): void { $track5->timecreated = $now + (60 * 5); // Insert out of order. - $trackrecords = array($track1, $track5, $track3, $track2, $track4); + $trackrecords = [$track1, $track5, $track3, $track2, $track4]; $DB->insert_records('local_assessfreq_trend', $trackrecords); } @@ -267,7 +266,7 @@ public function setup_quiz_tracking(int $now, int $quizid): void { /** * Test get upcomming quiz chart. */ - public function test_get_all_participants_inprogress_chart() { + public function test_get_all_participants_inprogress_chart(): void { $now = 1594788000; $upcomming = new all_participants_inprogress(); @@ -301,6 +300,5 @@ public function test_get_all_participants_inprogress_chart() { $this->assertEquals('Logged in', $labels[1]); $this->assertEquals('In progress', $labels[2]); $this->assertEquals('Finished', $labels[3]); - } } diff --git a/tests/output/assess_by_activity_test.php b/tests/output/assess_by_activity_test.php index c0167456..803d3675 100644 --- a/tests/output/assess_by_activity_test.php +++ b/tests/output/assess_by_activity_test.php @@ -35,7 +35,6 @@ * @covers \local_assessfreq\output\assess_by_activity */ class assess_by_activity_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -51,9 +50,10 @@ public function setUp(): void { // Create a course. $generator = $this->getDataGenerator(); $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); $this->course = $course; $version = get_config('moodle', 'version'); @@ -68,13 +68,13 @@ public function setUp(): void { /** * Test gett assess due by month chart method. */ - public function test_get_assess_activity_chart() { + public function test_get_assess_activity_chart(): void { global $DB; $year = 2020; // Make some records to put in the database; // Every even month should have two entries and every odd month one entry. - $records = array(); + $records = []; $lasrecord1 = new stdClass(); $lasrecord1->module = 'quiz'; @@ -131,7 +131,7 @@ public function test_get_assess_activity_chart() { $lasrecord5->endmonth = 4; $lasrecord5->endday = 6; - $records = array($lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4, $lasrecord5); + $records = [$lasrecord1, $lasrecord2, $lasrecord3, $lasrecord4, $lasrecord5]; $DB->insert_records('local_assessfreq_site', $records); @@ -161,6 +161,5 @@ public function test_get_assess_activity_chart() { $this->assertEquals(1, $values[7]); $this->assertEquals(0, $values[8]); } - } } diff --git a/tests/output/assess_by_month_student_test.php b/tests/output/assess_by_month_student_test.php index c9884f81..d28424dd 100644 --- a/tests/output/assess_by_month_student_test.php +++ b/tests/output/assess_by_month_student_test.php @@ -35,7 +35,6 @@ * @covers \local_assessfreq\output\assess_by_month_student */ class assess_by_month_student_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -51,9 +50,10 @@ public function setUp(): void { // Create a course. $generator = $this->getDataGenerator(); $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); $this->course = $course; $version = get_config('moodle', 'version'); @@ -69,7 +69,7 @@ public function setUp(): void { /** * Test gett assess due by month chart method. */ - public function test_get_assess_due_chart() { + public function test_get_assess_due_chart(): void { global $DB; $year = 2020; @@ -96,7 +96,6 @@ public function test_get_assess_due_chart() { $DB->insert_record('local_assessfreq_user', $userrecord, true); } - } $assessbymonthstudent = new assess_by_month_student(); diff --git a/tests/output/assess_by_month_test.php b/tests/output/assess_by_month_test.php index be1aace7..ccc47a85 100644 --- a/tests/output/assess_by_month_test.php +++ b/tests/output/assess_by_month_test.php @@ -35,7 +35,6 @@ * @covers \local_assessfreq\output\assess_by_month */ class assess_by_month_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -51,9 +50,10 @@ public function setUp(): void { // Create a course. $generator = $this->getDataGenerator(); $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); $this->course = $course; $version = get_config('moodle', 'version'); @@ -68,18 +68,17 @@ public function setUp(): void { /** * Test gett assess due by month chart method. */ - public function test_get_assess_due_chart() { + public function test_get_assess_due_chart(): void { global $DB; $year = 2020; // Make some records to put in the database; // Every even month should have two entries and every odd month one entry. - $records = array(); + $records = []; $month = 1; for ($i = 1; $i <= 24; $i++) { - if ($i > 12 && ($month % 2 != 0)) { - $month ++; + $month++; continue; } @@ -99,7 +98,7 @@ public function test_get_assess_due_chart() { if ($month == 12) { $month = 0; } - $month ++; + $month++; } $DB->insert_records('local_assessfreq_site', $records); diff --git a/tests/output/participant_summary_test.php b/tests/output/participant_summary_test.php index 2cbf50fd..1e7c57a7 100644 --- a/tests/output/participant_summary_test.php +++ b/tests/output/participant_summary_test.php @@ -35,7 +35,6 @@ * @covers \local_assessfreq\output\participant_summary */ class participant_summary_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -92,16 +91,15 @@ public function setUp(): void { $track5->timecreated = $now + (60 * 5); // Insert out of order. - $trackrecords = array($track1, $track5, $track3, $track2, $track4); + $trackrecords = [$track1, $track5, $track3, $track2, $track4]; $DB->insert_records('local_assessfreq_trend', $trackrecords); - } /** * Test gett assess due by month chart method. */ - public function test_get_assess_activity_chart() { + public function test_get_assess_activity_chart(): void { $participantsumamry = new participant_summary(); $result = $participantsumamry->get_participant_summary_chart(123); @@ -118,6 +116,5 @@ public function test_get_assess_activity_chart() { $this->assertEquals('Logged in', $labels[1]); $this->assertEquals('In progress', $labels[2]); $this->assertEquals('Finished', $labels[3]); - } } diff --git a/tests/output/participant_trend_test.php b/tests/output/participant_trend_test.php index dd1bd0cd..8ecfdfd8 100644 --- a/tests/output/participant_trend_test.php +++ b/tests/output/participant_trend_test.php @@ -35,7 +35,6 @@ * @covers \local_assessfreq\output\participant_trend */ class participant_trend_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -92,16 +91,15 @@ public function setUp(): void { $track5->timecreated = $now + (60 * 5); // Insert out of order. - $trackrecords = array($track1, $track5, $track3, $track2, $track4); + $trackrecords = [$track1, $track5, $track3, $track2, $track4]; $DB->insert_records('local_assessfreq_trend', $trackrecords); - } /** * Test get quiz trend chart method. */ - public function test_get_assess_activity_chart() { + public function test_get_assess_activity_chart(): void { $participantsumamry = new participant_trend(); $result = $participantsumamry->get_participant_trend_chart(123); @@ -118,6 +116,5 @@ public function test_get_assess_activity_chart() { $this->assertEquals(2, $series[1]->get_values()[2]); $this->assertEquals(2, $series[2]->get_values()[2]); $this->assertEquals(1, $series[3]->get_values()[4]); - } } diff --git a/tests/output/quiz_user_table_test.php b/tests/output/quiz_user_table_test.php index 30591924..1368e2e8 100644 --- a/tests/output/quiz_user_table_test.php +++ b/tests/output/quiz_user_table_test.php @@ -36,7 +36,6 @@ * @covers \local_assessfreq\output\quiz_user_table */ class quiz_user_table_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -92,23 +91,24 @@ public function setUp(): void { $generator = $this->getDataGenerator(); $layout = '1,2,0,3,4,0,5,6,0'; $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); - $this->quiz1 = $generator->create_module('quiz', array( + $this->quiz1 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593910800, 'timeclose' => 1593914400, 'timelimit' => 3600, - 'layout' => $layout - )); - $this->quiz2 = $generator->create_module('quiz', array( + 'layout' => $layout, + ]); + $this->quiz2 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593997200, 'timeclose' => 1594004400, - 'timelimit' => 7200 - )); + 'timelimit' => 7200, + ]); $this->course = $course; @@ -139,7 +139,7 @@ public function setUp(): void { $override2->timeclose = 1594005000; // End late. $override2->timelimit = 7200; - $overriderecords = array($override1, $override2); + $overriderecords = [$override1, $override2]; $DB->insert_records('quiz_overrides', $overriderecords); @@ -160,7 +160,7 @@ public function setUp(): void { $record4->firstip = '10.0.0.1'; $record4->lastip = '10.0.0.1'; - $sessionrecords = array($record4); + $sessionrecords = [$record4]; $DB->insert_records('sessions', $sessionrecords); $fakeattempt = new stdClass(); @@ -187,13 +187,12 @@ public function setUp(): void { $fakeattempt->uniqueid = 39; $fakeattempt->state = \mod_quiz\quiz_attempt::FINISHED; $DB->insert_record('quiz_attempts', $fakeattempt); - } /** * Test getting table data. */ - public function test_get_table_data() { + public function test_get_table_data(): void { global $CFG; $baseurl = $CFG->wwwroot . '/local/assessfreq/dashboard_quiz.php'; @@ -230,7 +229,5 @@ public function test_get_table_data() { $this->assertEquals(1594005000, $rawdata[$this->user4->id]->timeclose); $this->assertEquals(7200, $rawdata[$this->user4->id]->timelimit); $this->assertEquals('loggedin', $rawdata[$this->user4->id]->state); - } - } diff --git a/tests/output/student_search_table_test.php b/tests/output/student_search_table_test.php index 68cc4a38..73878e06 100644 --- a/tests/output/student_search_table_test.php +++ b/tests/output/student_search_table_test.php @@ -146,78 +146,79 @@ public function setUp(): void { $generator = $this->getDataGenerator(); $layout = '1,2,0,3,4,0,5,6,0'; $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); - $this->quiz1 = $generator->create_module('quiz', array( + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); + $this->quiz1 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593910800, 'timeclose' => 1593914400, 'timelimit' => 3600, - 'layout' => $layout - )); - $this->quiz2 = $generator->create_module('quiz', array( + 'layout' => $layout, + ]); + $this->quiz2 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593997200, 'timeclose' => 1594004400, - 'timelimit' => 7200 - )); + 'timelimit' => 7200, + ]); // Start is more than one hour in the past, but end is in the future. (Should return). - $this->quiz3 = $generator->create_module('quiz', array( + $this->quiz3 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 2)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the past, but end is in the future. (Should return). - $this->quiz4 = $generator->create_module('quiz', array( + $this->quiz4 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 0.5)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is more than one hour in the future. (Should return). - $this->quiz5 = $generator->create_module('quiz', array( + $this->quiz5 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.5)), 'timeclose' => ($now + (3600 * 2)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is less that one hour in the future. (Should return). - $this->quiz6 = $generator->create_module('quiz', array( + $this->quiz6 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.25)), 'timeclose' => ($now + (3600 * 0.75)), - 'timelimit' => 1800 - )); + 'timelimit' => 1800, + ]); // Start is more than one hour in the future, end is more than one hour in the future. (Should not return). - $this->quiz7 = $generator->create_module('quiz', array( + $this->quiz7 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 2)), 'timeclose' => ($now + (3600 * 3)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start and end date of override is more than one hour in the past. (Should not be returned). - $this->quiz8 = $generator->create_module('quiz', array( + $this->quiz8 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 3)), 'timeclose' => ($now - (3600 * 2)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is more than one hour in the past, but end is less than one hour in the past. (Should return). - $this->quiz9 = $generator->create_module('quiz', array( + $this->quiz9 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 2)), 'timeclose' => ($now - (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Add questions to quiz. $quizobj = \mod_quiz\quiz_settings::create($this->quiz1->id); @@ -236,7 +237,6 @@ public function setUp(): void { if ($slot % 2 == 0) { $question = $questiongenerator->create_question('shortanswer', null, ['category' => $cat->id]); - } else { $question = $questiongenerator->create_question('essay', null, ['category' => $cat->id]); } @@ -333,9 +333,9 @@ public function setUp(): void { $override9->timeclose = ($now - (3600 * 0.5)); $override9->timelimit = 3600; - $overriderecords = array( - $override1, $override2, $override3, $override4, $override5, $override6, $override7, $override8, $override9 - ); + $overriderecords = [ + $override1, $override2, $override3, $override4, $override5, $override6, $override7, $override8, $override9, + ]; $DB->insert_records('quiz_overrides', $overriderecords); @@ -408,7 +408,7 @@ public function setUp(): void { $record6->firstip = '10.0.0.1'; $record6->lastip = '10.0.0.1'; - $sessionrecords = array($record1, $record2, $record3, $record4, $record5, $record6); + $sessionrecords = [$record1, $record2, $record3, $record4, $record5, $record6]; $DB->insert_records('sessions', $sessionrecords); $fakeattempt = new stdClass(); @@ -450,12 +450,11 @@ public function setUp(): void { $fakeattempt->uniqueid = 65; $fakeattempt->state = \mod_quiz\quiz_attempt::OVERDUE; $DB->insert_record('quiz_attempts', $fakeattempt); - } /** * Test getting table data. */ - public function test_get_table_data() { + public function test_get_table_data(): void { global $CFG; $baseurl = $CFG->wwwroot . '/local/assessfreq/dashboard_quiz.php'; diff --git a/tests/output/upcomming_quizzes_test.php b/tests/output/upcomming_quizzes_test.php index d33d4a63..a0918400 100644 --- a/tests/output/upcomming_quizzes_test.php +++ b/tests/output/upcomming_quizzes_test.php @@ -35,7 +35,6 @@ * @covers \local_assessfreq\output\upcomming_quizzes */ class upcomming_quizzes_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -121,49 +120,50 @@ public function setUp(): void { $generator = $this->getDataGenerator(); $layout = '1,2,0,3,4,0,5,6,0'; $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); // Start is more than one hour in the past, but end is in the future. (Should return). - $this->quiz3 = $generator->create_module('quiz', array( + $this->quiz3 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 2)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the past, but end is in the future. (Should return). - $this->quiz4 = $generator->create_module('quiz', array( + $this->quiz4 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 0.5)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is more than one hour in the future. (Should return). - $this->quiz5 = $generator->create_module('quiz', array( + $this->quiz5 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.5)), 'timeclose' => ($now + (3600 * 2)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is less that one hour in the future. (Should return). - $this->quiz6 = $generator->create_module('quiz', array( + $this->quiz6 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.25)), 'timeclose' => ($now + (3600 * 0.75)), - 'timelimit' => 1800 - )); + 'timelimit' => 1800, + ]); // Start is more than one hour in the future, end is more than one hour in the future. (Should not return). - $this->quiz7 = $generator->create_module('quiz', array( + $this->quiz7 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 2)), 'timeclose' => ($now + (3600 * 3)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Create some users. $user1 = $generator->create_user(); @@ -196,7 +196,7 @@ public function setUp(): void { $override2->timeclose = 1594005000; // End late. $override2->timelimit = 7200; - $overriderecords = array($override1, $override2); + $overriderecords = [$override1, $override2]; $DB->insert_records('quiz_overrides', $overriderecords); @@ -206,13 +206,12 @@ public function setUp(): void { $this->user4 = $user4; $this->user5 = $user5; $this->user6 = $user6; - } /** * Test get upcomming quiz chart. */ - public function test_get_upcomming_quizzes_chart() { + public function test_get_upcomming_quizzes_chart(): void { $now = 1594780800; $upcomming = new upcomming_quizzes(); $result = $upcomming->get_upcomming_quizzes_chart($now); @@ -233,6 +232,5 @@ public function test_get_upcomming_quizzes_chart() { $this->assertEquals(0, $participantvalues[3]); $this->assertEquals(6, $participantvalues[4]); $this->assertEquals(0, $participantvalues[5]); - } } diff --git a/tests/quiz_test.php b/tests/quiz_test.php index 96cf4d33..9dda2a09 100644 --- a/tests/quiz_test.php +++ b/tests/quiz_test.php @@ -36,7 +36,6 @@ * @covers \local_assessfreq\quiz */ class quiz_test extends \advanced_testcase { - /** * * @var stdClass $course Test course. @@ -146,78 +145,79 @@ public function setUp(): void { $generator = $this->getDataGenerator(); $layout = '1,2,0,3,4,0,5,6,0'; $course = $generator->create_course( - array('format' => 'topics', 'numsections' => 3, - 'enablecompletion' => 1), - array('createsections' => true)); - $this->quiz1 = $generator->create_module('quiz', array( + ['format' => 'topics', 'numsections' => 3, + 'enablecompletion' => 1, ], + ['createsections' => true] + ); + $this->quiz1 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593910800, 'timeclose' => 1593914400, 'timelimit' => 3600, - 'layout' => $layout - )); - $this->quiz2 = $generator->create_module('quiz', array( + 'layout' => $layout, + ]); + $this->quiz2 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => 1593997200, 'timeclose' => 1594004400, - 'timelimit' => 7200 - )); + 'timelimit' => 7200, + ]); // Start is more than one hour in the past, but end is in the future. (Should return). - $this->quiz3 = $generator->create_module('quiz', array( + $this->quiz3 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 2)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the past, but end is in the future. (Should return). - $this->quiz4 = $generator->create_module('quiz', array( + $this->quiz4 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 0.5)), 'timeclose' => ($now + (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is more than one hour in the future. (Should return). - $this->quiz5 = $generator->create_module('quiz', array( + $this->quiz5 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.5)), 'timeclose' => ($now + (3600 * 2)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is less than one hour in the future, end is less that one hour in the future. (Should return). - $this->quiz6 = $generator->create_module('quiz', array( + $this->quiz6 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 0.25)), 'timeclose' => ($now + (3600 * 0.75)), - 'timelimit' => 1800 - )); + 'timelimit' => 1800, + ]); // Start is more than one hour in the future, end is more than one hour in the future. (Should not return). - $this->quiz7 = $generator->create_module('quiz', array( + $this->quiz7 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now + (3600 * 2)), 'timeclose' => ($now + (3600 * 3)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start and end date of override is more than one hour in the past. (Should not be returned). - $this->quiz8 = $generator->create_module('quiz', array( + $this->quiz8 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 3)), 'timeclose' => ($now - (3600 * 2)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Start is more than one hour in the past, but end is less than one hour in the past. (Should return). - $this->quiz9 = $generator->create_module('quiz', array( + $this->quiz9 = $generator->create_module('quiz', [ 'course' => $course->id, 'timeopen' => ($now - (3600 * 2)), 'timeclose' => ($now - (3600 * 0.5)), - 'timelimit' => 3600 - )); + 'timelimit' => 3600, + ]); // Add questions to quiz. $quizobj = \mod_quiz\quiz_settings::create($this->quiz1->id); @@ -236,7 +236,6 @@ public function setUp(): void { if ($slot % 2 == 0) { $question = $questiongenerator->create_question('shortanswer', null, ['category' => $cat->id]); - } else { $question = $questiongenerator->create_question('essay', null, ['category' => $cat->id]); } @@ -333,9 +332,9 @@ public function setUp(): void { $override9->timeclose = ($now - (3600 * 0.5)); $override9->timelimit = 3600; - $overriderecords = array( - $override1, $override2, $override3, $override4, $override5, $override6, $override7, $override8, $override9 - ); + $overriderecords = [ + $override1, $override2, $override3, $override4, $override5, $override6, $override7, $override8, $override9, + ]; $DB->insert_records('quiz_overrides', $overriderecords); @@ -408,7 +407,7 @@ public function setUp(): void { $record6->firstip = '10.0.0.1'; $record6->lastip = '10.0.0.1'; - $sessionrecords = array($record1, $record2, $record3, $record4, $record5, $record6); + $sessionrecords = [$record1, $record2, $record3, $record4, $record5, $record6]; $DB->insert_records('sessions', $sessionrecords); $fakeattempt = new stdClass(); @@ -449,7 +448,6 @@ public function setUp(): void { $fakeattempt->uniqueid = 65; $fakeattempt->state = \mod_quiz\quiz_attempt::OVERDUE; $DB->insert_record('quiz_attempts', $fakeattempt); - } /** @@ -502,15 +500,15 @@ public function setup_quiz_tracking(int $now, int $quizid): void { $track5->timecreated = $now + (60 * 5); // Insert out of order. - $trackrecords = array($track1, $track5, $track3, $track2, $track4); + $trackrecords = [$track1, $track5, $track3, $track2, $track4]; $DB->insert_records('local_assessfreq_trend', $trackrecords); } public function setup_mock_quiz_data(): array { - $quizzes = array ( + $quizzes = [ 208002 => - (object)array( + (object)[ 'name' => 'very SPECIAL Quiz 3', 'timeopen' => '15 July 2020, 10:40 AM', 'timeclose' => '15 July 2020, 1:10 PM', @@ -521,8 +519,8 @@ public function setup_mock_quiz_data(): array { 'overrideparticipants' => 0, 'url' => 'https://www.example.com/moodle/mod/quiz/view.php?id=354002', 'types' => - array ( - ), + [ + ], 'typecount' => 0, 'questioncount' => 0, 'resultlink' => 'https://www.example.com/moodle/mod/quiz/report.php?id=354002&mode=overview', @@ -535,7 +533,7 @@ public function setup_mock_quiz_data(): array { 'timestampopen' => '1594780800', 'timestampclose' => '1594789800', 'tracking' => - (object)array( + (object)[ 'id' => '314001', 'assessid' => '208002', 'notloggedin' => '1', @@ -543,10 +541,10 @@ public function setup_mock_quiz_data(): array { 'inprogress' => '3', 'finished' => '1', 'timecreated' => '1594788300', - ), - ), + ], + ], 208003 => - (object)array( + (object)[ 'name' => 'Independent Quiz 4', 'timeopen' => '15 July 2020, 12:10 PM', 'timeclose' => '15 July 2020, 1:10 PM', @@ -557,8 +555,8 @@ public function setup_mock_quiz_data(): array { 'overrideparticipants' => 0, 'url' => 'https://www.example.com/moodle/mod/quiz/view.php?id=354003', 'types' => - array ( - ), + [ + ], 'typecount' => 0, 'questioncount' => 0, 'resultlink' => 'https://www.example.com/moodle/mod/quiz/report.php?id=354003&mode=overview', @@ -571,7 +569,7 @@ public function setup_mock_quiz_data(): array { 'timestampopen' => '1594786200', 'timestampclose' => '1594789800', 'tracking' => - (object)array( + (object)[ 'id' => '314006', 'assessid' => '208003', 'notloggedin' => '1', @@ -579,9 +577,9 @@ public function setup_mock_quiz_data(): array { 'inprogress' => '3', 'finished' => '1', 'timecreated' => '1594788300', - ), - ), - ); + ], + ], + ]; return $quizzes; } @@ -589,7 +587,7 @@ public function setup_mock_quiz_data(): array { /** * Test getting quiz override info. */ - public function test_get_quiz_override_info() { + public function test_get_quiz_override_info(): void { $quizdata = new quiz(); $context = \context_module::instance($this->quiz1->cmid); @@ -602,13 +600,12 @@ public function test_get_quiz_override_info() { $this->assertEquals(1593996000, $result->start); $this->assertEquals(1594005000, $result->end); $this->assertEquals(2, $result->users); - } /** * Test getting quiz question information. */ - public function test_get_quiz_questions() { + public function test_get_quiz_questions(): void { $quizdata = new quiz(); // We're testing a private method, so we need to setup reflector magic. @@ -619,13 +616,12 @@ public function test_get_quiz_questions() { $this->assertEquals(2, $result->typecount); $this->assertEquals(6, $result->questioncount); - } /** * Test getting quiz data. */ - public function test_get_quiz_data() { + public function test_get_quiz_data(): void { $quizdata = new quiz(); $result = $quizdata->get_quiz_data($this->quiz1->id); @@ -637,13 +633,12 @@ public function test_get_quiz_data() { $this->assertEquals(2, $result->overrideparticipants); $this->assertEquals(2, $result->typecount); $this->assertEquals(6, $result->questioncount); - } /** * Test quiz override tracking. */ - public function test_get_tracked_overrides() { + public function test_get_tracked_overrides(): void { $quizdata = new quiz(); $method = new \ReflectionMethod('\local_assessfreq\quiz', 'get_tracked_overrides'); $method->setAccessible(true); // Allow accessing of private method. @@ -662,7 +657,7 @@ public function test_get_tracked_overrides() { /** * Test quiz tracking. */ - public function test_get_tracked_quizzes() { + public function test_get_tracked_quizzes(): void { $quizdata = new quiz(); $method = new \ReflectionMethod('\local_assessfreq\quiz', 'get_tracked_quizzes'); $method->setAccessible(true); // Allow accessing of private method. @@ -681,7 +676,7 @@ public function test_get_tracked_quizzes() { /** * Test quiz tracking with overrides. */ - public function test_get_tracked_quizzes_with_overrides() { + public function test_get_tracked_quizzes_with_overrides(): void { global $DB; $now = 1594788000; @@ -715,20 +710,19 @@ public function test_get_tracked_quizzes_with_overrides() { $this->assertEquals(($now + (3600 * 0.5)), $result[$this->quiz4->id]->timeclose); $this->assertCount(5, $result); - } /** * Test getting logged in users. */ - public function test_get_loggedin_users() { - $userids = array( + public function test_get_loggedin_users(): void { + $userids = [ $this->user1->id, $this->user2->id, $this->user3->id, $this->user4->id, ($this->user4->id + 123), - ); + ]; $quizdata = new quiz(); $method = new \ReflectionMethod('\local_assessfreq\quiz', 'get_loggedin_users'); @@ -743,7 +737,7 @@ public function test_get_loggedin_users() { /** * Test quiz tracking with overrides. */ - public function test_get_quiz_attempts() { + public function test_get_quiz_attempts(): void { $quizdata = new quiz(); $method = new \ReflectionMethod('\local_assessfreq\quiz', 'get_quiz_attempts'); @@ -758,7 +752,7 @@ public function test_get_quiz_attempts() { /** * Test processing quiz tracking. */ - public function test_process_quiz_tracking() { + public function test_process_quiz_tracking(): void { global $DB; $now = 1594788000; @@ -784,7 +778,7 @@ public function test_process_quiz_tracking() { /** * Test processing quiz tracking . */ - public function test_get_quiz_tracking() { + public function test_get_quiz_tracking(): void { $now = 1594788000; $this->setup_quiz_tracking($now, $this->quiz1->id); @@ -796,13 +790,12 @@ public function test_get_quiz_tracking() { $this->assertEquals($now + (60 * 3), array_pop($trackingdata)->timecreated); $this->assertEquals($now + (60 * 2), array_pop($trackingdata)->timecreated); $this->assertEquals($now + (60 * 1), array_pop($trackingdata)->timecreated); - } /** * Test getting in progress quiz counts. */ - public function test_get_inprogress_counts() { + public function test_get_inprogress_counts(): void { $now = 1594788000; $this->setup_quiz_tracking($now, $this->quiz3->id); $this->setup_quiz_tracking($now, $this->quiz4->id); @@ -812,26 +805,24 @@ public function test_get_inprogress_counts() { $this->assertEquals(2, $result['assessments']); $this->assertEquals(6, $result['participants']); - } /** * Test getting finished quizzes. */ - public function test_get_quizzes_finished() { + public function test_get_quizzes_finished(): void { $quizdata = new quiz(); $now = 1594788000; $result = $quizdata->get_quiz_summaries($now); $this->assertCount(1, $result['finished'][$now - HOURSECS]); - } /** * Test getting in progress quizzes. */ - public function test_get_quizzes_inprogress() { + public function test_get_quizzes_inprogress(): void { $now = 1594788000; $this->setup_quiz_tracking($now, $this->quiz3->id); $this->setup_quiz_tracking($now, $this->quiz4->id); @@ -844,13 +835,12 @@ public function test_get_quizzes_inprogress() { $this->assertGreaterThan($now, $result['inprogress'][$this->quiz3->id]->timestampclose); $this->assertLessThan($now, $result['inprogress'][$this->quiz4->id]->timestampopen); $this->assertGreaterThan($now, $result['inprogress'][$this->quiz4->id]->timestampclose); - } /** * Test getting upcomming quizzes. */ - public function test_get_quizzes_upcomming() { + public function test_get_quizzes_upcomming(): void { $quizdata = new quiz(); $now = 1594780800; @@ -868,13 +858,12 @@ public function test_get_quizzes_upcomming() { $this->assertCount(0, $result['upcomming'][$now + HOURSECS]); $this->assertCount(1, $result['upcomming'][$now + (HOURSECS * 2)]); $this->assertCount(0, $result['upcomming'][$now + (HOURSECS * 3)]); - } /** * Test filtering quizzes. */ - public function test_filter_quizzes() { + public function test_filter_quizzes(): void { // Mock data. $quizzes = $this->setup_mock_quiz_data(); @@ -894,7 +883,7 @@ public function test_filter_quizzes() { /** * Test filtering quizzes with pages. */ - public function test_filter_quizzes_paging() { + public function test_filter_quizzes_paging(): void { // Mock data. $quizzes = $this->setup_mock_quiz_data(); @@ -916,7 +905,7 @@ public function test_filter_quizzes_paging() { /** * Test filtering quizzes with pages. */ - public function test_sort_quizzes() { + public function test_sort_quizzes(): void { // Mock data. $quizzes = $this->setup_mock_quiz_data(); @@ -936,6 +925,5 @@ public function test_sort_quizzes() { $sorted = \local_assessfreq\utils::sort($quizzes, $sorton, 'desc'); $this->assertEquals('Test course 1', $sorted[208002]->coursefullname); - } } diff --git a/version.php b/version.php index 074d19d0..8ca5e353 100644 --- a/version.php +++ b/version.php @@ -27,7 +27,6 @@ $plugin->component = 'local_assessfreq'; $plugin->release = '2023102700'; $plugin->version = 2023102700; -$plugin->requires = 2023042400; // Requires 4.2 -$plugin->supports = [402, 402]; +$plugin->requires = 2023042400; // Requires 4.2. +$plugin->supported = [402, 402]; $plugin->maturity = MATURITY_STABLE; -