first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,355 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains a class definition for the LineItem resource
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @author Dirk Singels, Diego del Blanco, Claude Vervoort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace ltiservice_gradebookservices\local\resources;
use ltiservice_gradebookservices\local\service\gradebookservices;
use mod_lti\local\ltiservice\resource_base;
defined('MOODLE_INTERNAL') || die();
/**
* A resource implementing LineItem.
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class lineitem extends resource_base {
/**
* Class constructor.
*
* @param gradebookservices $service Service instance
*/
public function __construct($service) {
parent::__construct($service);
$this->id = 'LineItem.item';
$this->template = '/{context_id}/lineitems/{item_id}/lineitem';
$this->variables[] = 'LineItem.url';
$this->formats[] = 'application/vnd.ims.lis.v2.lineitem+json';
$this->methods[] = self::HTTP_GET;
$this->methods[] = self::HTTP_PUT;
$this->methods[] = self::HTTP_DELETE;
}
/**
* Execute the request for this resource.
*
* @param \mod_lti\local\ltiservice\response $response Response object for this request.
*/
public function execute($response) {
global $CFG, $DB;
$params = $this->parse_template();
$contextid = $params['context_id'];
$itemid = $params['item_id'];
$isget = $response->get_request_method() === self::HTTP_GET;
// We will receive typeid when working with LTI 1.x, if not then we are in LTI 2.
$typeid = optional_param('type_id', null, PARAM_INT);
$scopes = array(gradebookservices::SCOPE_GRADEBOOKSERVICES_LINEITEM);
if ($response->get_request_method() === self::HTTP_GET) {
$scopes[] = gradebookservices::SCOPE_GRADEBOOKSERVICES_LINEITEM_READ;
}
try {
if (!$this->check_tool($typeid, $response->get_request_data(), $scopes)) {
throw new \Exception(null, 401);
}
$typeid = $this->get_service()->get_type()->id;
if (!($course = $DB->get_record('course', array('id' => $contextid), 'id', IGNORE_MISSING))) {
throw new \Exception("Not Found: Course {$contextid} doesn't exist", 404);
}
if (!$this->get_service()->is_allowed_in_context($typeid, $course->id)) {
throw new \Exception('Not allowed in context', 403);
}
if (!$DB->record_exists('grade_items', array('id' => $itemid))) {
throw new \Exception("Not Found: Grade item {$itemid} doesn't exist", 404);
}
$item = $this->get_service()->get_lineitem($contextid, $itemid, $typeid);
if ($item === false) {
throw new \Exception('Line item does not exist', 404);
}
require_once($CFG->libdir.'/gradelib.php');
switch ($response->get_request_method()) {
case self::HTTP_GET:
$this->get_request($response, $item, $typeid);
break;
case self::HTTP_PUT:
$json = $this->process_put_request($response->get_request_data(), $item, $typeid);
$response->set_body($json);
$response->set_code(200);
break;
case self::HTTP_DELETE:
$this->process_delete_request($item);
$response->set_code(204);
break;
}
} catch (\Exception $e) {
$response->set_code($e->getCode());
$response->set_reason($e->getMessage());
}
}
/**
* Process a GET request.
*
* @param \mod_lti\local\ltiservice\response $response Response object for this request.
* @param object $item Grade item instance.
* @param string $typeid Tool Type Id
*/
private function get_request($response, $item, $typeid) {
$response->set_content_type($this->formats[0]);
$lineitem = gradebookservices::item_for_json($item, substr(parent::get_endpoint(),
0, strrpos(parent::get_endpoint(), "/", -10)), $typeid);
$response->set_body(json_encode($lineitem));
}
/**
* Process a PUT request.
*
* @param string $body PUT body
* @param \ltiservice_gradebookservices\local\resources\lineitem $olditem Grade item instance
* @param string $typeid Tool Type Id
*
* @return string
* @throws \Exception
*/
private function process_put_request($body, $olditem, $typeid) {
global $DB;
$json = json_decode($body);
if (empty($json) ||
!isset($json->scoreMaximum) ||
!isset($json->label)) {
throw new \Exception(null, 400);
}
$item = \grade_item::fetch(array('id' => $olditem->id, 'courseid' => $olditem->courseid));
$gbs = gradebookservices::find_ltiservice_gradebookservice_for_lineitem($olditem->id);
$updategradeitem = false;
$rescalegrades = false;
$oldgrademax = grade_floatval($item->grademax);
$upgradegradebookservices = false;
if ($item->itemname !== $json->label) {
$updategradeitem = true;
}
$item->itemname = $json->label;
if (!is_numeric($json->scoreMaximum)) {
throw new \Exception(null, 400);
} else {
if (grade_floats_different($oldgrademax,
grade_floatval($json->scoreMaximum))) {
$updategradeitem = true;
$rescalegrades = true;
}
$item->grademax = grade_floatval($json->scoreMaximum);
}
if ($gbs) {
$resourceid = (isset($json->resourceId)) ? $json->resourceId : '';
$tag = (isset($json->tag)) ? $json->tag : '';
if ($gbs->tag !== $tag || $gbs->resourceid !== $resourceid) {
$upgradegradebookservices = true;
}
$gbs->tag = $tag;
$gbs->resourceid = $resourceid;
$incomingurl = null;
$incomingparams = null;
if (isset($json->submissionReview)) {
$incomingurl = $json->submissionReview->url ?? 'DEFAULT';
if (isset($json->submissionReview->custom)) {
$incomingparams = params_to_string($json->submissionReview->custom);
}
}
if ($gbs->subreviewurl ?? null !== $incomingurl || $gbs->subreviewparams ?? null !== $incomingparams) {
$upgradegradebookservices = true;
$gbs->subreviewurl = $incomingurl;
$gbs->subreviewparams = $incomingparams;
}
}
$ltilinkid = null;
if (isset($json->resourceLinkId)) {
if (is_numeric($json->resourceLinkId)) {
$ltilinkid = $json->resourceLinkId;
if ($gbs) {
if (intval($gbs->ltilinkid) !== intval($json->resourceLinkId)) {
$gbs->ltilinkid = $json->resourceLinkId;
$upgradegradebookservices = true;
}
} else {
if (intval($item->iteminstance) !== intval($json->resourceLinkId)) {
$item->iteminstance = intval($json->resourceLinkId);
$updategradeitem = true;
}
}
} else {
throw new \Exception(null, 400);
}
} else if (isset($json->ltiLinkId)) {
if (is_numeric($json->ltiLinkId)) {
$ltilinkid = $json->ltiLinkId;
if ($gbs) {
if (intval($gbs->ltilinkid) !== intval($json->ltiLinkId)) {
$gbs->ltilinkid = $json->ltiLinkId;
$upgradegradebookservices = true;
}
} else {
if (intval($item->iteminstance) !== intval($json->ltiLinkId)) {
$item->iteminstance = intval($json->ltiLinkId);
$updategradeitem = true;
}
}
} else {
throw new \Exception(null, 400);
}
}
if ($ltilinkid != null) {
if (is_null($typeid)) {
if (!gradebookservices::check_lti_id($ltilinkid, $item->courseid,
$this->get_service()->get_tool_proxy()->id)) {
throw new \Exception(null, 403);
}
} else {
if (!gradebookservices::check_lti_1x_id($ltilinkid, $item->courseid,
$typeid)) {
throw new \Exception(null, 403);
}
}
}
if ($updategradeitem) {
if (!$item->update('mod/ltiservice_gradebookservices')) {
throw new \Exception(null, 500);
}
if ($rescalegrades) {
$item->rescale_grades_keep_percentage(0, $oldgrademax, 0, $item->grademax);
}
}
$lineitem = new lineitem($this->get_service());
$endpoint = $lineitem->get_endpoint();
if ($upgradegradebookservices) {
if (is_null($typeid)) {
$toolproxyid = $this->get_service()->get_tool_proxy()->id;
$baseurl = null;
} else {
$toolproxyid = null;
$baseurl = lti_get_type_type_config($typeid)->lti_toolurl;
}
$DB->update_record('ltiservice_gradebookservices', (object)array(
'id' => $gbs->id,
'gradeitemid' => $gbs->gradeitemid,
'courseid' => $gbs->courseid,
'toolproxyid' => $toolproxyid,
'typeid' => $typeid,
'baseurl' => $baseurl,
'ltilinkid' => $ltilinkid,
'resourceid' => $resourceid,
'tag' => $gbs->tag,
'subreviewurl' => $gbs->subreviewurl,
'subreviewparams' => $gbs->subreviewparams
));
}
if (is_null($typeid)) {
$id = "{$endpoint}";
$json->id = $id;
} else {
$id = "{$endpoint}?type_id={$typeid}";
$json->id = $id;
}
return json_encode($json, JSON_UNESCAPED_SLASHES);
}
/**
* Process a DELETE request.
*
* @param \ltiservice_gradebookservices\local\resources\lineitem $item Grade item instance
* @throws \Exception
*/
private function process_delete_request($item) {
global $DB;
$gradeitem = \grade_item::fetch(array('id' => $item->id));
if (($gbs = gradebookservices::find_ltiservice_gradebookservice_for_lineitem($item->id)) == false) {
throw new \Exception(null, 403);
}
if (!$gradeitem->delete('mod/ltiservice_gradebookservices')) {
throw new \Exception(null, 500);
} else {
$sqlparams = array();
$sqlparams['id'] = $gbs->id;
if (!$DB->delete_records('ltiservice_gradebookservices', $sqlparams)) {
throw new \Exception(null, 500);
}
}
}
/**
* Parse a value for custom parameter substitution variables.
*
* @param string $value String to be parsed
*
* @return string
*/
public function parse_value($value) {
global $COURSE, $CFG;
if (strpos($value, '$LineItem.url') !== false) {
$resolved = '';
require_once($CFG->libdir . '/gradelib.php');
$this->params['context_id'] = $COURSE->id;
if ($tool = $this->get_service()->get_type()) {
$this->params['tool_code'] = $tool->id;
}
$id = optional_param('id', 0, PARAM_INT); // Course Module ID.
if (empty($id)) {
$hint = optional_param('lti_message_hint', "", PARAM_TEXT);
if ($hint) {
$hintdec = json_decode($hint);
if (isset($hintdec->cmid)) {
$id = $hintdec->cmid;
}
}
}
if (!empty($id)) {
$cm = get_coursemodule_from_id('lti', $id, 0, false, MUST_EXIST);
$id = $cm->instance;
$item = grade_get_grades($COURSE->id, 'mod', 'lti', $id);
if ($item && $item->items) {
$this->params['item_id'] = $item->items[0]->id;
$resolved = parent::get_endpoint();
$resolved .= "?type_id={$tool->id}";
}
}
$value = str_replace('$LineItem.url', $resolved, $value);
}
return $value;
}
}
@@ -0,0 +1,302 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains a class definition for the LineItem container resource
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @author Dirk Singels, Diego del Blanco, Claude Vervoort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace ltiservice_gradebookservices\local\resources;
use ltiservice_gradebookservices\local\service\gradebookservices;
use mod_lti\local\ltiservice\resource_base;
defined('MOODLE_INTERNAL') || die();
/**
* A resource implementing LineItem container.
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class lineitems extends resource_base {
/**
* Class constructor.
*
* @param \ltiservice_gradebookservices\local\service\gradebookservices $service Service instance
*/
public function __construct($service) {
parent::__construct($service);
$this->id = 'LineItem.collection';
$this->template = '/{context_id}/lineitems';
$this->variables[] = 'LineItems.url';
$this->formats[] = 'application/vnd.ims.lis.v2.lineitemcontainer+json';
$this->formats[] = 'application/vnd.ims.lis.v2.lineitem+json';
$this->methods[] = self::HTTP_GET;
$this->methods[] = self::HTTP_POST;
}
/**
* Execute the request for this resource.
*
* @param \mod_lti\local\ltiservice\response $response Response object for this request.
*/
public function execute($response) {
global $DB;
$params = $this->parse_template();
$contextid = $params['context_id'];
$isget = $response->get_request_method() === self::HTTP_GET;
if ($isget) {
$contenttype = $response->get_accept();
} else {
$contenttype = $response->get_content_type();
}
$container = empty($contenttype) || ($contenttype === $this->formats[0]);
// We will receive typeid when working with LTI 1.x, if not then we are in LTI 2.
$typeid = optional_param('type_id', null, PARAM_INT);
$scopes = array(gradebookservices::SCOPE_GRADEBOOKSERVICES_LINEITEM);
if ($response->get_request_method() === self::HTTP_GET) {
$scopes[] = gradebookservices::SCOPE_GRADEBOOKSERVICES_LINEITEM_READ;
}
try {
if (!$this->check_tool($typeid, $response->get_request_data(), $scopes)) {
throw new \Exception(null, 401);
}
$typeid = $this->get_service()->get_type()->id;
if (empty($contextid) || !($container ^ ($response->get_request_method() === self::HTTP_POST)) ||
(!empty($contenttype) && !in_array($contenttype, $this->formats))) {
throw new \Exception('No context or unsupported content type', 400);
}
if (!($course = $DB->get_record('course', array('id' => $contextid), 'id', IGNORE_MISSING))) {
throw new \Exception("Not Found: Course {$contextid} doesn't exist", 404);
}
if (!$this->get_service()->is_allowed_in_context($typeid, $course->id)) {
throw new \Exception('Not allowed in context', 403);
}
if ($response->get_request_method() !== self::HTTP_POST) {
$resourceid = optional_param('resource_id', null, PARAM_TEXT);
$ltilinkid = optional_param('resource_link_id', null, PARAM_TEXT);
if (is_null($ltilinkid)) {
$ltilinkid = optional_param('lti_link_id', null, PARAM_TEXT);
}
$tag = optional_param('tag', null, PARAM_TEXT);
$limitnum = optional_param('limit', 0, PARAM_INT);
$limitfrom = optional_param('from', 0, PARAM_INT);
$itemsandcount = $this->get_service()->get_lineitems($contextid, $resourceid, $ltilinkid, $tag, $limitfrom,
$limitnum, $typeid);
$items = $itemsandcount[1];
$totalcount = $itemsandcount[0];
$json = $this->get_json_for_get_request($items, $resourceid, $ltilinkid, $tag, $limitfrom,
$limitnum, $totalcount, $typeid, $response);
$response->set_content_type($this->formats[0]);
} else {
$json = $this->get_json_for_post_request($response->get_request_data(), $contextid, $typeid);
$response->set_code(201);
$response->set_content_type($this->formats[1]);
}
$response->set_body($json);
} catch (\Exception $e) {
$response->set_code($e->getCode());
$response->set_reason($e->getMessage());
}
}
/**
* Generate the JSON for a GET request.
*
* @param array $items Array of lineitems
* @param string $resourceid Resource identifier used for filtering, may be null
* @param string $ltilinkid Resource Link identifier used for filtering, may be null
* @param string $tag Tag identifier used for filtering, may be null
* @param int $limitfrom Offset of the first line item to return
* @param int $limitnum Maximum number of line items to return, ignored if zero or less
* @param int $totalcount Number of total lineitems before filtering for paging
* @param int $typeid Maximum number of line items to return, ignored if zero or less
* @param \mod_lti\local\ltiservice\response $response
* @return string
*/
private function get_json_for_get_request($items, $resourceid, $ltilinkid,
$tag, $limitfrom, $limitnum, $totalcount, $typeid, $response) {
$firstpage = null;
$nextpage = null;
$prevpage = null;
$lastpage = null;
if (isset($limitnum) && $limitnum > 0) {
if ($limitfrom >= $totalcount || $limitfrom < 0) {
$outofrange = true;
} else {
$outofrange = false;
}
$limitprev = $limitfrom - $limitnum >= 0 ? $limitfrom - $limitnum : 0;
$limitcurrent = $limitfrom;
$limitlast = $totalcount - $limitnum + 1 >= 0 ? $totalcount - $limitnum + 1 : 0;
$limitfrom += $limitnum;
$baseurl = new \moodle_url($this->get_endpoint());
if (isset($resourceid)) {
$baseurl->param('resource_id', $resourceid);
}
if (isset($ltilinkid)) {
$baseurl->param('resource_link_id', $ltilinkid);
}
if (isset($tag)) {
$baseurl->param('tag', $tag);
}
if (is_null($typeid)) {
$baseurl->param('limit', $limitnum);
if (($limitfrom <= $totalcount - 1) && (!$outofrange)) {
$nextpage = new \moodle_url($baseurl, ['from' => $limitfrom]);
}
$firstpage = new \moodle_url($baseurl, ['from' => 0]);
$canonicalpage = new \moodle_url($baseurl, ['from' => $limitcurrent]);
$lastpage = new \moodle_url($baseurl, ['from' > $limitlast]);
if (($limitcurrent > 0) && (!$outofrange)) {
$prevpage = new \moodle_url($baseurl, ['from' => $limitprev]);
}
} else {
$baseurl->params(['type_id' => $typeid, 'limit' => $limitnum]);
if (($limitfrom <= $totalcount - 1) && (!$outofrange)) {
$nextpage = new \moodle_url($baseurl, ['from' => $limitfrom]);
}
$firstpage = new \moodle_url($baseurl, ['from' => 0]);
$canonicalpage = new \moodle_url($baseurl, ['from' => $limitcurrent]);
$lastpage = new \moodle_url($baseurl, ['from' => $limitlast]);
if (($limitcurrent > 0) && (!$outofrange)) {
$prevpage = new \moodle_url($baseurl, ['from' => $limitprev]);
}
}
}
$jsonitems = [];
$endpoint = parent::get_endpoint();
foreach ($items as $item) {
array_push($jsonitems, gradebookservices::item_for_json($item, $endpoint, $typeid));
}
if (isset($canonicalpage) && ($canonicalpage)) {
$links = 'Link: <' . $firstpage->out() . '>; rel=“first”';
if (!is_null($prevpage)) {
$links .= ', <' . $prevpage->out() . '>; rel=“prev”';
}
$links .= ', <' . $canonicalpage->out(). '>; rel=“canonical”';
if (!is_null($nextpage)) {
$links .= ', <' . $nextpage->out() . '>; rel=“next”';
}
$links .= ', <' . $lastpage->out() . '>; rel=“last”';
$response->add_additional_header($links);
}
return json_encode($jsonitems);
}
/**
* Generate the JSON for a POST request.
*
* @param string $body POST body
* @param string $contextid Course ID
* @param string $typeid
*
* @return string
* @throws \Exception
*/
private function get_json_for_post_request($body, $contextid, $typeid) {
global $CFG, $DB;
$json = json_decode($body);
if (empty($json) ||
!isset($json->scoreMaximum) ||
!isset($json->label)) {
throw new \Exception('No label or Score Maximum', 400);
}
if (is_numeric($json->scoreMaximum)) {
$max = $json->scoreMaximum;
} else {
throw new \Exception(null, 400);
}
require_once($CFG->libdir.'/gradelib.php');
$resourceid = (isset($json->resourceId)) ? $json->resourceId : '';
$ltilinkid = (isset($json->resourceLinkId)) ? $json->resourceLinkId : null;
if ($ltilinkid == null) {
$ltilinkid = (isset($json->ltiLinkId)) ? $json->ltiLinkId : null;
}
if ($ltilinkid != null) {
if (is_null($typeid)) {
if (!gradebookservices::check_lti_id($ltilinkid, $contextid, $this->get_service()->get_tool_proxy()->id)) {
throw new \Exception(null, 403);
}
} else {
if (!gradebookservices::check_lti_1x_id($ltilinkid, $contextid, $typeid)) {
throw new \Exception(null, 403);
}
}
}
$tag = (isset($json->tag)) ? $json->tag : '';
if (is_null($typeid)) {
$toolproxyid = $this->get_service()->get_tool_proxy()->id;
$baseurl = null;
} else {
$toolproxyid = null;
$baseurl = lti_get_type_type_config($typeid)->lti_toolurl;
}
$gradebookservices = new gradebookservices();
$id = $gradebookservices->add_standalone_lineitem($contextid, $json->label,
$max, $baseurl, $ltilinkid, $resourceid, $tag, $typeid, $toolproxyid);
if (is_null($typeid)) {
$json->id = parent::get_endpoint() . "/{$id}/lineitem";
} else {
$json->id = parent::get_endpoint() . "/{$id}/lineitem?type_id={$typeid}";
}
return json_encode($json, JSON_UNESCAPED_SLASHES);
}
/**
* Parse a value for custom parameter substitution variables.
*
* @param string $value String to be parsed
*
* @return string
*/
public function parse_value($value) {
global $COURSE;
if (strpos($value, '$LineItems.url') !== false) {
$this->params['context_id'] = $COURSE->id;
$query = '';
if (($tool = $this->get_service()->get_type())) {
$query = "?type_id={$tool->id}";
}
$value = str_replace('$LineItems.url', parent::get_endpoint() . $query, $value);
}
return $value;
}
}
@@ -0,0 +1,272 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains a class definition for the LISResults container resource
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @author Dirk Singels, Diego del Blanco, Claude Vervoort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace ltiservice_gradebookservices\local\resources;
use ltiservice_gradebookservices\local\service\gradebookservices;
use mod_lti\local\ltiservice\resource_base;
defined('MOODLE_INTERNAL') || die();
/**
* A resource implementing LISResult container.
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class results extends resource_base {
/**
* Class constructor.
*
* @param \ltiservice_gradebookservices\local\service\gradebookservices $service Service instance
*/
public function __construct($service) {
parent::__construct($service);
$this->id = 'Result.collection';
$this->template = '/{context_id}/lineitems/{item_id}/lineitem/results';
$this->variables[] = 'Results.url';
$this->formats[] = 'application/vnd.ims.lis.v2.resultcontainer+json';
$this->methods[] = 'GET';
}
/**
* Execute the request for this resource.
*
* @param \mod_lti\local\ltiservice\response $response Response object for this request.
*/
public function execute($response) {
global $CFG, $DB;
$params = $this->parse_template();
$contextid = $params['context_id'];
$itemid = $params['item_id'];
$isget = $response->get_request_method() === self::HTTP_GET;
// We will receive typeid when working with LTI 1.x, if not the we are in LTI 2.
$typeid = optional_param('type_id', null, PARAM_INT);
$scope = gradebookservices::SCOPE_GRADEBOOKSERVICES_RESULT_READ;
try {
if (!$this->check_tool($typeid, $response->get_request_data(), array($scope))) {
throw new \Exception(null, 401);
}
$typeid = $this->get_service()->get_type()->id;
if (!($course = $DB->get_record('course', array('id' => $contextid), 'id', IGNORE_MISSING))) {
throw new \Exception("Not Found: Course {$contextid} doesn't exist", 404);
}
if (!$this->get_service()->is_allowed_in_context($typeid, $course->id)) {
throw new \Exception('Not allowed in context', 403);
}
if (!$DB->record_exists('grade_items', array('id' => $itemid))) {
throw new \Exception("Not Found: Grade item {$itemid} doesn't exist", 404);
}
$item = $this->get_service()->get_lineitem($contextid, $itemid, $typeid);
if ($item === false) {
throw new \Exception('Line item does not exist', 404);
}
$gbs = gradebookservices::find_ltiservice_gradebookservice_for_lineitem($itemid);
$ltilinkid = null;
if (isset($item->iteminstance)) {
$ltilinkid = $item->iteminstance;
} else if ($gbs && isset($gbs->ltilinkid)) {
$ltilinkid = $gbs->ltilinkid;
}
if ($ltilinkid != null) {
if (is_null($typeid)) {
if (isset($item->iteminstance) && (!gradebookservices::check_lti_id($ltilinkid, $item->courseid,
$this->get_service()->get_tool_proxy()->id))) {
$response->set_code(403);
$response->set_reason("Invalid LTI id supplied.");
return;
}
} else {
if (isset($item->iteminstance) && (!gradebookservices::check_lti_1x_id($ltilinkid, $item->courseid,
$typeid))) {
$response->set_code(403);
$response->set_reason("Invalid LTI id supplied.");
return;
}
}
}
require_once($CFG->libdir.'/gradelib.php');
switch ($response->get_request_method()) {
case 'GET':
$useridfilter = optional_param('user_id', 0, PARAM_INT);
$limitnum = optional_param('limit', 0, PARAM_INT);
$limitfrom = optional_param('from', 0, PARAM_INT);
$typeid = optional_param('type_id', null, PARAM_TEXT);
$json = $this->get_json_for_get_request($item->id, $limitfrom, $limitnum,
$useridfilter, $typeid, $response);
$response->set_content_type($this->formats[0]);
$response->set_body($json);
break;
default: // Should not be possible.
$response->set_code(405);
$response->set_reason("Invalid request method specified.");
return;
}
$response->set_body($json);
} catch (\Exception $e) {
$response->set_code($e->getCode());
$response->set_reason($e->getMessage());
}
}
/**
* Generate the JSON for a GET request.
*
* @param int $itemid Grade item instance ID
* @param int $limitfrom Offset for the first result to include in this paged set
* @param int $limitnum Maximum number of results to include in the response, ignored if zero
* @param int $useridfilter The user id to filter the results.
* @param int $typeid Lti tool typeid (or null)
* @param \mod_lti\local\ltiservice\response $response The response element needed to add a header.
*
* @return string
*/
private function get_json_for_get_request($itemid, $limitfrom, $limitnum, $useridfilter, $typeid, $response) {
if ($useridfilter > 0) {
$grades = \grade_grade::fetch_all(array('itemid' => $itemid, 'userid' => $useridfilter));
} else {
$grades = \grade_grade::fetch_all(array('itemid' => $itemid));
}
$firstpage = null;
$nextpage = null;
$prevpage = null;
$lastpage = null;
if ($grades && isset($limitnum) && $limitnum > 0) {
// Since we only display grades that have been modified, we need to filter first in order to support
// paging.
$resultgrades = array_filter($grades, function ($grade) {
return !empty($grade->timemodified);
});
// We save the total count to calculate the last page.
$totalcount = count($resultgrades);
// We slice to the requested item offset to insure proper item is always first, and we always return
// first pageset of any remaining items.
$grades = array_slice($resultgrades, $limitfrom);
if (count($grades) > 0) {
$pagedgrades = array_chunk($grades, $limitnum);
$pageset = 0;
$grades = $pagedgrades[$pageset];
}
if ($limitfrom >= $totalcount || $limitfrom < 0) {
$outofrange = true;
} else {
$outofrange = false;
}
$limitprev = $limitfrom - $limitnum >= 0 ? $limitfrom - $limitnum : 0;
$limitcurrent = $limitfrom;
$limitlast = $totalcount - $limitnum + 1 >= 0 ? $totalcount - $limitnum + 1 : 0;
$limitfrom += $limitnum;
$baseurl = new \moodle_url($this->get_endpoint());
if (is_null($typeid)) {
$baseurl->param('limit', $limitnum);
if (($limitfrom <= $totalcount - 1) && (!$outofrange)) {
$nextpage = new \moodle_url($baseurl, ['from' => $limitfrom]);
}
$firstpage = new \moodle_url($baseurl, ['from' => 0]);
$canonicalpage = new \moodle_url($baseurl, ['from' => $limitcurrent]);
$lastpage = new \moodle_url($baseurl, ['from' => $limitlast]);
if (($limitcurrent > 0) && (!$outofrange)) {
$prevpage = new \moodle_url($baseurl, ['from' => $limitprev]);
}
} else {
$baseurl->params(['type_id' => $typeid, 'limit' => $limitnum]);
if (($limitfrom <= $totalcount - 1) && (!$outofrange)) {
$nextpage = new \moodle_url($baseurl, ['from' => $limitfrom]);
}
$firstpage = new \moodle_url($baseurl, ['from' => 0]);
$canonicalpage = new \moodle_url($baseurl, ['from' => $limitcurrent]);
if (($limitcurrent > 0) && (!$outofrange)) {
$prevpage = new \moodle_url($baseurl, ['from' => $limitprev]);
}
}
}
$jsonresults = [];
$lineitem = new lineitem($this->get_service());
$endpoint = $lineitem->get_endpoint();
if ($grades) {
foreach ($grades as $grade) {
if (!empty($grade->timemodified)) {
array_push($jsonresults, gradebookservices::result_for_json($grade, $endpoint, $typeid));
}
}
}
if (isset($canonicalpage) && ($canonicalpage)) {
$links = 'Link: <' . $firstpage->out() . '>; rel=“first”';
if (!is_null($prevpage)) {
$links .= ', <' . $prevpage->out() . '>; rel=“prev”';
}
$links .= ', <' . $canonicalpage->out() . '>; rel=“canonical”';
if (!is_null($nextpage)) {
$links .= ', <' . $nextpage->out() . '>; rel=“next”';
}
$links .= ', <' . $lastpage->out() . '>; rel=“last”';
$response->add_additional_header($links);
}
return json_encode($jsonresults);
}
/**
* Parse a value for custom parameter substitution variables.
*
* @param string $value String to be parsed
*
* @return string
*/
public function parse_value($value) {
global $COURSE, $CFG;
if (strpos($value, '$Results.url') !== false) {
require_once($CFG->libdir . '/gradelib.php');
$resolved = '';
$this->params['context_id'] = $COURSE->id;
$id = optional_param('id', 0, PARAM_INT); // Course Module ID.
if (!empty($id)) {
$cm = get_coursemodule_from_id('lti', $id, 0, false, MUST_EXIST);
$id = $cm->instance;
$item = grade_get_grades($COURSE->id, 'mod', 'lti', $id);
if ($item && $item->items) {
$this->params['item_id'] = $item->items[0]->id;
$resolved = parent::get_endpoint();
}
}
$value = str_replace('$Results.url', $resolved, $value);
}
return $value;
}
}
@@ -0,0 +1,239 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains a class definition for the LISResult container resource
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @author Dirk Singels, Diego del Blanco, Claude Vervoort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace ltiservice_gradebookservices\local\resources;
use ltiservice_gradebookservices\local\service\gradebookservices;
use mod_lti\local\ltiservice\resource_base;
defined('MOODLE_INTERNAL') || die();
/**
* A resource implementing LISResult container.
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class scores extends resource_base {
/**
* Class constructor.
*
* @param \ltiservice_gradebookservices\local\service\gradebookservices $service Service instance
*/
public function __construct($service) {
parent::__construct($service);
$this->id = 'Score.collection';
$this->template = '/{context_id}/lineitems/{item_id}/lineitem/scores';
$this->variables[] = 'Scores.url';
$this->formats[] = 'application/vnd.ims.lis.v1.scorecontainer+json';
$this->formats[] = 'application/vnd.ims.lis.v1.score+json';
$this->methods[] = 'POST';
}
/**
* Execute the request for this resource.
*
* @param \mod_lti\local\ltiservice\response $response Response object for this request.
*/
public function execute($response) {
global $CFG, $DB;
$params = $this->parse_template();
$contextid = $params['context_id'];
$itemid = $params['item_id'];
// GET is disabled by the moment, but we have the code ready
// for a future implementation.
$isget = $response->get_request_method() === 'GET';
if ($isget) {
$contenttype = $response->get_accept();
} else {
$contenttype = $response->get_content_type();
}
$container = empty($contenttype) || ($contenttype === $this->formats[0]);
// We will receive typeid when working with LTI 1.x, if not the we are in LTI 2.
$typeid = optional_param('type_id', null, PARAM_ALPHANUM);
$scope = gradebookservices::SCOPE_GRADEBOOKSERVICES_SCORE;
try {
if (!$this->check_tool($typeid, $response->get_request_data(), array($scope))) {
throw new \Exception(null, 401);
}
$typeid = $this->get_service()->get_type()->id;
if (empty($contextid) || !($container ^ ($response->get_request_method() === self::HTTP_POST)) ||
(!empty($contenttype) && !in_array($contenttype, $this->formats))) {
throw new \Exception('No context or unsupported content type', 400);
}
if (!($course = $DB->get_record('course', array('id' => $contextid), 'id', IGNORE_MISSING))) {
throw new \Exception("Not Found: Course {$contextid} doesn't exist", 404);
}
if (!$this->get_service()->is_allowed_in_context($typeid, $course->id)) {
throw new \Exception('Not allowed in context', 403);
}
if (!$DB->record_exists('grade_items', array('id' => $itemid))) {
throw new \Exception("Not Found: Grade item {$itemid} doesn't exist", 404);
}
$item = $this->get_service()->get_lineitem($contextid, $itemid, $typeid);
if ($item === false) {
throw new \Exception('Line item does not exist', 404);
}
$gbs = gradebookservices::find_ltiservice_gradebookservice_for_lineitem($itemid);
$ltilinkid = null;
if (isset($item->iteminstance)) {
$ltilinkid = $item->iteminstance;
} else if ($gbs && isset($gbs->ltilinkid)) {
$ltilinkid = $gbs->ltilinkid;
}
if ($ltilinkid != null) {
if (is_null($typeid)) {
if (isset($item->iteminstance) && (!gradebookservices::check_lti_id($ltilinkid, $item->courseid,
$this->get_service()->get_tool_proxy()->id))) {
$response->set_code(403);
$response->set_reason("Invalid LTI id supplied.");
return;
}
} else {
if (isset($item->iteminstance) && (!gradebookservices::check_lti_1x_id($ltilinkid, $item->courseid,
$typeid))) {
$response->set_code(403);
$response->set_reason("Invalid LTI id supplied.");
return;
}
}
}
$json = '[]';
require_once($CFG->libdir.'/gradelib.php');
switch ($response->get_request_method()) {
case 'GET':
$response->set_code(405);
$response->set_reason("GET requests are not allowed.");
break;
case 'POST':
try {
$json = $this->get_json_for_post_request($response, $response->get_request_data(), $item, $contextid,
$typeid);
$response->set_content_type($this->formats[1]);
} catch (\Exception $e) {
$response->set_code($e->getCode());
$response->set_reason($e->getMessage());
}
break;
default: // Should not be possible.
$response->set_code(405);
$response->set_reason("Invalid request method specified.");
return;
}
$response->set_body($json);
} catch (\Exception $e) {
$response->set_code($e->getCode());
$response->set_reason($e->getMessage());
}
}
/**
* Generate the JSON for a POST request.
*
* @param \mod_lti\local\ltiservice\response $response Response object for this request.
* @param string $body POST body
* @param object $item Grade item instance
* @param string $contextid
* @param string $typeid
*
* @throws \Exception
*/
private function get_json_for_post_request($response, $body, $item, $contextid, $typeid) {
$score = json_decode($body);
if (empty($score) ||
!isset($score->userId) ||
!isset($score->timestamp) ||
!isset($score->gradingProgress) ||
!isset($score->activityProgress) ||
!isset($score->timestamp) ||
isset($score->timestamp) && !gradebookservices::validate_iso8601_date($score->timestamp) ||
(isset($score->scoreGiven) && !is_numeric($score->scoreGiven)) ||
(isset($score->scoreGiven) && !isset($score->scoreMaximum)) ||
(isset($score->scoreMaximum) && !is_numeric($score->scoreMaximum)) ||
(!gradebookservices::is_user_gradable_in_course($contextid, $score->userId))
) {
throw new \Exception('Incorrect score received' . $body, 400);
}
$score->timemodified = intval($score->timestamp);
if (!isset($score->scoreMaximum)) {
$score->scoreMaximum = 1;
}
$response->set_code(200);
$grade = \grade_grade::fetch(array('itemid' => $item->id, 'userid' => $score->userId));
if ($grade && !empty($grade->timemodified)) {
if ($grade->timemodified >= strtotime($score->timestamp)) {
$exmsg = "Refusing score with an earlier timestamp for item " . $item->id . " and user " . $score->userId;
throw new \Exception($exmsg, 409);
}
}
if (isset($score->scoreGiven)) {
if ($score->gradingProgress != 'FullyGraded') {
$score->scoreGiven = null;
}
}
$this->get_service()->save_grade_item($item, $score, $score->userId);
}
/**
* Parse a value for custom parameter substitution variables.
*
* @param string $value String to be parsed
*
* @return string
*/
public function parse_value($value) {
global $COURSE, $CFG;
if (strpos($value, '$Scores.url') !== false) {
require_once($CFG->libdir . '/gradelib.php');
$resolved = '';
$this->params['context_id'] = $COURSE->id;
$id = optional_param('id', 0, PARAM_INT); // Course Module ID.
if (!empty($id)) {
$cm = get_coursemodule_from_id('lti', $id, 0, false, MUST_EXIST);
$id = $cm->instance;
$item = grade_get_grades($COURSE->id, 'mod', 'lti', $id);
if ($item && $item->items) {
$this->params['item_id'] = $item->items[0]->id;
$resolved = parent::get_endpoint();
}
}
$value = str_replace('$Scores.url', $resolved, $value);
}
return $value;
}
}
@@ -0,0 +1,901 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains a class definition for the LTI Gradebook Services
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @author Dirk Singels, Diego del Blanco, Claude Vervoort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace ltiservice_gradebookservices\local\service;
use ltiservice_gradebookservices\local\resources\lineitem;
use ltiservice_gradebookservices\local\resources\lineitems;
use ltiservice_gradebookservices\local\resources\results;
use ltiservice_gradebookservices\local\resources\scores;
use mod_lti\local\ltiservice\resource_base;
use mod_lti\local\ltiservice\service_base;
use moodle_url;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/mod/lti/locallib.php');
/**
* A service implementing LTI Gradebook Services.
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class gradebookservices extends service_base {
/** Read-only access to Gradebook services */
const GRADEBOOKSERVICES_READ = 1;
/** Full access to Gradebook services */
const GRADEBOOKSERVICES_FULL = 2;
/** Scope for full access to Lineitem service */
const SCOPE_GRADEBOOKSERVICES_LINEITEM = 'https://purl.imsglobal.org/spec/lti-ags/scope/lineitem';
/** Scope for full access to Lineitem service */
const SCOPE_GRADEBOOKSERVICES_LINEITEM_READ = 'https://purl.imsglobal.org/spec/lti-ags/scope/lineitem.readonly';
/** Scope for access to Result service */
const SCOPE_GRADEBOOKSERVICES_RESULT_READ = 'https://purl.imsglobal.org/spec/lti-ags/scope/result.readonly';
/** Scope for access to Score service */
const SCOPE_GRADEBOOKSERVICES_SCORE = 'https://purl.imsglobal.org/spec/lti-ags/scope/score';
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
$this->id = 'gradebookservices';
$this->name = get_string($this->get_component_id(), $this->get_component_id());
}
/**
* Get the resources for this service.
*
* @return resource_base[]
*/
public function get_resources() {
// The containers should be ordered in the array after their elements.
// Lineitems should be after lineitem.
if (empty($this->resources)) {
$this->resources = array();
$this->resources[] = new lineitem($this);
$this->resources[] = new lineitems($this);
$this->resources[] = new results($this);
$this->resources[] = new scores($this);
}
return $this->resources;
}
/**
* Get the scope(s) permitted for this service.
*
* @return array
*/
public function get_permitted_scopes() {
$scopes = array();
$ok = !empty($this->get_type());
if ($ok && isset($this->get_typeconfig()['ltiservice_gradesynchronization'])) {
if (!empty($setting = $this->get_typeconfig()['ltiservice_gradesynchronization'])) {
$scopes[] = self::SCOPE_GRADEBOOKSERVICES_LINEITEM_READ;
$scopes[] = self::SCOPE_GRADEBOOKSERVICES_RESULT_READ;
$scopes[] = self::SCOPE_GRADEBOOKSERVICES_SCORE;
if ($setting == self::GRADEBOOKSERVICES_FULL) {
$scopes[] = self::SCOPE_GRADEBOOKSERVICES_LINEITEM;
}
}
}
return $scopes;
}
/**
* Get the scopes defined by this service.
*
* @return array
*/
public function get_scopes() {
return [self::SCOPE_GRADEBOOKSERVICES_LINEITEM_READ, self::SCOPE_GRADEBOOKSERVICES_RESULT_READ,
self::SCOPE_GRADEBOOKSERVICES_SCORE, self::SCOPE_GRADEBOOKSERVICES_LINEITEM];
}
/**
* Adds form elements for gradebook sync add/edit page.
*
* @param \MoodleQuickForm $mform Moodle quickform object definition
*/
public function get_configuration_options(&$mform) {
$selectelementname = 'ltiservice_gradesynchronization';
$identifier = 'grade_synchronization';
$options = [
get_string('nevergs', $this->get_component_id()),
get_string('partialgs', $this->get_component_id()),
get_string('alwaysgs', $this->get_component_id())
];
$mform->addElement('select', $selectelementname, get_string($identifier, $this->get_component_id()), $options);
$mform->setType($selectelementname, 'int');
$mform->setDefault($selectelementname, 0);
$mform->addHelpButton($selectelementname, $identifier, $this->get_component_id());
}
/**
* For submission review, if there is a dedicated URL, use it as the target link.
*
* @param string $messagetype message type for this launch
* @param string $targetlinkuri current target link uri
* @param string|null $customstr concatenated list of custom parameters
* @param int $courseid
* @param null|object $lti LTI Instance.
*
* @return array containing the target link URL and the custom params string to use.
*/
public function override_endpoint(string $messagetype, string $targetlinkuri, ?string $customstr, int $courseid,
?object $lti = null): array {
global $DB;
if ($messagetype == 'LtiSubmissionReviewRequest' && isset($lti->id)) {
$conditions = array('courseid' => $courseid, 'ltilinkid' => $lti->id);
$coupledlineitems = $DB->get_records('ltiservice_gradebookservices', $conditions);
if (count($coupledlineitems) == 1) {
$item = reset($coupledlineitems);
$url = $item->subreviewurl;
$subreviewparams = $item->subreviewparams;
if (!empty($url) && $url != 'DEFAULT') {
$targetlinkuri = $url;
}
if (!empty($subreviewparams)) {
if (!empty($customstr)) {
$customstr .= "\n{$subreviewparams}";
} else {
$customstr = $subreviewparams;
}
}
}
}
return [$targetlinkuri, $customstr];
}
/**
* Return an array of key/claim mapping allowing LTI 1.1 custom parameters
* to be transformed to LTI 1.3 claims.
*
* @return array Key/value pairs of params to claim mapping.
*/
public function get_jwt_claim_mappings(): array {
return [
'custom_gradebookservices_scope' => [
'suffix' => 'ags',
'group' => 'endpoint',
'claim' => 'scope',
'isarray' => true
],
'custom_lineitems_url' => [
'suffix' => 'ags',
'group' => 'endpoint',
'claim' => 'lineitems',
'isarray' => false
],
'custom_lineitem_url' => [
'suffix' => 'ags',
'group' => 'endpoint',
'claim' => 'lineitem',
'isarray' => false
],
'custom_results_url' => [
'suffix' => 'ags',
'group' => 'endpoint',
'claim' => 'results',
'isarray' => false
],
'custom_result_url' => [
'suffix' => 'ags',
'group' => 'endpoint',
'claim' => 'result',
'isarray' => false
],
'custom_scores_url' => [
'suffix' => 'ags',
'group' => 'endpoint',
'claim' => 'scores',
'isarray' => false
],
'custom_score_url' => [
'suffix' => 'ags',
'group' => 'endpoint',
'claim' => 'score',
'isarray' => false
]
];
}
/**
* Return an array of key/values to add to the launch parameters.
*
* @param string $messagetype 'basic-lti-launch-request' or 'ContentItemSelectionRequest'.
* @param string $courseid the course id.
* @param object $user The user id.
* @param string $typeid The tool lti type id.
* @param string $modlti The id of the lti activity.
*
* The type is passed to check the configuration
* and not return parameters for services not used.
*
* @return array of key/value pairs to add as launch parameters.
*/
public function get_launch_parameters($messagetype, $courseid, $user, $typeid, $modlti = null) {
global $DB;
$launchparameters = array();
$this->set_type(lti_get_type($typeid));
$this->set_typeconfig(lti_get_type_config($typeid));
// Only inject parameters if the service is enabled for this tool.
if (isset($this->get_typeconfig()['ltiservice_gradesynchronization'])) {
if ($this->get_typeconfig()['ltiservice_gradesynchronization'] == self::GRADEBOOKSERVICES_READ ||
$this->get_typeconfig()['ltiservice_gradesynchronization'] == self::GRADEBOOKSERVICES_FULL) {
// Check for used in context is only needed because there is no explicit site tool - course relation.
if ($this->is_allowed_in_context($typeid, $courseid)) {
$id = null;
if (!is_null($modlti)) {
$conditions = array('courseid' => $courseid, 'itemtype' => 'mod',
'itemmodule' => 'lti', 'iteminstance' => $modlti);
$coupledlineitems = $DB->get_records('grade_items', $conditions);
$conditionsgbs = array('courseid' => $courseid, 'ltilinkid' => $modlti);
$lineitemsgbs = $DB->get_records('ltiservice_gradebookservices', $conditionsgbs);
// If a link has more that one attached grade items, per spec we do not populate line item url.
if (count($lineitemsgbs) == 1) {
$id = reset($lineitemsgbs)->gradeitemid;
}
if (count($lineitemsgbs) < 2 && count($coupledlineitems) == 1) {
$coupledid = reset($coupledlineitems)->id;
if (!is_null($id) && $id != $coupledid) {
$id = null;
} else {
$id = $coupledid;
}
}
}
$launchparameters['gradebookservices_scope'] = implode(',', $this->get_permitted_scopes());
$launchparameters['lineitems_url'] = '$LineItems.url';
if (!is_null($id)) {
$launchparameters['lineitem_url'] = '$LineItem.url';
}
}
}
}
return $launchparameters;
}
/**
* Fetch the lineitem instances.
*
* @param string $courseid ID of course
* @param string $resourceid Resource identifier used for filtering, may be null
* @param string $ltilinkid Resource Link identifier used for filtering, may be null
* @param string $tag
* @param int $limitfrom Offset for the first line item to include in a paged set
* @param int $limitnum Maximum number of line items to include in the paged set
* @param string $typeid
*
* @return array
* @throws \Exception
*/
public function get_lineitems($courseid, $resourceid, $ltilinkid, $tag, $limitfrom, $limitnum, $typeid) {
global $DB;
// Select all lti potential linetiems in site.
$params = array('courseid' => $courseid);
$sql = "SELECT i.*
FROM {grade_items} i
WHERE (i.courseid = :courseid)
ORDER BY i.id";
$lineitems = $DB->get_records_sql($sql, $params);
// For each one, check the gbs id, and check that toolproxy matches. If so, add the
// tag to the result and add it to a final results array.
$lineitemstoreturn = array();
$lineitemsandtotalcount = array();
if ($lineitems) {
foreach ($lineitems as $lineitem) {
$gbs = $this->find_ltiservice_gradebookservice_for_lineitem($lineitem->id);
if ($gbs && (!isset($tag) || (isset($tag) && $gbs->tag == $tag))
&& (!isset($ltilinkid) || (isset($ltilinkid) && $gbs->ltilinkid == $ltilinkid))
&& (!isset($resourceid) || (isset($resourceid) && $gbs->resourceid == $resourceid))) {
if (is_null($typeid)) {
if ($this->get_tool_proxy()->id == $gbs->toolproxyid) {
array_push($lineitemstoreturn, $lineitem);
}
} else {
if ($typeid == $gbs->typeid) {
array_push($lineitemstoreturn, $lineitem);
}
}
} else if (($lineitem->itemtype == 'mod' && $lineitem->itemmodule == 'lti'
&& !isset($resourceid) && !isset($tag)
&& (!isset($ltilinkid) || (isset($ltilinkid)
&& $lineitem->iteminstance == $ltilinkid)))) {
// We will need to check if the activity related belongs to our tool proxy.
$ltiactivity = $DB->get_record('lti', array('id' => $lineitem->iteminstance));
if (($ltiactivity) && (isset($ltiactivity->typeid))) {
if ($ltiactivity->typeid != 0) {
$tool = $DB->get_record('lti_types', array('id' => $ltiactivity->typeid));
} else {
$tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $courseid);
if (!$tool) {
$tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $courseid);
}
}
if (is_null($typeid)) {
if (($tool) && ($this->get_tool_proxy()->id == $tool->toolproxyid)) {
array_push($lineitemstoreturn, $lineitem);
}
} else {
if (($tool) && ($tool->id == $typeid)) {
array_push($lineitemstoreturn, $lineitem);
}
}
}
}
}
$lineitemsandtotalcount = array();
array_push($lineitemsandtotalcount, count($lineitemstoreturn));
// Return the right array based in the paging parameters limit and from.
if (($limitnum) && ($limitnum > 0)) {
$lineitemstoreturn = array_slice($lineitemstoreturn, $limitfrom, $limitnum);
}
array_push($lineitemsandtotalcount, $lineitemstoreturn);
}
return $lineitemsandtotalcount;
}
/**
* Fetch a lineitem instance.
*
* Returns the lineitem instance if found, otherwise false.
*
* @param string $courseid ID of course
* @param string $itemid ID of lineitem
* @param string $typeid
*
* @return \ltiservice_gradebookservices\local\resources\lineitem|bool
*/
public function get_lineitem($courseid, $itemid, $typeid) {
global $DB, $CFG;
require_once($CFG->libdir . '/gradelib.php');
$lineitem = \grade_item::fetch(array('id' => $itemid));
if ($lineitem) {
$gbs = $this->find_ltiservice_gradebookservice_for_lineitem($itemid);
if (!$gbs) {
// We will need to check if the activity related belongs to our tool proxy.
$ltiactivity = $DB->get_record('lti', array('id' => $lineitem->iteminstance));
if (($ltiactivity) && (isset($ltiactivity->typeid))) {
if ($ltiactivity->typeid != 0) {
$tool = $DB->get_record('lti_types', array('id' => $ltiactivity->typeid));
} else {
$tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $courseid);
if (!$tool) {
$tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $courseid);
}
}
if (is_null($typeid)) {
if (!(($tool) && ($this->get_tool_proxy()->id == $tool->toolproxyid))) {
return false;
}
} else {
if (!(($tool) && ($tool->id == $typeid))) {
return false;
}
}
} else {
return false;
}
}
}
return $lineitem;
}
/**
* Adds a decoupled (standalone) line item.
* Decoupled line items are not directly attached to
* an lti instance activity. They are recorded in
* the gradebook as manual activities and the
* gradebookservices is used to associate that manual column
* with the tool in addition to storing the LTI related
* metadata (resource id, tag).
*
* @param string $courseid ID of course
* @param string $label label of lineitem
* @param float $maximumscore maximum score of lineitem
* @param string $baseurl
* @param int|null $ltilinkid id of lti instance this line item is associated with
* @param string|null $resourceid resource id of lineitem
* @param string|null $tag tag of lineitem
* @param int $typeid lti type to which this line item is associated with
* @param int|null $toolproxyid lti2 tool proxy to which this lineitem is associated to
*
* @return int id of the created gradeitem
*/
public function add_standalone_lineitem(string $courseid, string $label, float $maximumscore,
string $baseurl, ?int $ltilinkid, ?string $resourceid, ?string $tag, int $typeid,
int $toolproxyid = null): int {
global $DB;
$params = array();
$params['itemname'] = $label;
$params['gradetype'] = GRADE_TYPE_VALUE;
$params['grademax'] = $maximumscore;
$params['grademin'] = 0;
$item = new \grade_item(array('id' => 0, 'courseid' => $courseid));
\grade_item::set_properties($item, $params);
$item->itemtype = 'manual';
$item->grademax = $maximumscore;
$id = $item->insert('mod/ltiservice_gradebookservices');
$DB->insert_record('ltiservice_gradebookservices', (object)array(
'gradeitemid' => $id,
'courseid' => $courseid,
'toolproxyid' => $toolproxyid,
'typeid' => $typeid,
'baseurl' => $baseurl,
'ltilinkid' => $ltilinkid,
'resourceid' => $resourceid,
'tag' => $tag
));
return $id;
}
/**
* Set a grade item.
*
* @param object $gradeitem Grade Item record
* @param object $score Result object
* @param int $userid User ID
*
* @throws \Exception
* @deprecated since Moodle 3.7 MDL-62599 - please do not use this function any more.
* @see gradebookservices::save_grade_item($gradeitem, $score, $userid)
*/
public static function save_score($gradeitem, $score, $userid) {
$service = new gradebookservices();
$service->save_grade_item($gradeitem, $score, $userid);
}
/**
* Saves a score received from the LTI tool.
*
* @param object $gradeitem Grade Item record
* @param object $score Result object
* @param int $userid User ID
*
* @throws \Exception
*/
public function save_grade_item($gradeitem, $score, $userid) {
global $DB, $CFG;
$source = 'mod' . $this->get_component_id();
if ($DB->get_record('user', array('id' => $userid)) === false) {
throw new \Exception(null, 400);
}
require_once($CFG->libdir . '/gradelib.php');
$finalgrade = null;
$timemodified = null;
if (isset($score->scoreGiven)) {
$finalgrade = grade_floatval($score->scoreGiven);
$max = 1;
if (isset($score->scoreMaximum)) {
$max = $score->scoreMaximum;
}
if (!is_null($max) && grade_floats_different($max, $gradeitem->grademax) && grade_floats_different($max, 0.0)) {
// Rescale to match the grade item maximum.
$finalgrade = grade_floatval($finalgrade * $gradeitem->grademax / $max);
}
if (isset($score->timestamp)) {
$timemodified = strtotime($score->timestamp);
} else {
$timemodified = time();
}
}
$feedbackformat = FORMAT_MOODLE;
$feedback = null;
if (!empty($score->comment)) {
$feedback = $score->comment;
$feedbackformat = FORMAT_PLAIN;
}
if ($gradeitem->is_manual_item()) {
$result = $gradeitem->update_final_grade($userid, $finalgrade, null, $feedback, FORMAT_PLAIN, null, $timemodified);
} else {
if (!$grade = \grade_grade::fetch(array('itemid' => $gradeitem->id, 'userid' => $userid))) {
$grade = new \grade_grade();
$grade->userid = $userid;
$grade->itemid = $gradeitem->id;
}
$grade->rawgrademax = $score->scoreMaximum;
$grade->timemodified = $timemodified;
$grade->feedbackformat = $feedbackformat;
$grade->feedback = $feedback;
$grade->rawgrade = $finalgrade;
$status = grade_update($source, $gradeitem->courseid,
$gradeitem->itemtype, $gradeitem->itemmodule,
$gradeitem->iteminstance, $gradeitem->itemnumber, $grade);
$result = ($status == GRADE_UPDATE_OK);
}
if (!$result) {
debugging("failed to save score for item ".$gradeitem->id." and user ".$grade->userid);
throw new \Exception(null, 500);
}
}
/**
* Get the json object representation of the grade item
*
* @param object $item Grade Item record
* @param string $endpoint Endpoint for lineitems container request
* @param string $typeid
*
* @return object
*/
public static function item_for_json($item, $endpoint, $typeid) {
$lineitem = new \stdClass();
if (is_null($typeid)) {
$typeidstring = "";
} else {
$typeidstring = "?type_id={$typeid}";
}
$lineitem->id = "{$endpoint}/{$item->id}/lineitem" . $typeidstring;
$lineitem->label = $item->itemname;
$lineitem->scoreMaximum = floatval($item->grademax);
$gbs = self::find_ltiservice_gradebookservice_for_lineitem($item->id);
if ($gbs) {
$lineitem->resourceId = (!empty($gbs->resourceid)) ? $gbs->resourceid : '';
$lineitem->tag = (!empty($gbs->tag)) ? $gbs->tag : '';
if (isset($gbs->ltilinkid)) {
$lineitem->resourceLinkId = strval($gbs->ltilinkid);
$lineitem->ltiLinkId = strval($gbs->ltilinkid);
}
if (!empty($gbs->subreviewurl)) {
$submissionreview = new \stdClass();
if ($gbs->subreviewurl != 'DEFAULT') {
$submissionreview->url = $gbs->subreviewurl;
}
if (!empty($gbs->subreviewparams)) {
$submissionreview->custom = lti_split_parameters($gbs->subreviewparams);
}
$lineitem->submissionReview = $submissionreview;
}
} else {
$lineitem->tag = '';
if (isset($item->iteminstance)) {
$lineitem->resourceLinkId = strval($item->iteminstance);
$lineitem->ltiLinkId = strval($item->iteminstance);
}
}
return $lineitem;
}
/**
* Get the object matching the JSON representation of the result.
*
* @param object $grade Grade record
* @param string $endpoint Endpoint for lineitem
* @param int $typeid The id of the type to include in the result url.
*
* @return object
*/
public static function result_for_json($grade, $endpoint, $typeid) {
if (is_null($typeid)) {
$id = "{$endpoint}/results?user_id={$grade->userid}";
} else {
$id = "{$endpoint}/results?type_id={$typeid}&user_id={$grade->userid}";
}
$result = new \stdClass();
$result->id = $id;
$result->userId = $grade->userid;
if (!empty($grade->finalgrade)) {
$result->resultScore = floatval($grade->finalgrade);
$result->resultMaximum = floatval($grade->rawgrademax);
if (!empty($grade->feedback)) {
$result->comment = $grade->feedback;
}
if (is_null($typeid)) {
$result->scoreOf = $endpoint;
} else {
$result->scoreOf = "{$endpoint}?type_id={$typeid}";
}
$result->timestamp = date('c', $grade->timemodified);
}
return $result;
}
/**
* Check if an LTI id is valid.
*
* @param string $linkid The lti id
* @param string $course The course
* @param string $toolproxy The tool proxy id
*
* @return boolean
*/
public static function check_lti_id($linkid, $course, $toolproxy) {
global $DB;
// Check if lti type is zero or not (comes from a backup).
$sqlparams1 = array();
$sqlparams1['linkid'] = $linkid;
$sqlparams1['course'] = $course;
$ltiactivity = $DB->get_record('lti', array('id' => $linkid, 'course' => $course));
if ($ltiactivity->typeid == 0) {
$tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $course);
if (!$tool) {
$tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $course);
}
return (($tool) && ($toolproxy == $tool->toolproxyid));
} else {
$sqlparams2 = array();
$sqlparams2['linkid'] = $linkid;
$sqlparams2['course'] = $course;
$sqlparams2['toolproxy'] = $toolproxy;
$sql = 'SELECT lti.*
FROM {lti} lti
INNER JOIN {lti_types} typ ON lti.typeid = typ.id
WHERE lti.id = ?
AND lti.course = ?
AND typ.toolproxyid = ?';
return $DB->record_exists_sql($sql, $sqlparams2);
}
}
/**
* Check if an LTI id is valid when we are in a LTI 1.x case
*
* @param string $linkid The lti id
* @param string $course The course
* @param string $typeid The lti type id
*
* @return boolean
*/
public static function check_lti_1x_id($linkid, $course, $typeid) {
global $DB;
// Check if lti type is zero or not (comes from a backup).
$sqlparams1 = array();
$sqlparams1['linkid'] = $linkid;
$sqlparams1['course'] = $course;
$ltiactivity = $DB->get_record('lti', array('id' => $linkid, 'course' => $course));
if ($ltiactivity) {
if ($ltiactivity->typeid == 0) {
$tool = lti_get_tool_by_url_match($ltiactivity->toolurl, $course);
if (!$tool) {
$tool = lti_get_tool_by_url_match($ltiactivity->securetoolurl, $course);
}
return (($tool) && ($typeid == $tool->id));
} else {
$sqlparams2 = array();
$sqlparams2['linkid'] = $linkid;
$sqlparams2['course'] = $course;
$sqlparams2['typeid'] = $typeid;
$sql = 'SELECT lti.*
FROM {lti} lti
INNER JOIN {lti_types} typ ON lti.typeid = typ.id
WHERE lti.id = ?
AND lti.course = ?
AND typ.id = ?';
return $DB->record_exists_sql($sql, $sqlparams2);
}
} else {
return false;
}
}
/**
* Updates the tag, resourceid and submission review values for a grade item coupled to an lti link instance.
*
* @param object $ltiinstance The lti instance to which the grade item is coupled to
* @param string|null $resourceid The resourceid to apply to the lineitem. If empty string which will be stored as null.
* @param string|null $tag The tag to apply to the lineitem. If empty string which will be stored as null.
* @param moodle_url|null $subreviewurl The submission review target link URL
* @param string|null $subreviewparams The submission review custom parameters.
*
*/
public static function update_coupled_gradebookservices(object $ltiinstance,
?string $resourceid, ?string $tag, ?\moodle_url $subreviewurl, ?string $subreviewparams): void {
global $DB;
if ($ltiinstance && $ltiinstance->typeid) {
$gradeitem = $DB->get_record('grade_items', array('itemmodule' => 'lti', 'iteminstance' => $ltiinstance->id));
if ($gradeitem) {
$resourceid = (isset($resourceid) && empty(trim($resourceid))) ? null : $resourceid;
$subreviewurlstr = $subreviewurl ? $subreviewurl->out(false) : null;
$tag = (isset($tag) && empty(trim($tag))) ? null : $tag;
$gbs = self::find_ltiservice_gradebookservice_for_lineitem($gradeitem->id);
if ($gbs) {
$gbs->resourceid = $resourceid;
$gbs->tag = $tag;
$gbs->subreviewurl = $subreviewurlstr;
$gbs->subreviewparams = $subreviewparams;
$DB->update_record('ltiservice_gradebookservices', $gbs);
} else {
$baseurl = lti_get_type_type_config($ltiinstance->typeid)->lti_toolurl;
$DB->insert_record('ltiservice_gradebookservices', (object)array(
'gradeitemid' => $gradeitem->id,
'courseid' => $gradeitem->courseid,
'typeid' => $ltiinstance->typeid,
'baseurl' => $baseurl,
'ltilinkid' => $ltiinstance->id,
'resourceid' => $resourceid,
'tag' => $tag,
'subreviewurl' => $subreviewurlstr,
'subreviewparams' => $subreviewparams
));
}
}
}
}
/**
* Called when a new LTI Instance is added.
*
* @param object $lti LTI Instance.
*/
public function instance_added(object $lti): void {
self::update_coupled_gradebookservices($lti, $lti->lineitemresourceid ?? null, $lti->lineitemtag ?? null,
isset($lti->lineitemsubreviewurl) ? new moodle_url($lti->lineitemsubreviewurl) : null,
$lti->lineitemsubreviewparams ?? null);
}
/**
* Called when a new LTI Instance is updated.
*
* @param object $lti LTI Instance.
*/
public function instance_updated(object $lti): void {
self::update_coupled_gradebookservices($lti, $lti->lineitemresourceid ?? null, $lti->lineitemtag ?? null,
isset($lti->lineitemsubreviewurl) ? new moodle_url($lti->lineitemsubreviewurl) : null,
$lti->lineitemsubreviewparams ?? null);
}
/**
* Set the form data when displaying the LTI Instance form.
*
* @param object $defaultvalues Default form values.
*/
public function set_instance_form_values(object $defaultvalues): void {
$defaultvalues->lineitemresourceid = '';
$defaultvalues->lineitemtag = '';
$defaultvalues->subreviewurl = '';
$defaultvalues->subreviewparams = '';
if (is_object($defaultvalues) && $defaultvalues->instance) {
$gbs = self::find_ltiservice_gradebookservice_for_lti($defaultvalues->instance);
if ($gbs) {
$defaultvalues->lineitemresourceid = $gbs->resourceid;
$defaultvalues->lineitemtag = $gbs->tag;
$defaultvalues->lineitemsubreviewurl = $gbs->subreviewurl;
$defaultvalues->lineitemsubreviewparams = $gbs->subreviewparams;
}
}
}
/**
* Deletes orphaned rows from the 'ltiservice_gradebookservices' table.
*
* Sometimes, if a gradebook entry is deleted and it was a lineitem
* the row in the table ltiservice_gradebookservices can become an orphan
* This method will clean these orphans. It will happens based on a task
* because it is not urgent and we don't want to slow the service
*/
public static function delete_orphans_ltiservice_gradebookservices_rows() {
global $DB;
$sql = "DELETE
FROM {ltiservice_gradebookservices}
WHERE gradeitemid NOT IN (SELECT id
FROM {grade_items} gi)";
$DB->execute($sql);
}
/**
* Check if a user can be graded in a course
*
* @param int $courseid The course
* @param int $userid The user
* @return bool
*/
public static function is_user_gradable_in_course($courseid, $userid) {
global $CFG;
$gradableuser = false;
$coursecontext = \context_course::instance($courseid);
if (is_enrolled($coursecontext, $userid, '', false)) {
$roles = get_user_roles($coursecontext, $userid);
$gradebookroles = explode(',', $CFG->gradebookroles);
foreach ($roles as $role) {
foreach ($gradebookroles as $gradebookrole) {
if ($role->roleid === $gradebookrole) {
$gradableuser = true;
}
}
}
}
return $gradableuser;
}
/**
* Find the right element in the ltiservice_gradebookservice table for an lti instance
*
* @param string $instanceid The LTI module instance id
* @return object gradebookservice for this line item
*/
public static function find_ltiservice_gradebookservice_for_lti($instanceid) {
global $DB;
if ($instanceid) {
$gradeitem = $DB->get_record('grade_items', array('itemmodule' => 'lti', 'iteminstance' => $instanceid));
if ($gradeitem) {
return self::find_ltiservice_gradebookservice_for_lineitem($gradeitem->id);
}
}
}
/**
* Find the right element in the ltiservice_gradebookservice table for a lineitem
*
* @param string $lineitemid The lineitem (gradeitem) id
* @return object gradebookservice if it exists
*/
public static function find_ltiservice_gradebookservice_for_lineitem($lineitemid) {
global $DB;
if ($lineitemid) {
return $DB->get_record('ltiservice_gradebookservices',
array('gradeitemid' => $lineitemid));
}
}
/**
* Validates specific ISO 8601 format of the timestamps.
*
* @param string $date The timestamp to check.
* @return boolean true or false if the date matches the format.
*
*/
public static function validate_iso8601_date($date) {
if (preg_match('/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])' .
'(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))' .
'([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)' .
'?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/', $date) > 0) {
return true;
} else {
return false;
}
}
}
@@ -0,0 +1,113 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for ltiservice_gradebookservices.
*
* @package ltiservice_gradebookservices
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace ltiservice_gradebookservices\privacy;
use \core_privacy\local\metadata\collection;
use \core_privacy\local\request\contextlist;
use \core_privacy\local\request\approved_contextlist;
use \core_privacy\local\request\userlist;
use \core_privacy\local\request\approved_userlist;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for ltiservice_gradebookservices.
*
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @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\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @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 {
$collection->link_external_location('External LTI provider.', [
'userid' => 'privacy:metadata:userid',
'grade' => 'privacy:metadata:grade',
'maxgrade' => 'privacy:metadata:maxgrade',
'feedback' => 'privacy:metadata:feedback',
'timemodified' => 'privacy:metadata:timemodified'
], 'privacy:metadata:externalpurpose');
return $collection;
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
return new contextlist();
}
/**
* Get the list of users who have data within a context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
}
/**
* Delete all user data which matches the specified context.
*
* @param \context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
}
}
@@ -0,0 +1,58 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* A scheduled task for gradebookservices.
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @author Dirk Singels, Diego del Blanco, Claude Vervoort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace ltiservice_gradebookservices\task;
use core\task\scheduled_task;
use ltiservice_gradebookservices\local\service\gradebookservices;
defined('MOODLE_INTERNAL') || die();
/**
* Class containing the scheduled task for gradebookservices.
*
* @package ltiservice_gradebookservices
* @copyright 2017 Cengage Learning http://www.cengage.com
* @author Dirk Singels, Diego del Blanco, Claude Vervoort
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class cleanup_task extends scheduled_task {
/**
* Get a descriptive name for this task (shown to admins).
*
* @return string
*/
public function get_name() {
return get_string('taskcleanup', 'ltiservice_gradebookservices');
}
/**
* Run forum cron.
*/
public function execute() {
gradebookservices::delete_orphans_ltiservice_gradebookservices_rows();
}
}