Skip to content

Commit

Permalink
PM-43593 started cleanup of code
Browse files Browse the repository at this point in the history
  • Loading branch information
mk-kialo committed Sep 19, 2024
1 parent 55cbfa7 commit 345d90f
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 74 deletions.
6 changes: 4 additions & 2 deletions classes/grading/line_item.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@

namespace mod_kialo\grading;

defined('MOODLE_INTERNAL') || die();

/**
* Represents a line item in the LTI 1.3 Assignment and Grading Service.
*
* @package mod_kialo
* @copyright 2023 onwards, Kialo GmbH <[email protected]>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class line_item {
/**
Expand Down
25 changes: 25 additions & 0 deletions classes/kialo_view.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
namespace mod_kialo;

use context_module;
use Psr\Http\Message\ResponseInterface;

/**
* Helpers for Kialo views.
Expand Down Expand Up @@ -63,4 +64,28 @@ public static function get_current_group_info(\stdClass $cm, \stdClass $course):
$result->groupname = groups_get_group_name($groupid);
return $result;
}

/**
* Writes a response to the client.
*
* @param ResponseInterface $response
* @return void
*/
public static function write_response(ResponseInterface $response): void {
$statusline = sprintf(
'HTTP/%s %s %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
);
header($statusline);

foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}

echo $response->getBody();
}
}
10 changes: 7 additions & 3 deletions classes/lti_flow.php
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,11 @@ public static function add_grading_service(MessagePayloadBuilder $payloadbuilder
]);
}

/**
* Generates an access token for the service to use when calling the LTI service endpoints.
* @return ResponseInterface
* @throws \dml_exception
*/
public static function generate_service_access_token(): ResponseInterface {
$kialoconfig = kialo_config::get_instance();
$registrationrepo = $kialoconfig->get_registration_repository();
Expand All @@ -443,10 +448,8 @@ public static function generate_service_access_token(): ResponseInterface {
$response = new Response();

try {
// Extract keyChainIdentifier from request uri parameter.
$keychainidentifier = $kialoconfig->get_platform_keychain()->getIdentifier();

// Validate assertion, generate and sign access token response, using the key chain private key.
$keychainidentifier = $kialoconfig->get_platform_keychain()->getIdentifier();
$response = $generator->generate($request, $response, $keychainidentifier);
} catch (OAuthServerException $exception) {
$response = $exception->generateHttpResponse($response);
Expand All @@ -456,6 +459,7 @@ public static function generate_service_access_token(): ResponseInterface {
}

/**
* Authenticates a service request using the LTI access token. Throws an error if authentication fails.
* @param array $scopes The scopes that the service request must have.
* @return void
* @throws \dml_exception
Expand Down
44 changes: 17 additions & 27 deletions lti_lineitem.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,58 +15,50 @@
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.

/**
* When an LTI message is launching a resource associated to one and only one lineitem,
* the claim must include the endpoint URL for accessing the associated line item;
* in all other cases, this property must be either blank or not included in the claim.
*
* Handles GET and POST (/scores) requests for LTI 1.3 Assignment and Grading Service line items.
* See LTI 1.3 Assignment and Grading Service specification: https://www.imsglobal.org/spec/lti-ags/v2p0.
*
* @package mod_kialo
* @copyright 2023 onwards, Kialo GmbH <[email protected]>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*
* @var moodle_database $DB
* @var stdClass $CFG see moodle's config.php
*/

// phpcs:disable moodle.Files.RequireLogin.Missing

require_once(__DIR__ . '/../../config.php');
require_once(__DIR__ . '/lib.php');
require_once(__DIR__ . '/constants.php');
require_once(__DIR__ . '/vendor/autoload.php');
require_once($CFG->libdir . '/gradelib.php');

use mod_kialo\grading\line_item;
use mod_kialo\kialo_logger;
use mod_kialo\lti_flow;
use OAT\Library\Lti1p3Core\Exception\LtiException;

$logger = new kialo_logger("lti_lineitem");
$logger->info("LTI lineitem request received.", $_POST ?? $_GET ?? []);

//lti_flow::authenticate_service_request(MOD_KIALO_LTI_AGS_SCOPES);
lti_flow::authenticate_service_request(MOD_KIALO_LTI_AGS_SCOPES);

$courseid = required_param('course_id', PARAM_INT);
$cmid = required_param('cmid', PARAM_INT);
$resourcelinkid = required_param('resource_link_id', PARAM_TEXT);
$module = get_coursemodule_from_id('kialo', $cmid, $courseid);
if (!$module) {
die("Module $cmid not found");
}
$module = get_coursemodule_from_id('kialo', $cmid, $courseid, false, MUST_EXIST);
$moduleinstance = $DB->get_record('kialo', ['id' => $module->instance], '*', MUST_EXIST);

$gradeitem = grade_item::fetch(['iteminstance' => $module->instance, 'itemtype' => 'mod']);
if (!$gradeitem) {
die("Grade item for module CMID=$cmid (instance={$module->instance}) not found");
throw new LtiException("Grade item for module CMID=$cmid (instance={$module->instance}) not found");
}

if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] == '/scores') {
// Parse JSON POST request body.
// Receive a score for the line item via JSON request body.
$input = file_get_contents('php://input');
$data = json_decode($input, true);

$userid = $data['userId'];
$scoregiven = isset($data['scoreGiven']) ? max(0, min($data['scoreGiven'], $gradeitem->grademax)) : null;
$scoregiven = isset($data['scoreGiven']) ? max(0, min(floatval($data['scoreGiven']), $gradeitem->grademax)) : null;
$comment = $data['comment'];
$timestamp = isset($data['timestamp']) ? strtotime($data['timestamp']) : time();
$activityprogress = $data['activityProgress'];
$gradingprogress = $data['gradingProgress'];

if ($scoregiven < 0 && $scoregiven > $gradeitem->grademax) {
$logger->error("Invalid score given: $scoregiven");
die("Invalid score given: $scoregiven");
}

$grades = [
'userid' => $userid,
Expand All @@ -78,9 +70,8 @@
}

kialo_grade_item_update($moduleinstance, $grades);

} else {
// Handle GET request
// Return the line item information.
$lineitem = new line_item();
$lineitem->id = (new moodle_url($_SERVER['REQUEST_URI']))->out(false);
$lineitem->label = $module->name;
Expand All @@ -90,4 +81,3 @@
header('Content-Type: application/json; utf-8');
echo json_encode($lineitem, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}

23 changes: 11 additions & 12 deletions lti_token.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,25 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* This endpoint returns a service access token for the use with the LTI services (e.g. for grading).
* See also https://github.com/oat-sa/lib-lti1p3-core/blob/master/doc/service/service-server.md.
*
* @package mod_kialo
* @copyright 2023 onwards, Kialo GmbH <[email protected]>
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

// phpcs:disable moodle.Files.RequireLogin.Missing
define('NO_DEBUG_DISPLAY', true);
define('NO_MOODLE_COOKIES', true);

require_once(__DIR__ . '/../../config.php');
require_once(__DIR__ . '/lib.php');
require_once(__DIR__ . '/constants.php');
require_once('vendor/autoload.php');

use mod_kialo\kialo_view;
use mod_kialo\lti_flow;

$response = lti_flow::generate_service_access_token();

// Write the response.
$statusline = sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase());
header($statusline, true); /* The header replaces a previous similar header. */

foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}

echo $response->getBody();
kialo_view::write_response($response);
50 changes: 20 additions & 30 deletions openid-configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,35 +28,24 @@
define('NO_MOODLE_COOKIES', true);
require_once(__DIR__ . '/../../config.php');

/**
* Returns the LTI capabilities that are supported by this plugin.
*
* @return array
*/
function lti_get_capabilities()
{
$capabilities = [
'basic-lti-launch-request' => '',
'ContentItemSelectionRequest' => '',
'ResourceLink.id' => 'resource_link_id',
'ResourceLink.title' => 'resource_link_title',
'ResourceLink.description' => 'resource_link_description',
'User.id' => 'user_id',
'User.username' => '$USER->username',
'Person.name.full' => 'lis_person_name_full',
'Person.name.given' => 'lis_person_name_given',
'Person.name.middle' => 'lis_person_name_given',
'Person.name.family' => 'lis_person_name_family',
'Person.email.primary' => 'lis_person_contact_email_primary',
'Person.sourcedId' => 'lis_person_sourcedid',
'Membership.role' => 'roles',
'Result.sourcedId' => 'lis_result_sourcedid',
'Result.autocreate' => 'lis_outcome_service_url',

];

return $capabilities;
}
$capabilities = [
'basic-lti-launch-request' => '',
'ContentItemSelectionRequest' => '',
'ResourceLink.id' => 'resource_link_id',
'ResourceLink.title' => 'resource_link_title',
'ResourceLink.description' => 'resource_link_description',
'User.id' => 'user_id',
'User.username' => '$USER->username',
'Person.name.full' => 'lis_person_name_full',
'Person.name.given' => 'lis_person_name_given',
'Person.name.middle' => 'lis_person_name_given',
'Person.name.family' => 'lis_person_name_family',
'Person.email.primary' => 'lis_person_contact_email_primary',
'Person.sourcedId' => 'lis_person_sourcedid',
'Membership.role' => 'roles',
'Result.sourcedId' => 'lis_result_sourcedid',
'Result.autocreate' => 'lis_outcome_service_url',
];

$scopes = [
'openid',
Expand All @@ -65,6 +54,7 @@ function lti_get_capabilities()
"https://purl.imsglobal.org/spec/lti-ags/scope/score",
"https://purl.imsglobal.org/spec/lti-ags/scope/lineitem",
];

$conf = [
'issuer' => $CFG->wwwroot . '/mod/kialo',
'token_endpoint' => (new moodle_url('/mod/kialo/lti_token.php'))->out(false),
Expand Down Expand Up @@ -97,7 +87,7 @@ function lti_get_capabilities()
['type' => 'LtiResourceLinkRequest'],
['type' => 'LtiDeepLinkingRequest', 'placements' => ['ContentArea']],
],
'variables' => array_keys(lti_get_capabilities()),
'variables' => array_keys($capabilities),
],
];

Expand Down

0 comments on commit 345d90f

Please sign in to comment.