dirroot."/admin/migrate-setup.php";
}
if ( ! isset($CFG) ) exit;
$DATABASE_UNINSTALL = array(
"drop table if exists {$CFG->dbprefix}lti_tool_registration_token",
"drop table if exists {$CFG->dbprefix}lti_content",
"drop table if exists {$CFG->dbprefix}lti_tool_deployment_claim",
"drop table if exists {$CFG->dbprefix}lti_tool_deployment_scope",
"drop table if exists {$CFG->dbprefix}lti_tool_deployment_placement",
"drop table if exists {$CFG->dbprefix}lti_tool_message_placement",
"drop table if exists {$CFG->dbprefix}lti_tool_registration_log",
"drop table if exists {$CFG->dbprefix}lti_tool_message",
"drop table if exists {$CFG->dbprefix}lti_tool_deployment_context",
"drop table if exists {$CFG->dbprefix}lti_tool_deployment_org",
"drop table if exists {$CFG->dbprefix}lti_tool_deployment",
"drop table if exists {$CFG->dbprefix}lti_tool_registration",
"drop table if exists {$CFG->dbprefix}lti_gclass_queue",
"drop table if exists {$CFG->dbprefix}lti_gclass_log",
"drop table if exists {$CFG->dbprefix}lti_context_plus_log",
"drop table if exists {$CFG->dbprefix}lti_result",
"drop table if exists {$CFG->dbprefix}lti_service",
"drop table if exists {$CFG->dbprefix}lti_membership",
"drop table if exists {$CFG->dbprefix}lti_link",
"drop table if exists {$CFG->dbprefix}lti_category",
"drop table if exists {$CFG->dbprefix}lti_link_activity",
"drop table if exists {$CFG->dbprefix}lti_link_user_activity",
"drop table if exists {$CFG->dbprefix}manifest",
"drop table if exists {$CFG->dbprefix}context_images",
"drop table if exists {$CFG->dbprefix}lti_context",
"drop table if exists {$CFG->dbprefix}lti_org",
"drop table if exists {$CFG->dbprefix}lti_user",
"drop table if exists {$CFG->dbprefix}lti_issuer",
"drop table if exists {$CFG->dbprefix}lti_keyset",
"drop table if exists {$CFG->dbprefix}lti_key",
// After lti_key. A later foreign key on lti_key will require that order.
"drop table if exists {$CFG->dbprefix}lti_registration",
"drop table if exists {$CFG->dbprefix}lti_nonce",
"drop table if exists {$CFG->dbprefix}lti_message",
"drop table if exists {$CFG->dbprefix}lti_domain",
"drop table if exists {$CFG->dbprefix}lti_external",
"drop table if exists {$CFG->dbprefix}cal_event",
"drop table if exists {$CFG->dbprefix}cal_key",
"drop table if exists {$CFG->dbprefix}cal_context",
"drop table if exists {$CFG->dbprefix}tsugi_string",
"drop table if exists {$CFG->dbprefix}sessions"
);
// Note that the TEXT xxx_key fields are UNIQUE but not
// marked as UNIQUE because of MySQL key index length limitations.
$DATABASE_INSTALL = array(
array( "{$CFG->dbprefix}lti_keyset",
"create table {$CFG->dbprefix}lti_keyset (
keyset_id INTEGER NOT NULL AUTO_INCREMENT,
keyset_title TEXT NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
pubkey TEXT NULL,
privkey TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_keyset_const_pk` PRIMARY KEY (keyset_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// Inbound LTI 1.3 registration. Tsugi is the tool.
// lti_tool_registration is the other direction, where Tsugi is the platform.
// One row is one OAuth client (issuer + client_id). Deployments stay on lti_key.
// Created before lti_key so a later foreign key can live in the lti_key CREATE.
// Nothing reads this table yet. Launch and dynamic registration still use lti_key.
array( "{$CFG->dbprefix}lti_registration",
"create table {$CFG->dbprefix}lti_registration (
lti_registration_id INTEGER NOT NULL AUTO_INCREMENT,
-- Row guid. An omitted value gets an unswapped MySQL UUID() (version 1).
-- Same bytes as UUID_TO_BIN(UUID()). Inserts pass Guid::uuid7().
-- UNHEX, REPLACE, and UUID are allowed in a default on MySQL 8.0.13+ and
-- MariaDB 10.5. UUID_TO_BIN is not allowed in a MariaDB 10.5 default.
-- Explicit NULL stays NULL. The unique key allows more than one NULL.
-- This is not tool_platform.guid. That value is platform_guid.
guid BINARY(16) NULL DEFAULT (UNHEX(REPLACE(UUID(), '-', ''))),
-- Human label. Not part of the OAuth identity. Copied from key_title
-- when a registration is created from a key.
title TEXT NULL,
notes TEXT NULL,
-- Issuer is required. client_id stays NULL until the platform assigns one.
issuer VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
client_id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
-- The first completed (issuer, client_id) owns these four values.
-- Later deployments of that client reuse this row. They do not get another copy.
-- Canvas cloud shares the issuer and these URLs, so the client id separates schools.
-- Blackboard SaaS shares https://blackboard.com. The authorize, token, and
-- keyset URLs are on the school host, and the token audience is often a
-- different gateway value. The first row to store that client freezes them.
-- A hostname change, or another key entered with different URLs, has nowhere
-- else to go. Handle this when dynamic registration writes this table.
-- Do not copy the first lti_key lms_* values and assume the other keys agree.
oidc_auth_url TEXT NULL,
keyset_url TEXT NULL,
token_url TEXT NULL,
-- OpenID authorization_server, stored verbatim. Often not the token URL.
token_audience TEXT NULL,
-- One-time dynamic registration code. Same column as lti_key.unlock_code.
-- Dynamic registration still checks the code on the key.
unlock_code MEDIUMTEXT NULL,
-- NULL until a later dynamic registration flow records the unlock. Nothing writes this yet.
dynamic_registration_unlocked_at TIMESTAMP NULL,
product_family_code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
-- tool_platform.guid from a launch. Registration usually does not have it yet.
platform_guid VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
-- Future values: manual, dynamic. Nothing reads these yet.
registration_method VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'manual',
-- Future values: pending, active, disabled.
registration_status VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'pending',
-- Future values: automatic, approval, reject. Default is approval.
new_deployment_policy VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'approval',
-- Provenance only. Not a foreign key and not deployment ownership.
created_by_user_id INTEGER NULL,
json MEDIUMTEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
-- NULLs are distinct, so pending rows can share an issuer while client_id
-- is still NULL. A completed (issuer, client_id) pair cannot be repeated.
CONSTRAINT `{$CFG->dbprefix}lti_registration_const_1` UNIQUE (issuer, client_id),
CONSTRAINT `{$CFG->dbprefix}lti_registration_const_guid` UNIQUE (`guid`),
CONSTRAINT `{$CFG->dbprefix}lti_registration_const_pk` PRIMARY KEY (lti_registration_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// https://stackoverflow.com/questions/28418360/jwt-json-web-token-audience-aud-versus-client-id-whats-the-difference
// Key is in effect "tenant" (like a billing endpoint)
// We need to be able to look this up by either oauth_consumer_key or
// (issuer, client_id, deployment_id)
// TODO: Decide if the key_key must always be unique.
array( "{$CFG->dbprefix}lti_key",
"create table {$CFG->dbprefix}lti_key (
key_id INTEGER NOT NULL AUTO_INCREMENT,
key_title TEXT NULL,
key_sha256 CHAR(64) NULL,
key_key VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL, -- oauth_consumer_key
deleted TINYINT(1) NOT NULL DEFAULT 0,
secret VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
new_secret VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
-- This is the owner of this key - it is not a foreign key
-- on purpose to avoid potential circular foreign keys
user_id INTEGER NULL,
-- Issuer / client_id / deployment_id defines a client (i.e. who pays the bill)
deploy_sha256 CHAR(64) NULL,
deploy_key VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL, -- deployment_id renamed
-- Per-key LTI 1.3 platform configuration (dynamic registration or manual entry).
-- oidc_login uses key_id in the URL, so launch lookup is by primary key plus
-- lms_client and wildcard iss handling in LTIX::loadAllData().
lms_issuer VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL, -- iss from the JWT
lms_issuer_sha256 CHAR(64) NULL,
lms_client VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL, -- aud from the JWT / client_id in OAuth
lms_oidc_auth TEXT NULL,
lms_keyset_url TEXT NULL,
lms_token_url TEXT NULL,
lms_token_audience TEXT NULL,
-- Inbound registration. NULL means this key is not in that model yet.
-- ON DELETE SET NULL detaches the key when the registration is removed.
-- deployment_status NULL means the approval workflow does not apply.
-- Future values: pending, active, blocked.
-- platform_guid is tool_platform.guid from a launch, not this row's guid.
lti_registration_id INTEGER NULL,
deployment_status VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NULL,
-- NULL until a later approval workflow sets it. Existing keys stay NULL.
deployment_approved_at TIMESTAMP NULL,
platform_guid VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
-- Default IANA zone copied onto a new Plus context. Existing courses keep their own.
timezone VARCHAR(64) NULL,
-- 1 when this tenant supports a Tsugi Plus course launch.
plus TINYINT(1) NOT NULL DEFAULT 0,
-- Our cache of the LMS data
lms_cache_keyset TEXT NULL,
lms_cache_pubkey TEXT NULL,
lms_cache_kid TEXT NULL,
unlock_code MEDIUMTEXT NULL,
-- NULL until a later dynamic registration flow records the unlock. Nothing writes this yet.
dynamic_registration_unlocked_at TIMESTAMP NULL,
json MEDIUMTEXT NULL,
user_json MEDIUMTEXT NULL,
settings MEDIUMTEXT NULL,
settings_url TEXT NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
login_at TIMESTAMP NULL,
login_count BIGINT DEFAULT 0,
login_time BIGINT DEFAULT 0,
-- An omitted guid gets an unswapped MySQL UUID() (version 1).
-- Same bytes as UUID_TO_BIN(UUID()). Inserts and backfill pass Guid::uuid7().
-- UNHEX, REPLACE, and UUID are allowed in a default on MySQL 8.0.13+ and
-- MariaDB 10.5. UUID_TO_BIN is not allowed in a MariaDB 10.5 default.
-- Explicit NULL stays NULL. The unique key allows more than one NULL.
-- Upgrade adds this unique key. It does not add this default.
guid BINARY(16) NULL DEFAULT (UNHEX(REPLACE(UUID(), '-', ''))),
-- deploy_sha256 participates in uniqueness; NULL deploy_sha256 (wildcard deploy_key)
-- allows multiple rows per key_sha256 in typical MySQL UNIQUE-with-NULL semantics.
CONSTRAINT `{$CFG->dbprefix}lti_key_const_1` UNIQUE(key_sha256, deploy_sha256),
CONSTRAINT `{$CFG->dbprefix}lti_key_const_guid` UNIQUE (`guid`),
CONSTRAINT `{$CFG->dbprefix}lti_key_ibfk_1`
FOREIGN KEY (`lti_registration_id`)
REFERENCES `{$CFG->dbprefix}lti_registration` (`lti_registration_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_key_const_pk` PRIMARY KEY (key_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
/* If MySQL had constraints - these would be nice in lti_key - for now
we will just need to be careful in code.
CONSTRAINT `{$CFG->dbprefix}lti_key_both_not_null`
CHECK (
(key_sha256 IS NOT NULL OR deploy_sha256 IS NOT NULL)
)
CONSTRAINT `{$CFG->dbprefix}lti_key_deploy_linked`
CHECK (
(deploy_key IS NOT NULL AND issuer_id IS NOT NULL)
OR (deploy_key NOT NULL AND issuer_id NOT NULL)
)
*/
array( "{$CFG->dbprefix}lti_user",
"create table {$CFG->dbprefix}lti_user (
user_id INTEGER NOT NULL AUTO_INCREMENT,
user_sha256 CHAR(64) NULL,
user_key TEXT NULL,
subject_sha256 CHAR(64) NULL,
subject_key TEXT NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
key_id INTEGER NOT NULL,
profile_id INTEGER NULL,
displayname TEXT NULL,
email TEXT NULL,
locale CHAR(63) NULL,
image TEXT NULL,
subscribe SMALLINT NULL,
-- Site-level capability to mint courses (not an LTI membership role)
create_courses TINYINT(1) NOT NULL DEFAULT 0,
json MEDIUMTEXT NULL,
login_at TIMESTAMP NULL,
login_count BIGINT DEFAULT 0,
login_time BIGINT DEFAULT 0,
-- Google classroom token for this user. gc_status is the last
-- refresh or call error. Null means the last check succeeded.
gc_token TEXT NULL,
gc_status VARCHAR(512) NULL,
gc_checked_at TIMESTAMP NULL,
ipaddr VARCHAR(64),
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
-- An omitted guid gets an unswapped MySQL UUID() (version 1).
-- Same bytes as UUID_TO_BIN(UUID()). Inserts and backfill pass Guid::uuid7().
-- UNHEX, REPLACE, and UUID are allowed in a default on MySQL 8.0.13+ and
-- MariaDB 10.5. UUID_TO_BIN is not allowed in a MariaDB 10.5 default.
-- Explicit NULL stays NULL. The unique key allows more than one NULL.
-- Upgrade adds this unique key. It does not add this default.
guid BINARY(16) NULL DEFAULT (UNHEX(REPLACE(UUID(), '-', ''))),
CONSTRAINT `{$CFG->dbprefix}lti_user_ibfk_1`
FOREIGN KEY (`key_id`)
REFERENCES `{$CFG->dbprefix}lti_key` (`key_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_user_const_1` UNIQUE(key_id, user_sha256),
CONSTRAINT `{$CFG->dbprefix}lti_user_const_2` UNIQUE(key_id, subject_sha256),
CONSTRAINT `{$CFG->dbprefix}lti_user_const_guid` UNIQUE (`guid`),
INDEX `{$CFG->dbprefix}lti_user_indx_email` (email(255)),
INDEX `{$CFG->dbprefix}lti_user_indx_profile` (profile_id),
-- Google login: key_id and email, newest updated_at first.
-- UNIQUE(key_id, user_sha256) walks every user on that key.
INDEX `{$CFG->dbprefix}lti_user_indx_key_email` (key_id, email(255), updated_at),
CONSTRAINT `{$CFG->dbprefix}lti_user_const_pk` PRIMARY KEY (user_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
/* If MySQL had CHECK constraints - these would be nice in lti_user - for now
we will just need to be careful in code.
CONSTRAINT `{$CFG->dbprefix}lti_user_both_not_null`
CHECK (
(user_sha256 IS NOT NULL OR subject_sha256 IS NOT NULL)
)
*/
// Organization hierarchy inside one tenant key. The tenant is lti_key.
// A null parent_org_id is a top-level org. The tenant itself is not an org row.
array( "{$CFG->dbprefix}lti_org",
"create table {$CFG->dbprefix}lti_org (
org_id INTEGER NOT NULL AUTO_INCREMENT,
key_id INTEGER NOT NULL,
parent_org_id INTEGER NULL,
title VARCHAR(512) NOT NULL,
-- Label only. Parent links define the hierarchy, not this value.
org_type VARCHAR(64) NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_org_const_pk` PRIMARY KEY (org_id),
-- Referenced by child orgs, registrations, and deployments so those rows
-- stay on the same tenant key as this org.
CONSTRAINT `{$CFG->dbprefix}lti_org_const_1` UNIQUE (org_id, key_id),
INDEX `{$CFG->dbprefix}lti_org_indx_1` (key_id),
INDEX `{$CFG->dbprefix}lti_org_indx_2` (parent_org_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_org_ibfk_1`
FOREIGN KEY (`key_id`)
REFERENCES `{$CFG->dbprefix}lti_key` (`key_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
-- Same key_id as the parent, so a child cannot attach to another tenant.
-- ON DELETE RESTRICT: OrgService::deleteOrg reparents children first.
-- CASCADE here would delete the subtree. Cycles are rejected in moveOrg.
-- MySQL cannot CHECK org_id because that column is AUTO_INCREMENT.
CONSTRAINT `{$CFG->dbprefix}lti_org_ibfk_2`
FOREIGN KEY (`parent_org_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_org` (`org_id`, `key_id`)
ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_context",
"create table {$CFG->dbprefix}lti_context (
context_id INTEGER NOT NULL AUTO_INCREMENT,
-- Same type as context_id. NULL until a later change records one. No foreign key.
previous_context_id INTEGER NULL,
context_sha256 CHAR(64) NOT NULL,
context_key VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
secret VARCHAR(128) NULL,
gc_secret VARCHAR(128) NULL,
key_id INTEGER NOT NULL,
-- Optional org inside this tenant key. NULL leaves an existing course unplaced.
org_id INTEGER NULL,
-- If this course was created by a user within a key
-- For example Google Glassroom - or an ad-hoc group
user_id INTEGER NULL,
path TEXT NULL,
title TEXT NULL,
short_title VARCHAR(64) NULL,
lessons MEDIUMTEXT NULL,
json MEDIUMTEXT NULL,
user_json MEDIUMTEXT NULL,
settings MEDIUMTEXT NULL,
settings_url TEXT NULL,
ext_memberships_id TEXT NULL,
ext_memberships_url TEXT NULL,
memberships_url TEXT NULL,
lineitems_url TEXT NULL,
lti13_lineitems TEXT NULL,
lti13_membership_url TEXT NULL,
lti13_context_groups_url TEXT NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
login_at TIMESTAMP NULL,
login_count BIGINT DEFAULT 0,
login_time BIGINT DEFAULT 0,
viewDueDates TINYINT(1) NOT NULL DEFAULT 1,
-- Active course manifest version (NULL = file-based $CFG->lessons)
manifest_id INTEGER NULL,
-- 1 when a Plus launch controls this course. 0 for file-based lessons and ordinary resource links.
plus_course TINYINT(1) NOT NULL DEFAULT 0,
-- 1 when anyone may open this course's lessons without membership.
anonymous_lessons TINYINT(1) NOT NULL DEFAULT 0,
-- Deployment id from the Plus launch. Token calls read this.
lti13_deployment_id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
-- lti_link of the Plus launch. No foreign key: lti_link already points here.
plus_launch_link_id INTEGER NULL,
-- When the Names and Roles pull last started.
nrps_at TIMESTAMP NULL,
-- IANA zone for line-item endDateTime. Null sends the due day with no shift.
timezone VARCHAR(64) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
-- An omitted guid gets an unswapped MySQL UUID() (version 1).
-- Same bytes as UUID_TO_BIN(UUID()). Inserts and backfill pass Guid::uuid7().
-- UNHEX, REPLACE, and UUID are allowed in a default on MySQL 8.0.13+ and
-- MariaDB 10.5. UUID_TO_BIN is not allowed in a MariaDB 10.5 default.
-- Explicit NULL stays NULL. The unique key allows more than one NULL.
-- Upgrade adds this unique key. It does not add this default.
guid BINARY(16) NULL DEFAULT (UNHEX(REPLACE(UUID(), '-', ''))),
CONSTRAINT `{$CFG->dbprefix}lti_context_ibfk_1`
FOREIGN KEY (`key_id`)
REFERENCES `{$CFG->dbprefix}lti_key` (`key_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_context_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
-- A composite (org_id, key_id) foreign key with ON DELETE SET NULL would
-- also null key_id. OrgService::placeContext() keeps the course and the org on the same key.
CONSTRAINT `{$CFG->dbprefix}lti_context_ibfk_3`
FOREIGN KEY (`org_id`)
REFERENCES `{$CFG->dbprefix}lti_org` (`org_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_context_const_1` UNIQUE(key_id, context_sha256),
-- Deployment scope and registration ownership reference (context_id, key_id)
-- so a course link cannot leave this tenant key.
CONSTRAINT `{$CFG->dbprefix}lti_context_const_2` UNIQUE(context_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_context_const_guid` UNIQUE (`guid`),
CONSTRAINT `{$CFG->dbprefix}lti_context_const_pk` PRIMARY KEY (context_id),
INDEX `{$CFG->dbprefix}lti_context_indx_1` (org_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}context_images",
"create table {$CFG->dbprefix}context_images (
context_id INTEGER NOT NULL,
hero MEDIUMBLOB NULL,
hero_mime VARCHAR(64) NULL,
hero_bytes INTEGER NULL,
hero_updated_at TIMESTAMP NULL,
icon MEDIUMBLOB NULL,
icon_mime VARCHAR(64) NULL,
icon_bytes INTEGER NULL,
icon_updated_at TIMESTAMP NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}context_images_const_pk` PRIMARY KEY (context_id),
CONSTRAINT `{$CFG->dbprefix}context_images_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}manifest",
"create table {$CFG->dbprefix}manifest (
manifest_id INTEGER NOT NULL AUTO_INCREMENT,
context_id INTEGER NOT NULL,
version INTEGER NOT NULL,
title TEXT NULL,
-- Skinny Setup field (theme key). New course-setup features are sibling
-- columns, not keys inside the lessons JSON (`manifest` MEDIUMTEXT).
theme VARCHAR(64) NULL,
-- Teacher-edited course top nav (JSON). NULL = CourseNav default.
navigation MEDIUMTEXT NULL,
manifest MEDIUMTEXT NOT NULL,
comment TEXT NULL,
user_id INTEGER NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}manifest_const_pk` PRIMARY KEY (manifest_id),
CONSTRAINT `{$CFG->dbprefix}manifest_const_1` UNIQUE (context_id, version),
CONSTRAINT `{$CFG->dbprefix}manifest_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}manifest_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
INDEX `{$CFG->dbprefix}manifest_indx_1` (context_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One grade category in a course, like a Canvas assignment group.
// A link is in at most one category. No row here means the link is
// uncategorized, which is the default. There is no sentinel category.
// grade_percent is an integer percent of the overall grade. Zero is a
// real weight. Regular categories are the denominator and are meant to
// total 100. extra_credit is outside that 100: its percent is added to
// the numerator and left out of the denominator. The database does not
// check that the regular percents sum to 100.
// position is the grade book order. Lower numbers come first.
// Delete is real. lti_link.category_id is ON DELETE SET NULL, so the
// links stay and become uncategorized. A soft-delete flag would leave
// that foreign key set, so this table has none.
array( "{$CFG->dbprefix}lti_category",
"create table {$CFG->dbprefix}lti_category (
category_id INTEGER NOT NULL AUTO_INCREMENT,
context_id INTEGER NOT NULL,
title VARCHAR(255) NOT NULL,
-- Integer percent of the overall grade. Zero contributes nothing.
grade_percent INTEGER NOT NULL DEFAULT 0,
-- Extra credit adds grade_percent to the numerator only.
-- Regular categories are the denominator.
extra_credit TINYINT(1) NOT NULL DEFAULT 0,
-- Grade book order. Lower numbers come first.
position INTEGER NOT NULL DEFAULT 0,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_category_const_pk` PRIMARY KEY (category_id),
-- One name per course. Two weights cannot share a title.
CONSTRAINT `{$CFG->dbprefix}lti_category_const_1` UNIQUE (context_id, title),
CONSTRAINT `{$CFG->dbprefix}lti_category_chk_1` CHECK (
grade_percent >= 0 AND grade_percent <= 100
),
CONSTRAINT `{$CFG->dbprefix}lti_category_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// Gradebook column. Due dates, column publish, the line item, and the grade
// stay here. Launch URL, open target, custom parameters, and send flags
// are lti_content. Do not grow this table into launch config.
array( "{$CFG->dbprefix}lti_link",
"create table {$CFG->dbprefix}lti_link (
link_id INTEGER NOT NULL AUTO_INCREMENT,
link_sha256 CHAR(64) NOT NULL,
link_key VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
context_id INTEGER NOT NULL,
-- Optional grade category in this same course. NULL is uncategorized.
-- Same-course is not a foreign key: ON DELETE SET NULL cannot also
-- name context_id, because that column is NOT NULL.
category_id INTEGER NULL,
path TEXT NULL,
lti13_lineitem TEXT NULL,
title TEXT NULL,
score_maximum DOUBLE NULL,
-- Legacy due window still read by Assignments, Lessons, and Calendar.
-- New workflow dates are the columns below. Do not overload these two.
start_datetime TIMESTAMP NULL,
end_datetime TIMESTAMP NULL,
-- Soft publish. Existing links default to published. Unpublish deletes nothing.
published TINYINT(1) NOT NULL DEFAULT 1,
-- Hidden from students. Independent of published. Existing links stay visible.
hidden TINYINT(1) NOT NULL DEFAULT 0,
-- Set when an LTI 1.1 launch stores service_id and a sourcedid in an associated lti_result.
upward TINYINT(1) NOT NULL DEFAULT 0,
-- AGS gradesReleased. NULL means the tool has not said.
grades_released TINYINT(1) NULL,
-- Deep Linking available window. Lessons reads these. It does not store its own.
available_start_datetime TIMESTAMP NULL,
available_end_datetime TIMESTAMP NULL,
-- Deep Linking submission window, and the AGS line item startDateTime/endDateTime.
submission_start_datetime TIMESTAMP NULL,
submission_end_datetime TIMESTAMP NULL,
-- Tsugi due. Not an AGS field, and not submission end.
due_datetime TIMESTAMP NULL,
-- Opaque AGS resourceId and tag for the tool that owns this column.
-- That tool may be external, or internal (quiz, discussions). Not the quiz primary key.
ags_resource_id VARCHAR(256) NULL,
ags_tag VARCHAR(256) NULL,
-- Google coursework id when this column is mirrored. The link_key stays
-- the lesson resource id. File-based Classroom courses leave this empty
-- and keep the coursework id in link_key.
gc_coursework VARCHAR(64) NULL,
-- Google course id for that coursework. The launch URL is not a course page,
-- so a later grade send reads the course from here.
gc_course VARCHAR(64) NULL,
json MEDIUMTEXT NULL,
settings MEDIUMTEXT NULL,
settings_url TEXT NULL,
placementsecret VARCHAR(64) NULL,
oldplacementsecret VARCHAR(64) NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
-- An omitted guid gets an unswapped MySQL UUID() (version 1).
-- Same bytes as UUID_TO_BIN(UUID()). Inserts and backfill pass Guid::uuid7().
-- UNHEX, REPLACE, and UUID are allowed in a default on MySQL 8.0.13+ and
-- MariaDB 10.5. UUID_TO_BIN is not allowed in a MariaDB 10.5 default.
-- Explicit NULL stays NULL. The unique key allows more than one NULL.
-- Upgrade adds this unique key. It does not add this default.
guid BINARY(16) NULL DEFAULT (UNHEX(REPLACE(UUID(), '-', ''))),
CONSTRAINT `{$CFG->dbprefix}lti_link_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
-- Deleting the category leaves the link, with category_id cleared.
CONSTRAINT `{$CFG->dbprefix}lti_link_ibfk_2`
FOREIGN KEY (`category_id`)
REFERENCES `{$CFG->dbprefix}lti_category` (`category_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_link_const_1` UNIQUE(link_sha256, context_id),
CONSTRAINT `{$CFG->dbprefix}lti_link_const_guid` UNIQUE (`guid`),
CONSTRAINT `{$CFG->dbprefix}lti_link_const_pk` PRIMARY KEY (link_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One row per upward call on a context: roster, line item, or score.
// A replay inserts another row. It does not change this one.
array( "{$CFG->dbprefix}lti_context_plus_log",
"create table {$CFG->dbprefix}lti_context_plus_log (
context_plus_log_id INTEGER NOT NULL AUTO_INCREMENT,
context_id INTEGER NOT NULL,
link_id INTEGER NULL,
user_id INTEGER NULL,
-- roster, lineitem_create, lineitem_update, score
kind VARCHAR(32) NOT NULL,
success TINYINT(1) NOT NULL DEFAULT 0,
http_response INTEGER NULL,
url TEXT NULL,
request MEDIUMTEXT NULL,
detail MEDIUMTEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_context_plus_log_const_pk` PRIMARY KEY (context_plus_log_id),
INDEX `{$CFG->dbprefix}lti_context_plus_log_indx_1` (context_id, created_at),
CONSTRAINT `{$CFG->dbprefix}lti_context_plus_log_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_context_plus_log_ibfk_2`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_context_plus_log_ibfk_3`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_link_activity",
"create table {$CFG->dbprefix}lti_link_activity (
link_id INTEGER NOT NULL,
event INTEGER NOT NULL,
link_count INTEGER UNSIGNED NOT NULL DEFAULT 0,
activity VARBINARY(1024) NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_link_activity_ibfk_1`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (link_id,event)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_membership",
"create table {$CFG->dbprefix}lti_membership (
membership_id INTEGER NOT NULL AUTO_INCREMENT,
context_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
role SMALLINT NULL,
role_override SMALLINT NULL,
viewDueDates TINYINT(1) NOT NULL DEFAULT 1,
json MEDIUMTEXT NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
visited_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_membership_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_membership_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_membership_const_1` UNIQUE(context_id, user_id),
CONSTRAINT `{$CFG->dbprefix}lti_membership_const_pk` PRIMARY KEY (membership_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_link_user_activity",
"create table {$CFG->dbprefix}lti_link_user_activity (
link_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
event INTEGER NOT NULL,
link_user_count INTEGER UNSIGNED NOT NULL DEFAULT 0,
activity VARBINARY(1024) NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_link_user_activity_ibfk_1`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_link_user_activity_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_link_user_activity_const_pk` PRIMARY KEY (link_id, user_id, event)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_service",
"create table {$CFG->dbprefix}lti_service (
service_id INTEGER NOT NULL AUTO_INCREMENT,
service_sha256 CHAR(64) NOT NULL,
service_key TEXT NOT NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
key_id INTEGER NOT NULL,
format VARCHAR(1024) NULL,
json MEDIUMTEXT NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_service_ibfk_1`
FOREIGN KEY (`key_id`)
REFERENCES `{$CFG->dbprefix}lti_key` (`key_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_service_const_1` UNIQUE(key_id, service_sha256),
CONSTRAINT `{$CFG->dbprefix}lti_service_const_pk` PRIMARY KEY (service_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// service_id/sourcedid are for LTI 1.x
// result_url is for LTI 2.x
// Sometimes we might get both
array( "{$CFG->dbprefix}lti_result",
"create table {$CFG->dbprefix}lti_result (
result_id INTEGER NOT NULL AUTO_INCREMENT,
link_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
result_url TEXT NULL,
sourcedid TEXT NULL,
service_id INTEGER NULL,
gc_submit_id TEXT NULL,
ipaddr VARCHAR(64),
grade FLOAT NULL,
note MEDIUMTEXT NULL,
comment MEDIUMTEXT NULL,
attempts INTEGER NULL,
server_grade FLOAT NULL,
grading_progress VARCHAR(30) NOT NULL DEFAULT 'NotReady',
activity_progress VARCHAR(30) NOT NULL DEFAULT 'Initialized',
result_maximum DOUBLE NULL,
-- AGS scoreGiven. The link score_maximum is the column denominator.
-- grade remains the derived 0-1 fraction.
score_given DOUBLE NULL,
lti13_result_id TEXT NULL,
scoring_user_id INTEGER NULL,
score_timestamp TIMESTAMP NULL,
-- AGS submission.startedAt. submitted_at is submission.submittedAt.
started_at TIMESTAMP NULL,
submitted_at TIMESTAMP NULL,
json MEDIUMTEXT NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
attempted_at TIMESTAMP NULL,
retrieved_at TIMESTAMP NULL,
-- Last Plus line-item or score error. Cleared when a score send succeeds.
server_status VARCHAR(512) NULL,
CONSTRAINT `{$CFG->dbprefix}lti_result_ibfk_1`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_result_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_result_ibfk_3`
FOREIGN KEY (`service_id`)
REFERENCES `{$CFG->dbprefix}lti_service` (`service_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_result_ibfk_4`
FOREIGN KEY (`scoring_user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
-- Note service_id is not part of the key on purpose
-- It is data that can change and can be null in LTI 2.0
CONSTRAINT `{$CFG->dbprefix}lti_result_const_1` UNIQUE(link_id, user_id),
CONSTRAINT `{$CFG->dbprefix}lti_result_const_pk` PRIMARY KEY (result_id),
-- Indexes for performance optimization (grades queries)
KEY `{$CFG->dbprefix}lti_result_indx_link_deleted_grade` (link_id, deleted, grade),
KEY `{$CFG->dbprefix}lti_result_indx_link_user_grade` (link_id, user_id, grade, deleted),
-- Grade list: WHERE link_id ORDER BY updated_at LIMIT n
KEY `{$CFG->dbprefix}lti_result_indx_link_updated` (link_id, updated_at)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One waiting Classroom grade per result. A successful send deletes the row.
// Reset clears the error and leaves the row. It does not call Google.
array( "{$CFG->dbprefix}lti_gclass_queue",
"create table {$CFG->dbprefix}lti_gclass_queue (
gclass_queue_id INTEGER NOT NULL AUTO_INCREMENT,
context_id INTEGER NOT NULL,
link_id INTEGER NULL,
user_id INTEGER NULL,
result_id INTEGER NOT NULL,
owner_id INTEGER NOT NULL,
grade DOUBLE NULL,
gc_course VARCHAR(64) NULL,
gc_coursework TEXT NULL,
gc_submit_id TEXT NULL,
-- pending, or error after a send that did not reach Classroom
state VARCHAR(16) NOT NULL DEFAULT 'pending',
detail VARCHAR(512) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_queue_const_pk` PRIMARY KEY (gclass_queue_id),
CONSTRAINT `{$CFG->dbprefix}lti_gclass_queue_const_1` UNIQUE (result_id),
INDEX `{$CFG->dbprefix}lti_gclass_queue_indx_1` (context_id, state),
CONSTRAINT `{$CFG->dbprefix}lti_gclass_queue_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_queue_ibfk_2`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_queue_ibfk_3`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_queue_ibfk_4`
FOREIGN KEY (`result_id`)
REFERENCES `{$CFG->dbprefix}lti_result` (`result_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_queue_ibfk_5`
FOREIGN KEY (`owner_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One row per Classroom attempt. Reset does not delete these.
array( "{$CFG->dbprefix}lti_gclass_log",
"create table {$CFG->dbprefix}lti_gclass_log (
gclass_log_id INTEGER NOT NULL AUTO_INCREMENT,
context_id INTEGER NOT NULL,
link_id INTEGER NULL,
user_id INTEGER NULL,
result_id INTEGER NULL,
-- score, coursework_create, reconnect, due_date
kind VARCHAR(32) NOT NULL,
success TINYINT(1) NOT NULL DEFAULT 0,
http_response INTEGER NULL,
url TEXT NULL,
request MEDIUMTEXT NULL,
detail MEDIUMTEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_log_const_pk` PRIMARY KEY (gclass_log_id),
INDEX `{$CFG->dbprefix}lti_gclass_log_indx_1` (context_id, created_at),
CONSTRAINT `{$CFG->dbprefix}lti_gclass_log_ibfk_1`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_log_ibfk_2`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_log_ibfk_3`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_gclass_log_ibfk_4`
FOREIGN KEY (`result_id`)
REFERENCES `{$CFG->dbprefix}lti_result` (`result_id`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// Nonce is not connected using foreign key for performance
// and because it is effectively just a temporary cache
array( "{$CFG->dbprefix}lti_nonce",
"create table {$CFG->dbprefix}lti_nonce (
nonce CHAR(128) NOT NULL,
key_id INTEGER NOT NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_nonce_const_1` UNIQUE(key_id, nonce)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// This is for messaging if web sockets is not present
// These records should never last more than 5 minutes
// No foreign key on link_id - orphan records will expire
array( "{$CFG->dbprefix}lti_message",
"create table {$CFG->dbprefix}lti_message (
link_id INTEGER NOT NULL,
room_id INTEGER NOT NULL DEFAULT 0,
message TEXT NULL,
micro_time DOUBLE NOT NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_message_const_pk` PRIMARY KEY (link_id,room_id, micro_time)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_domain",
"create table {$CFG->dbprefix}lti_domain (
domain_id INTEGER NOT NULL AUTO_INCREMENT,
key_id INTEGER NOT NULL,
context_id INTEGER NULL,
deleted TINYINT(1) NOT NULL DEFAULT 0,
domain VARCHAR(128),
port INTEGER NULL,
consumer_key VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin,
secret VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin,
json TEXT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_domain_ibfk_1`
FOREIGN KEY (`key_id`)
REFERENCES `{$CFG->dbprefix}lti_key` (`key_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_domain_ibfk_2`
FOREIGN KEY (`context_id`)
REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_domain_const_pk` PRIMARY KEY (domain_id),
CONSTRAINT `{$CFG->dbprefix}lti_domain_const_1` UNIQUE(key_id, context_id, domain, port)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_external",
"create table {$CFG->dbprefix}lti_external (
external_id INTEGER NOT NULL AUTO_INCREMENT,
endpoint VARCHAR(128),
name TEXT,
url VARCHAR(128),
description TEXT,
fa_icon VARCHAR(128),
pubkey TEXT,
privkey TEXT,
deleted TINYINT(1) NOT NULL DEFAULT 0,
json TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_external_const_pk` PRIMARY KEY (external_id),
CONSTRAINT `{$CFG->dbprefix}lti_external_const_1` UNIQUE(endpoint)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// String table - Not normalized at all - very costly
// Enable with $CFG->checktranslation = true
array( "{$CFG->dbprefix}tsugi_string",
"create table {$CFG->dbprefix}tsugi_string (
string_id INTEGER NOT NULL AUTO_INCREMENT,
domain VARCHAR(128) NOT NULL,
string_text TEXT,
updated_at TIMESTAMP NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
string_sha256 CHAR(64) NOT NULL,
CONSTRAINT `{$CFG->dbprefix}lti_string_const_pk` PRIMARY KEY (string_id),
CONSTRAINT `{$CFG->dbprefix}lti_string_const_1` UNIQUE(domain, string_sha256)
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// Sessions is used if we are storing session data
// in the database if we are storing sessions elsewhere
// this will remain empty
array( "{$CFG->dbprefix}sessions",
"CREATE TABLE {$CFG->dbprefix}sessions (
sess_id VARCHAR(128) NOT NULL PRIMARY KEY,
sess_data BLOB NOT NULL,
sess_time INTEGER UNSIGNED NOT NULL,
sess_lifetime MEDIUMINT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL
) COLLATE utf8_bin, ENGINE = InnoDB;"),
// Outbound LTI tool registration inside one tenant key.
// key_id is the tenant. It is not an extra owner_tenant_id.
// owner_org_id and owner_context_id are administrative ownership, not
// where a deployment may be used. Both null means the tenant administers it.
// One owner may be set. Both set is rejected by chk_2.
//
// IMS Dynamic Registration messages are rows in lti_tool_message, not columns
// on this registration. message_json keeps placements, roles, and custom
// parameters. Placement rows live in lti_tool_message_placement. Sakai stores
// placements as columns; this table does not.
// registration_json is the parsed registration document. The raw wire text
// lives in lti_tool_registration_log, which is text so malformed JSON can be kept.
array( "{$CFG->dbprefix}lti_tool_registration",
"create table {$CFG->dbprefix}lti_tool_registration (
registration_id INTEGER NOT NULL AUTO_INCREMENT,
key_id INTEGER NOT NULL,
owner_org_id INTEGER NULL,
owner_context_id INTEGER NULL,
created_by_user_id INTEGER NULL,
title VARCHAR(512) NOT NULL,
-- One registration is LTI 1.1 or LTI 1.3, never both.
-- lti_version stays '1.1' or '1.3'. Protocol-only columns use lti11_ or lti13_.
-- json and registration_json are shared. An LTI 1.1 registration has exactly
-- one deployment row, created with the registration. Its deployment_id is null.
lti_version VARCHAR(8) NOT NULL DEFAULT '1.3',
lti11_key VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
lti11_secret VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
lti11_url TEXT NULL,
lti13_client_id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
lti13_oidc_login_url TEXT NULL,
lti13_jwks_url TEXT NULL,
lti13_launch_url TEXT NULL,
lti13_redirect_uri TEXT NULL,
json MEDIUMTEXT NULL,
registration_json JSON NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_const_pk` PRIMARY KEY (registration_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_const_1` UNIQUE (registration_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_chk_1` CHECK (
(lti_version = '1.1'
AND lti11_key IS NOT NULL AND lti11_key <> ''
AND lti11_secret IS NOT NULL AND lti11_secret <> ''
AND lti11_url IS NOT NULL AND lti11_url <> ''
AND lti13_client_id IS NULL
AND lti13_oidc_login_url IS NULL
AND lti13_jwks_url IS NULL
AND lti13_launch_url IS NULL
AND lti13_redirect_uri IS NULL)
OR
(lti_version = '1.3'
AND lti11_key IS NULL
AND lti11_secret IS NULL
AND lti11_url IS NULL)
),
-- Tenant, one organization, or one course. Not an org and a course.
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_chk_2` CHECK (
owner_org_id IS NULL OR owner_context_id IS NULL
),
INDEX `{$CFG->dbprefix}lti_tool_registration_indx_1` (key_id),
INDEX `{$CFG->dbprefix}lti_tool_registration_indx_2` (owner_org_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_registration_indx_3` (owner_context_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_ibfk_1`
FOREIGN KEY (`key_id`)
REFERENCES `{$CFG->dbprefix}lti_key` (`key_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
-- ON DELETE RESTRICT: deleteOrg clears owner_org_id first. CASCADE would
-- delete the registration, and that would delete its deployments.
-- ON UPDATE RESTRICT: chk_2 names owner_org_id, and MySQL error 3823
-- rejects any other referential action on a column named by a CHECK.
-- The course-owner foreign key is added in DATABASE_UPGRADE. An existing
-- lti_context must gain (context_id, key_id) before that key can be added.
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_ibfk_2`
FOREIGN KEY (`owner_org_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_org` (`org_id`, `key_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_ibfk_3`
FOREIGN KEY (`created_by_user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One LTI deployment_id for one registration. Scope is not stored here.
// A deployment may be assigned to many orgs and many courses through the
// join tables below. key_id is copied from the registration so those
// assignments cannot leave the tenant. deployment_id is the external LTI id.
array( "{$CFG->dbprefix}lti_tool_deployment",
"create table {$CFG->dbprefix}lti_tool_deployment (
tool_deployment_id INTEGER NOT NULL AUTO_INCREMENT,
registration_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
deployment_id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_const_pk` PRIMARY KEY (tool_deployment_id),
-- Join tables reference (tool_deployment_id, key_id) to stay on this tenant.
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_const_1` UNIQUE (tool_deployment_id, key_id),
-- One external deployment_id per registration. MySQL allows many NULLs in
-- this key, so it does not limit an LTI 1.1 registration to one row.
-- ToolDeploymentService::createDeployment() does that.
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_const_2` UNIQUE (registration_id, deployment_id),
-- lti_tool_deployment_placement references this so an enabled placement
-- cannot name a different registration or tenant than the deployment.
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_const_3` UNIQUE (tool_deployment_id, registration_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_indx_1` (registration_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_ibfk_1`
FOREIGN KEY (`registration_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_registration` (`registration_id`, `key_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One outbound launch. A lesson item, and later a rich-text URL, points here
// by content_id. The lesson may keep its own display title. This row is the
// launch. A quiz is not a content row; quiz1_quiz already owns its link.
//
// The course foreign key is added in DATABASE_UPGRADE. An existing lti_context
// must gain (context_id, key_id) before that key can be added.
//
// link_id NULL is not a grade column. Non-null is gradable, and it is unique
// so two launches cannot share one link. There is no separate gradable flag.
// resource_link_id lives here. A cartridge item keeps its id. A launch
// with no id, or an id this course already uses, is given a new one.
// Creating the link copies that id to lti_link.link_key.
//
// published starts unpublished. While link_id is null, this flag is the only
// student-visibility flag. Marking the launch gradable copies it onto
// lti_link.published. After link_id is set, student visibility reads the link.
//
// The LTI 1.1 secret stays on lti_tool_registration.lti11_secret. This row
// does not copy the key or the secret. Deleting a lesson item does not delete
// this row, the link, or lti_result.
array( "{$CFG->dbprefix}lti_content",
"create table {$CFG->dbprefix}lti_content (
content_id INTEGER NOT NULL AUTO_INCREMENT,
context_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
tool_deployment_id INTEGER NOT NULL,
link_id INTEGER NULL,
title VARCHAR(512) NULL,
launch_url TEXT NOT NULL,
-- How the launch opens. Sakai newpage is this column. New rows open in a new window.
-- window: a new window.
-- iframe: LTI document target iframe, shown as a modal. There is no modal value.
-- inline: embedded in the lesson page. A Tsugi extension, not an LTI document target.
target VARCHAR(32) NOT NULL DEFAULT 'window',
-- Placement custom parameters. Not the registration message custom.
-- A deep link content item's custom object is stored here.
custom JSON NULL,
resource_link_id VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
-- lti_sha256(resource_link_id). The same value as lti_link.link_sha256
-- when the grade column is created.
resource_link_sha256 CHAR(64) NOT NULL,
-- NULL follows the deployment grant. 0 or 1 is this launch's choice.
send_name TINYINT(1) NULL,
send_email TINYINT(1) NULL,
send_grade TINYINT(1) NULL,
-- New rows are unpublished. Grey ban / green check, same as a link.
published TINYINT(1) NOT NULL DEFAULT 0,
-- Parked deep-link content item. The return flow is not built.
-- Its line item, available window, and submission window belong on lti_link.
content_item JSON NULL,
entity_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_content_const_pk` PRIMARY KEY (content_id),
CONSTRAINT `{$CFG->dbprefix}lti_content_const_1` UNIQUE (link_id),
CONSTRAINT `{$CFG->dbprefix}lti_content_const_2` UNIQUE (context_id, resource_link_sha256),
CONSTRAINT `{$CFG->dbprefix}lti_content_chk_1` CHECK (
target IN ('window', 'iframe', 'inline')
),
INDEX `{$CFG->dbprefix}lti_content_indx_1` (context_id, key_id),
INDEX `{$CFG->dbprefix}lti_content_indx_2` (tool_deployment_id, key_id),
-- A deployment delete stops here while a launch still points at it.
CONSTRAINT `{$CFG->dbprefix}lti_content_ibfk_1`
FOREIGN KEY (`tool_deployment_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_deployment` (`tool_deployment_id`, `key_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT,
-- Removing the grade column leaves the launch. It does not remove this row.
CONSTRAINT `{$CFG->dbprefix}lti_content_ibfk_2`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// Where a deployment may be used. Not registration ownership.
// The course foreign key is added in DATABASE_UPGRADE. An existing lti_context
// must gain (context_id, key_id) before that key can be added.
array( "{$CFG->dbprefix}lti_tool_deployment_org",
"create table {$CFG->dbprefix}lti_tool_deployment_org (
tool_deployment_id INTEGER NOT NULL,
org_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_org_const_pk` PRIMARY KEY (tool_deployment_id, org_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_org_indx_1` (org_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_org_indx_2` (tool_deployment_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_org_ibfk_1`
FOREIGN KEY (`tool_deployment_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_deployment` (`tool_deployment_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT,
-- ON DELETE RESTRICT: deleteOrg moves these assignments first.
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_org_ibfk_2`
FOREIGN KEY (`org_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_org` (`org_id`, `key_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
array( "{$CFG->dbprefix}lti_tool_deployment_context",
"create table {$CFG->dbprefix}lti_tool_deployment_context (
tool_deployment_id INTEGER NOT NULL,
context_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_context_const_pk` PRIMARY KEY (tool_deployment_id, context_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_context_indx_1` (context_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_context_indx_2` (tool_deployment_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_context_ibfk_1`
FOREIGN KEY (`tool_deployment_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_deployment` (`tool_deployment_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One row per Dynamic Registration messages[] entry, in source-document order.
// sequence is the array index, starting at 0. It is not a UI sort order.
// message_json keeps the whole parsed descriptor, including placements.
// key_id is copied from the registration. Placements reference
// (message_id, registration_id, key_id), so a placement cannot leave
// this message, this registration, or this tenant.
// An LTI 1.3 registration copies messages from its registration document.
// An LTI 1.1 registration synthesizes them from launch checkboxes
// (resource link, deep link, privacy launch) and placement checkboxes.
// Name, email, grade, and roster checkboxes are claims and scope on
// registration_json, the same document an LTI 1.3 registration stores.
// Whether a deployment releases those is a separate allow-list on
// lti_tool_deployment_claim and lti_tool_deployment_scope.
array( "{$CFG->dbprefix}lti_tool_message",
"create table {$CFG->dbprefix}lti_tool_message (
message_id INTEGER NOT NULL AUTO_INCREMENT,
registration_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
sequence INTEGER NOT NULL,
message_type VARCHAR(255) NOT NULL,
target_link_uri TEXT NULL,
label TEXT NULL,
icon_uri TEXT NULL,
message_json JSON NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_const_pk` PRIMARY KEY (message_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_const_1` UNIQUE (registration_id, sequence),
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_const_2` UNIQUE (message_id, registration_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_message_indx_1` (message_type),
INDEX `{$CFG->dbprefix}lti_tool_message_indx_2` (registration_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_ibfk_1`
FOREIGN KEY (`registration_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_registration` (`registration_id`, `key_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One placement this message can appear in. Several rows share one message.
// message_json still holds the original placements array.
// The same message type may occur more than once on a registration, so a
// placement string is not an identity. This row is.
array( "{$CFG->dbprefix}lti_tool_message_placement",
"create table {$CFG->dbprefix}lti_tool_message_placement (
message_placement_id INTEGER NOT NULL AUTO_INCREMENT,
message_id INTEGER NOT NULL,
registration_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
placement VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_placement_const_pk` PRIMARY KEY (message_placement_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_placement_const_1` UNIQUE (message_id, placement),
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_placement_const_2` UNIQUE (message_placement_id, registration_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_message_placement_indx_1` (message_id, registration_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_message_placement_ibfk_1`
FOREIGN KEY (`message_id`, `registration_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_message` (`message_id`, `registration_id`, `key_id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// Which registered message placements a deployment has enabled.
// This is not where the deployment may be used. Org and course scope stay
// on lti_tool_deployment_org and lti_tool_deployment_context.
// registration_id and key_id are copied from the deployment and must match
// the placement, so a deployment cannot enable another registration or tenant.
// Deleting the message, the placement, or the deployment removes the enablement.
array( "{$CFG->dbprefix}lti_tool_deployment_placement",
"create table {$CFG->dbprefix}lti_tool_deployment_placement (
tool_deployment_id INTEGER NOT NULL,
message_placement_id INTEGER NOT NULL,
registration_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL,
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_placement_const_pk` PRIMARY KEY (tool_deployment_id, message_placement_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_placement_indx_1` (tool_deployment_id, registration_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_placement_indx_2` (message_placement_id, registration_id, key_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_placement_ibfk_1`
FOREIGN KEY (`tool_deployment_id`, `registration_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_deployment` (`tool_deployment_id`, `registration_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_placement_ibfk_2`
FOREIGN KEY (`message_placement_id`, `registration_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_message_placement` (`message_placement_id`, `registration_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// The admin's choice to release a claim the registration asked for.
// A row means this deployment allows it. No row means it stays blocked.
// iss and sub are not stored here. They are always sent.
// registration_id and key_id match the deployment, so the grant cannot
// move to another registration or tenant.
array( "{$CFG->dbprefix}lti_tool_deployment_claim",
"create table {$CFG->dbprefix}lti_tool_deployment_claim (
tool_deployment_id INTEGER NOT NULL,
registration_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
claim VARCHAR(64) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_claim_const_pk` PRIMARY KEY (tool_deployment_id, claim),
INDEX `{$CFG->dbprefix}lti_tool_deployment_claim_indx_1` (tool_deployment_id, registration_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_claim_indx_2` (registration_id, claim),
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_claim_ibfk_1`
FOREIGN KEY (`tool_deployment_id`, `registration_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_deployment` (`tool_deployment_id`, `registration_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// The admin's choice to grant a service scope the registration asked for.
// A row means this deployment allows that scope URI. No row means it stays blocked.
array( "{$CFG->dbprefix}lti_tool_deployment_scope",
"create table {$CFG->dbprefix}lti_tool_deployment_scope (
tool_deployment_id INTEGER NOT NULL,
registration_id INTEGER NOT NULL,
key_id INTEGER NOT NULL,
scope VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_scope_const_pk` PRIMARY KEY (tool_deployment_id, scope),
INDEX `{$CFG->dbprefix}lti_tool_deployment_scope_indx_1` (tool_deployment_id, registration_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_deployment_scope_indx_2` (registration_id, scope),
CONSTRAINT `{$CFG->dbprefix}lti_tool_deployment_scope_ibfk_1`
FOREIGN KEY (`tool_deployment_id`, `registration_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_deployment` (`tool_deployment_id`, `registration_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// Append-only raw Dynamic Registration traffic. payload_text is LONGTEXT, not
// JSON, so a body that is not valid JSON is still stored.
// registration_id stays nullable and is set null when the registration is
// deleted. cc_import_log cascades away with its import. This log is the
// certification record, so the payload text survives the registration row.
array( "{$CFG->dbprefix}lti_tool_registration_log",
"create table {$CFG->dbprefix}lti_tool_registration_log (
log_id INTEGER NOT NULL AUTO_INCREMENT,
registration_id INTEGER NULL,
sequence INTEGER NOT NULL,
direction VARCHAR(16) NOT NULL,
phase VARCHAR(64) NOT NULL,
content_type VARCHAR(255) NULL,
http_status INTEGER NULL,
payload_text LONGTEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_log_const_pk` PRIMARY KEY (log_id),
INDEX `{$CFG->dbprefix}lti_tool_registration_log_indx_1` (registration_id, sequence),
INDEX `{$CFG->dbprefix}lti_tool_registration_log_indx_2` (created_at),
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_log_ibfk_1`
FOREIGN KEY (`registration_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_registration` (`registration_id`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
// One-time IMS Dynamic Registration token. The registration row does not
// exist yet. The tool POSTs with this token, and only then is the tool created.
// token_sha256 is the lookup. The raw token is not stored.
// owner_org_id and owner_context_id match lti_tool_registration: tenant, one
// organization, or one course. Both set is rejected.
// used_at stays null until the POST is stored. registration_id is filled then.
array( "{$CFG->dbprefix}lti_tool_registration_token",
"create table {$CFG->dbprefix}lti_tool_registration_token (
token_id INTEGER NOT NULL AUTO_INCREMENT,
token_sha256 CHAR(64) NOT NULL,
key_id INTEGER NOT NULL,
owner_org_id INTEGER NULL,
owner_context_id INTEGER NULL,
created_by_user_id INTEGER NULL,
tool_url TEXT NOT NULL,
expires_at TIMESTAMP NOT NULL,
used_at TIMESTAMP NULL,
registration_id INTEGER NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_token_const_pk` PRIMARY KEY (token_id),
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_token_const_1` UNIQUE (token_sha256),
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_token_chk_1` CHECK (
owner_org_id IS NULL OR owner_context_id IS NULL
),
INDEX `{$CFG->dbprefix}lti_tool_registration_token_indx_1` (key_id),
INDEX `{$CFG->dbprefix}lti_tool_registration_token_indx_2` (owner_context_id, key_id),
INDEX `{$CFG->dbprefix}lti_tool_registration_token_indx_3` (expires_at),
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_token_ibfk_1`
FOREIGN KEY (`key_id`)
REFERENCES `{$CFG->dbprefix}lti_key` (`key_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
-- ON UPDATE RESTRICT: chk_1 names these columns. MySQL error 3823 rejects
-- any other referential action on a column named by a CHECK.
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_token_ibfk_2`
FOREIGN KEY (`owner_org_id`, `key_id`)
REFERENCES `{$CFG->dbprefix}lti_org` (`org_id`, `key_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT,
-- The course-owner foreign key is added in DATABASE_UPGRADE. An existing
-- lti_context must gain (context_id, key_id) before that key can be added.
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_token_ibfk_4`
FOREIGN KEY (`created_by_user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `{$CFG->dbprefix}lti_tool_registration_token_ibfk_5`
FOREIGN KEY (`registration_id`)
REFERENCES `{$CFG->dbprefix}lti_tool_registration` (`registration_id`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET=utf8"),
);
// Called after a table has been created...
$DATABASE_POST_CREATE = function($table) {
global $CFG, $PDOX;
if ( $table == "{$CFG->dbprefix}lti_key") {
$shaval = lti_sha256('12345');
$guid_12345 = \Tsugi\Core\Guid::uuid7();
$sql= "insert into {$CFG->dbprefix}lti_key (key_sha256, key_key, secret, guid) values
( '$shaval', '12345', 'secret', UNHEX('{$guid_12345}'))";
error_log("Post-create: ".$sql);
echo("Post-create: ".$sql."
\n");
$q = $PDOX->queryDie($sql);
// Secret is big ugly string for the google key - in case we launch internally in Koseu
$secret = bin2hex(openssl_random_pseudo_bytes(16));
$shaval = lti_sha256('google.com');
$guid_google = \Tsugi\Core\Guid::uuid7();
$sql = "insert into {$CFG->dbprefix}lti_key (key_sha256, secret, key_key, guid) values
( '$shaval', '$secret', 'google.com', UNHEX('{$guid_google}'))";
error_log("Post-create: ".$sql);
echo("Post-create: ".$sql."
\n");
$q = $PDOX->queryDie($sql);
}
if ( $table == "{$CFG->dbprefix}lti_nonce") {
$sql = "CREATE INDEX `{$CFG->dbprefix}nonce_indx_1` ON {$CFG->dbprefix}lti_nonce ( nonce ) USING HASH";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryDie($sql);
// PGSQL has no CRON feature - we depend on the probabilistic cleanup
if ( $PDOX->isMySQL() ) {
$sql = "CREATE EVENT IF NOT EXISTS {$CFG->dbprefix}lti_nonce_auto
ON SCHEDULE EVERY 1 HOUR DO
DELETE FROM {$CFG->dbprefix}lti_nonce WHERE created_at < (UNIX_TIMESTAMP() - 3600)";
error_log("Post-create: ".$sql);
echo("Post-create: ".$sql."
\n");
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
}
}
};
$DATABASE_UPGRADE = function($oldversion) {
global $CFG, $PDOX;
// Removed the 2014 - 2017 migrations - 2019-06-15
// This is a place to make sure added fields are present
// if you add a field to a table, put it in here and it will be auto-added
$add_some_fields = array(
array('lti_key', 'key_title', 'TEXT NULL'),
array('lti_link', 'lti13_lineitem', 'TEXT NULL'),
array('lti_context', 'lti13_lineitems', 'TEXT NULL'),
array('lti_context', 'user_json', 'MEDIUMTEXT NULL'),
array('lti_context', 'lti13_membership_url', 'TEXT NULL'),
array('lti_key', 'deploy_key', 'TEXT NULL'),
array('lti_key', 'user_json', 'MEDIUMTEXT NULL'),
// 2021-08-26 - Add key-local security arrangements
array('lti_key', 'lms_issuer', 'TEXT NULL'),
array('lti_key', 'lms_issuer_sha256', 'CHAR(64) NULL'),
array('lti_key', 'lms_client', 'TEXT NULL'),
array('lti_key', 'lms_oidc_auth', 'TEXT NULL'),
array('lti_key', 'lms_keyset_url', 'TEXT NULL'),
array('lti_key', 'lms_token_url', 'TEXT NULL'),
array('lti_key', 'lms_token_audience', 'TEXT NULL'),
// Tenant/key cache of the LMS signing data
array('lti_key', 'lms_cache_keyset', 'TEXT NULL'),
array('lti_key', 'lms_cache_pubkey', 'TEXT NULL'),
array('lti_key', 'lms_cache_kid', 'TEXT NULL'),
array('lti_keyset', 'keyset_title', 'TEXT NULL'),
array('lti_result', 'grading_progress', 'VARCHAR(30) NOT NULL DEFAULT \'NotReady\''),
array('lti_result', 'activity_progress', 'VARCHAR(30) NOT NULL DEFAULT \'Initialized\''),
array('lti_link', 'score_maximum', 'DOUBLE NULL'),
// 2025-03-10 AGS Phase 1: result schema for Assignments and Grades Service
array('lti_result', 'result_maximum', 'DOUBLE NULL'),
array('lti_result', 'lti13_result_id', 'TEXT NULL'),
array('lti_result', 'scoring_user_id', 'INTEGER NULL'),
array('lti_result', 'score_timestamp', 'TIMESTAMP NULL'),
array('lti_result', 'submitted_at', 'TIMESTAMP NULL'),
// 2023-05-11
array('lti_key', 'unlock_code', 'MEDIUMTEXT NULL'),
// 2023-07-29 Adding Context Groups Service
array('lti_context', 'lti13_context_groups_url', 'TEXT NULL'),
// 2024-09-17
array('lti_result', 'attempts', 'INTEGER NULL'),
array('lti_result', 'attempted_at', 'TIMESTAMP NULL'),
// 2025-03-11 AGS LineItem due dates (startDateTime/endDateTime)
array('lti_link', 'start_datetime', 'TIMESTAMP NULL'),
array('lti_link', 'end_datetime', 'TIMESTAMP NULL'),
// 2026-03-29 Per-context and per-membership visibility for due dates (existing rows default to on)
array('lti_context', 'viewDueDates', 'TINYINT(1) NOT NULL DEFAULT 1'),
array('lti_membership', 'viewDueDates', 'TINYINT(1) NOT NULL DEFAULT 1'),
// 2026-08-28 Active course manifest version (NULL = file-based $CFG->lessons)
array('lti_context', 'manifest_id', 'INTEGER NULL'),
// 2026-09-23 Short course title (first six characters seed the home label)
array('lti_context', 'short_title', 'VARCHAR(64) NULL'),
// 2026-08-28 Named course theme key (NULL = site $CFG->theme)
array('manifest', 'theme', 'VARCHAR(64) NULL'),
// 2026-09-15 Teacher-edited course top nav JSON (NULL = default)
array('manifest', 'navigation', 'MEDIUMTEXT NULL'),
// 2026-08-28 User-level capability to create site-login courses
array('lti_user', 'create_courses', 'TINYINT(1) NOT NULL DEFAULT 0'),
// 2026-09-18 Last time this user entered this course (site-login flyout recency)
array('lti_membership', 'visited_at', 'TIMESTAMP NULL'),
// 2026-09-23 Gradebook workflow on the link. Existing rows stay published.
// start_datetime / end_datetime are left alone; they are still the live due UI.
array('lti_link', 'published', 'TINYINT(1) NOT NULL DEFAULT 1'),
array('lti_link', 'hidden', 'TINYINT(1) NOT NULL DEFAULT 0'),
array('lti_link', 'grades_released', 'TINYINT(1) NULL'),
array('lti_link', 'available_start_datetime', 'TIMESTAMP NULL'),
array('lti_link', 'available_end_datetime', 'TIMESTAMP NULL'),
array('lti_link', 'submission_start_datetime', 'TIMESTAMP NULL'),
array('lti_link', 'submission_end_datetime', 'TIMESTAMP NULL'),
array('lti_link', 'due_datetime', 'TIMESTAMP NULL'),
array('lti_link', 'ags_resource_id', 'VARCHAR(256) NULL'),
array('lti_link', 'ags_tag', 'VARCHAR(256) NULL'),
// 2026-10-13 Optional grade category. NULL stays uncategorized.
// The foreign key is added below, after lti_category exists.
array('lti_link', 'category_id', 'INTEGER NULL'),
// 2026-10-18 LTI 1.1 outcome flag. Existing links stay 0 until a launch
// stores service_id and a sourcedid. Old results are not scanned.
array('lti_link', 'upward', 'TINYINT(1) NOT NULL DEFAULT 0'),
// 2026-10-28 Classroom coursework id for a manifest course column.
// The resource link id stays in link_key.
array('lti_link', 'gc_coursework', 'VARCHAR(64) NULL'),
array('lti_link', 'gc_course', 'VARCHAR(64) NULL'),
// 2026-10-13 Extra credit is outside the 100. Existing categories stay regular.
array('lti_category', 'extra_credit', 'TINYINT(1) NOT NULL DEFAULT 0'),
// 2026-10-13 Grade book category order. Lower numbers come first.
array('lti_category', 'position', 'INTEGER NOT NULL DEFAULT 0'),
// 2026-09-23 Numerator and AGS submission.startedAt on the result.
array('lti_result', 'score_given', 'DOUBLE NULL'),
array('lti_result', 'started_at', 'TIMESTAMP NULL'),
// 2026-09-30 Optional organization placement. Existing courses stay unplaced.
array('lti_context', 'org_id', 'INTEGER NULL'),
// 2026-10-18 Optional earlier course. Same type as context_id. No foreign key.
array('lti_context', 'previous_context_id', 'INTEGER NULL'),
// 2026-10-24 Plus course. Existing courses stay ordinary.
array('lti_context', 'plus_course', 'TINYINT(1) NOT NULL DEFAULT 0'),
array('lti_context', 'lti13_deployment_id', 'TEXT NULL'),
array('lti_context', 'plus_launch_link_id', 'INTEGER NULL'),
array('lti_context', 'nrps_at', 'TIMESTAMP NULL'),
array('lti_context', 'timezone', 'VARCHAR(64) NULL'),
// 2026-11-03 This course allows anonymous lesson preview. Existing courses stay closed.
array('lti_context', 'anonymous_lessons', 'TINYINT(1) NOT NULL DEFAULT 0'),
array('lti_key', 'timezone', 'VARCHAR(64) NULL'),
array('lti_key', 'plus', 'TINYINT(1) NOT NULL DEFAULT 0'),
// 2026-10-26 Last Plus score or line-item error shown in the grade book.
array('lti_result', 'server_status', 'VARCHAR(512) NULL'),
// 2026-10-27 Last Classroom refresh error, and the last successful check.
array('lti_user', 'gc_status', 'VARCHAR(512) NULL'),
array('lti_user', 'gc_checked_at', 'TIMESTAMP NULL'),
// 2026-11-21 Inbound LTI 1.3 registration. Existing keys stay NULL.
// The foreign key is added below. platform_guid is tool_platform.guid, not lti_key.guid.
// lti_registration itself is created from DATABASE_INSTALL.
array('lti_key', 'lti_registration_id', 'INTEGER NULL'),
array('lti_key', 'deployment_status', 'VARCHAR(20) CHARACTER SET ascii COLLATE ascii_bin NULL'),
array('lti_key', 'deployment_approved_at', 'TIMESTAMP NULL'),
array('lti_key', 'platform_guid', 'VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NULL'),
array('lti_key', 'dynamic_registration_unlocked_at', 'TIMESTAMP NULL'),
array('lti_registration', 'title', 'TEXT NULL'),
array('lti_registration', 'notes', 'TEXT NULL'),
);
foreach ( $add_some_fields as $add_field ) {
if (count($add_field) != 3 ) {
echo("Badly formatted add_field");
var_dump($add_field);
continue;
}
$table = $add_field[0];
$column = $add_field[1];
$type = $add_field[2];
if ( $PDOX->columnExists($column, "{$CFG->dbprefix}".$table ) ) continue;
$sql= "ALTER TABLE {$CFG->dbprefix}$table ADD $column $type";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Generally wait a while to drop the fields - there is no rush
$drop_some_fields = array(
array('lti_result', 'lti13_lineitem'),
// 20190610 - Remove lti13 fields from lti_key
// (Yes this is somewhat ironic :) )
array('lti_key', 'lti13_oidc_auth'),
array('lti_key', 'lti13_keyset_url'),
array('lti_key', 'lti13_keyset'),
array('lti_key', 'lti13_platform_pubkey'),
array('lti_key', 'lti13_kid'),
array('lti_key', 'lti13_pubkey'),
array('lti_key', 'lti13_privkey'),
array('lti_key', 'lti13_token_url'),
// Remove from lti2
array('lti_key', 'consumer_profile'),
array('lti_key', 'new_consumer_profile'),
array('lti_key', 'tool_profile'),
array('lti_key', 'new_tool_profile'),
array('lti_key', 'ack'),
// TODO: Twists and turns - remove these after the branch has run for a bit
array('lti_key', 'lms_issuer_key'),
array('lti_key', 'our_pubkey'),
array('lti_key', 'our_privkey'),
array('lti_key', 'our_pubkey_old'),
array('lti_key', 'our_pubkey_old_at'),
array('lti_key', 'our_pubkey_next'),
array('lti_key', 'our_pubkey_next_at'),
array('lti_key', 'our_privkey_next'),
array('lti_key', 'our_token_url'),
array('lti_key', 'our_token_audience'),
array('lti_key', 'platform_issuer_key'),
array('lti_key', 'platform_issuer_client'),
array('lti_key', 'platform_oidc_auth'),
array('lti_key', 'platform_keyset_url'),
array('lti_key', 'platform_keyset'),
array('lti_key', 'platform_kid'),
array('lti_key', 'platform_pubkey'),
array('lti_key', 'lms_deployment_id'),
array('lti_key', 'lms_deployment'),
array('lti_key', 'lms_issuer_client_id'),
array('lti_key', 'lms_issuer_client'),
array('lti_key', 'lms_keyset'),
array('lti_key', 'lms_pubkey'),
array('lti_key', 'lms_kid'),
// TODO: Remove these later - well after 2021-09 / global key signing
// array('lti_issuer', 'lti13_pubkey',),
// array('lti_issuer', 'lti13_privkey',),
);
foreach ( $drop_some_fields as $drop_field ) {
if (count($drop_field) != 2 ) {
echo("Badly formatted drop_field");
var_dump($drop_field);
continue;
}
$table = $drop_field[0];
$column = $drop_field[1];
if ( ! $PDOX->columnExists($column, "{$CFG->dbprefix}".$table ) ) continue;
$sql= "ALTER TABLE {$CFG->dbprefix}$table DROP $column";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Make sure that lti_key has the correct unique indexes
$needed_indexes = array(
'lti_key_const_1' => 'ADD CONSTRAINT `lti_key_const_1` UNIQUE(key_sha256, deploy_sha256)',
);
$indexes = $PDOX->indexes($CFG->dbprefix."lti_key");
// DROP INDEX index_name ON tbl_name
$keep_issuer_index = $PDOX->columnExists('issuer_id', $CFG->dbprefix."lti_key");
// The unique guid key is added later in this upgrade. This pass must not
// drop it when the table already has it.
$keep_guid_index = $CFG->dbprefix."lti_key_const_guid";
foreach($indexes as $index) {
if ( strcasecmp($index, "PRIMARY") == 0 ) continue;
if ( strcasecmp($index, "ibfk") == 0 ) continue;
// lti_key_const_2 backs issuer_id until lti_issuer phase 3 (2026-10-01 UTC)
if ( $keep_issuer_index && $index === $CFG->dbprefix."lti_key_const_2" ) continue;
if ( $index === $keep_guid_index ) continue;
$command = isset($needed_indexes[$index]) ? $needed_indexes[$index] : null;
if ( is_string($command) ) continue;
$sql = "DROP INDEX ".$index." ON ".$CFG->dbprefix."lti_key";
echo($sql."
\n");
error_log($sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal dropping index: ".$q->errorImplode;
error_log($message);
echo($message);
}
}
// ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`)
foreach($needed_indexes as $index => $command) {
if ( in_array($index, $indexes) ) continue;
$sql = "ALTER TABLE ".$CFG->dbprefix."lti_key". " " . $command;
echo($sql."
\n");
error_log($sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal adding index: ".$q->errorImplode;
error_log($message);
echo($message);
}
}
// Old-school migrations
if ( $oldversion < 201801271430 ) {
$sql= "ALTER TABLE {$CFG->dbprefix}mail_bulk
DROP FOREIGN KEY `{$CFG->dbprefix}mail_bulk_ibfk_2`";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
$sql= "ALTER TABLE {$CFG->dbprefix}mail_bulk ADD
CONSTRAINT `{$CFG->dbprefix}mail_bulk_ibfk_2`
FOREIGN KEY (`user_id`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
$sql= "ALTER TABLE {$CFG->dbprefix}mail_sent
DROP FOREIGN KEY `{$CFG->dbprefix}mail_sent_ibfk_2`";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
$sql= "ALTER TABLE {$CFG->dbprefix}mail_sent ADD
CONSTRAINT `{$CFG->dbprefix}mail_sent_ibfk_2`
FOREIGN KEY (`link_id`)
REFERENCES `{$CFG->dbprefix}lti_link` (`link_id`)
ON DELETE CASCADE ON UPDATE CASCADE";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
$sql= "ALTER TABLE {$CFG->dbprefix}mail_sent
DROP FOREIGN KEY `{$CFG->dbprefix}mail_sent_ibfk_3`";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
$sql= "ALTER TABLE {$CFG->dbprefix}mail_sent ADD
CONSTRAINT `{$CFG->dbprefix}mail_sent_ibfk_3`
FOREIGN KEY (`user_to`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
$sql= "ALTER TABLE {$CFG->dbprefix}mail_sent
DROP FOREIGN KEY `{$CFG->dbprefix}mail_sent_ibfk_4`";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
$sql= "ALTER TABLE {$CFG->dbprefix}mail_sent ADD
CONSTRAINT `{$CFG->dbprefix}mail_sent_ibfk_4`
FOREIGN KEY (`user_from`)
REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating event: ".$q->errorImplode;
error_log($message);
echo($message);
}
}
// Add the deleted_at column to columns if they are not there.
// Double check created_at and updated_at
$tables = array( 'lti_key', 'lti_context', 'lti_link', 'lti_user',
'lti_membership', 'lti_service', 'lti_result', 'lti_domain');
foreach($tables as $table) {
if ( ! $PDOX->columnExists('deleted_at', "{$CFG->dbprefix}".$table) ) {
$sql= "ALTER TABLE {$CFG->dbprefix}{$table} ADD deleted_at TIMESTAMP NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryDie($sql);
}
if ( ! $PDOX->columnExists('updated_at', "{$CFG->dbprefix}".$table) ) {
$sql= "ALTER TABLE {$CFG->dbprefix}{$table} ADD updated_at TIMESTAMP NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryDie($sql);
}
if ( ! $PDOX->columnExists('created_at', "{$CFG->dbprefix}".$table) ) {
$sql= "ALTER TABLE {$CFG->dbprefix}{$table} ADD created_at NOT NULL DEFAULT CURRENT_TIMESTAMP";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryDie($sql);
}
}
// New for the LTI Advantage issuer refactor
if ( ! $PDOX->columnExists('deploy_sha256', "{$CFG->dbprefix}lti_key") ) {
$sql= "ALTER TABLE {$CFG->dbprefix}lti_key ADD deploy_sha256 CHAR(64) NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Version 201905111039 improvements - Prepare for issuer refactor
if ( $oldversion < 201905111039 ) {
$sql= "ALTER TABLE {$CFG->dbprefix}lti_key MODIFY key_sha256 CHAR(64) NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
$sql= "ALTER TABLE {$CFG->dbprefix}lti_key MODIFY key_key TEXT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Legacy lti_issuer column renames and issuer_guid (only while table still exists).
// information_schema avoids SHOW COLUMNS, which logs SQLSTATE 42S02 after phase 3.
$issuer_table = "{$CFG->dbprefix}lti_issuer";
$issuer_table_row = $PDOX->rowDie(
"SELECT TABLE_NAME AS table_name
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :table_name",
array(':table_name' => $issuer_table)
);
$have_issuer_table = is_array($issuer_table_row);
if ( $have_issuer_table ) {
// Note still have to edit the entry to get the sha256 properly set
if ( $PDOX->columnExists('issuer_issuer', $issuer_table) &&
! $PDOX->columnExists('issuer_key', $issuer_table) ) {
$sql= "ALTER TABLE {$issuer_table} CHANGE issuer_issuer issuer_key TEXT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
if ( $PDOX->columnExists('issuer_client_id', $issuer_table) &&
! $PDOX->columnExists('issuer_client', $issuer_table) ) {
$sql= "ALTER TABLE {$issuer_table} CHANGE issuer_client_id issuer_client TEXT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Add the issuer_guid field
if ( ! $PDOX->columnExists('issuer_guid', $issuer_table) ) {
$sql= "ALTER TABLE {$issuer_table} ADD issuer_guid CHAR(36) NULL DEFAULT '42'";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
$sql= "UPDATE {$issuer_table} SET issuer_guid=(SELECT UUID()) WHERE issuer_guid='42'";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
$sql= "ALTER TABLE {$issuer_table} ADD
CONSTRAINT `{$CFG->dbprefix}lti_issuer_const_guid`
UNIQUE (`issuer_guid`)";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
// CONSTRAINT `{$CFG->dbprefix}lti_issuer_const_1` UNIQUE(issuer_sha256),
$sql= "ALTER TABLE {$issuer_table} DROP KEY `{$CFG->dbprefix}lti_issuer_const_1`";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
} // end legacy lti_issuer column migrations
if ( $PDOX->columnExists('user_subject', "{$CFG->dbprefix}lti_user") &&
! $PDOX->columnExists('subject_key', "{$CFG->dbprefix}lti_user") ) {
$sql= "ALTER TABLE {$CFG->dbprefix}lti_user CHANGE user_subject subject_key TEXT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
if ( ! $PDOX->columnExists('subject_sha256', "{$CFG->dbprefix}lti_user") ) {
$sql= "ALTER TABLE {$CFG->dbprefix}lti_user ADD subject_sha256 CHAR(64) NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
$sql= "ALTER TABLE {$CFG->dbprefix}lti_user ADD
CONSTRAINT `{$CFG->dbprefix}lti_user_const_2` UNIQUE(key_id, subject_sha256)";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Version 201905270930 improvements
if ( $oldversion < 201905270930 ) {
$sql= "ALTER TABLE {$CFG->dbprefix}lti_user MODIFY user_key TEXT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
$sql= "ALTER TABLE {$CFG->dbprefix}lti_user MODIFY user_sha256 CHAR(64) NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
$sql= "ALTER TABLE {$CFG->dbprefix}lti_user MODIFY subject_sha256 CHAR(64) NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Version 201907070902 improvements - Bad CREATE statement
if ( $oldversion < 201907070902 ) {
$sql= "ALTER TABLE {$CFG->dbprefix}lti_key MODIFY key_key TEXT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
}
// Auto populate and/or rotate the lti_keyset data
echo("Checking lti_keyset
\n");
$success = \Tsugi\Core\Keyset::maintain();
if ( is_string($success) ) {
error_log("Unable to generate public/private pair: ".$success);
echo("Unable to generate public/private pair: ".$success."
\n");
}
// Add indexes that might not be there
$indexes_to_create = array(
"{$CFG->dbprefix}lti_result_indx_link_deleted_grade" =>
"CREATE INDEX `{$CFG->dbprefix}lti_result_indx_link_deleted_grade` ON {$CFG->dbprefix}lti_result (link_id, deleted, grade)",
"{$CFG->dbprefix}lti_result_indx_link_user_grade" =>
"CREATE INDEX `{$CFG->dbprefix}lti_result_indx_link_user_grade` ON {$CFG->dbprefix}lti_result (link_id, user_id, grade, deleted)",
// Grade list pages sort one link by updated_at and then LIMIT.
// UNIQUE(link_id, user_id) finds the rows but cannot keep that order.
"{$CFG->dbprefix}lti_result_indx_link_updated" =>
"CREATE INDEX `{$CFG->dbprefix}lti_result_indx_link_updated` ON {$CFG->dbprefix}lti_result (link_id, updated_at)"
);
foreach($indexes_to_create as $index_name => $sql) {
if ( ! $PDOX->indexExists($index_name, "{$CFG->dbprefix}lti_result") ) {
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating index: ".$q->errorImplode;
error_log($message);
echo($message."
\n");
}
}
}
// 2025-03-10 AGS Phase 1: Replace unused TINYINT grading/activity_progress with VARCHAR(30)
// Two separate checks: if TINYINT drop it, if column missing add it. Columns were never read/written.
if ( $PDOX->isMySQL() ) {
if ( $PDOX->columnExists('grading_progress', "{$CFG->dbprefix}lti_result") ) {
$grading_col = $PDOX->describeColumn('grading_progress', "{$CFG->dbprefix}lti_result");
$grading_type = $grading_col ? strtolower(\Tsugi\Util\U::get($grading_col, "Type", "")) : "";
if ( strpos($grading_type, 'tinyint') !== false ) {
$sql = "ALTER TABLE {$CFG->dbprefix}lti_result DROP COLUMN grading_progress";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$PDOX->queryReturnError($sql);
}
}
if ( ! $PDOX->columnExists('grading_progress', "{$CFG->dbprefix}lti_result") ) {
$sql = "ALTER TABLE {$CFG->dbprefix}lti_result ADD COLUMN grading_progress VARCHAR(30) NOT NULL DEFAULT 'NotReady'";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$PDOX->queryReturnError($sql);
}
if ( $PDOX->columnExists('activity_progress', "{$CFG->dbprefix}lti_result") ) {
$activity_col = $PDOX->describeColumn('activity_progress', "{$CFG->dbprefix}lti_result");
$activity_type = $activity_col ? strtolower(\Tsugi\Util\U::get($activity_col, "Type", "")) : "";
if ( strpos($activity_type, 'tinyint') !== false ) {
$sql = "ALTER TABLE {$CFG->dbprefix}lti_result DROP COLUMN activity_progress";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$PDOX->queryReturnError($sql);
}
}
if ( ! $PDOX->columnExists('activity_progress', "{$CFG->dbprefix}lti_result") ) {
$sql = "ALTER TABLE {$CFG->dbprefix}lti_result ADD COLUMN activity_progress VARCHAR(30) NOT NULL DEFAULT 'Initialized'";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$PDOX->queryReturnError($sql);
}
}
// The score comment lives in lti_result.comment. Copy note into comment once,
// in the upgrade that creates the column, then leave both columns alone.
$result_table = "{$CFG->dbprefix}lti_result";
if ( $PDOX->columnExists('note', $result_table) && ! $PDOX->columnExists('comment', $result_table) ) {
$sql = "ALTER TABLE {$result_table} ADD comment MEDIUMTEXT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( $q->success ) {
$sql = "UPDATE {$result_table} SET comment = note WHERE note IS NOT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( $q->success ) {
$sql = "UPDATE {$result_table} SET note = NULL WHERE note IS NOT NULL";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$PDOX->queryReturnError($sql);
}
}
}
// Add FK for scoring_user_id if column exists and FK does not
if ( $PDOX->columnExists('scoring_user_id', "{$CFG->dbprefix}lti_result") ) {
$indexes = $PDOX->indexes("{$CFG->dbprefix}lti_result");
$fk_name = "{$CFG->dbprefix}lti_result_ibfk_4";
if ( ! in_array($fk_name, $indexes) ) {
$sql = "ALTER TABLE {$CFG->dbprefix}lti_result ADD CONSTRAINT `{$fk_name}`
FOREIGN KEY (`scoring_user_id`) REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
ON DELETE SET NULL ON UPDATE CASCADE";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal adding scoring_user_id FK: ".$q->errorImplode;
error_log($message);
echo($message."
\n");
}
}
}
// Issue #226 phase 1: copy lti_issuer data into lti_key for all linked keys (idempotent).
// Clears issuer_id, lms_issuer, and lms_issuer_sha256 on lti_key; copies other lms_*
// from issuer (issuer precedence, key fallback). Safe to run until phase 3 drops the table.
if ( $have_issuer_table
&& $PDOX->columnExists('lms_issuer', "{$CFG->dbprefix}lti_key") ) {
$lti_migration_coalesce = function($issuer_val, $key_val) {
if ( $issuer_val !== null && $issuer_val !== '' && strlen(trim((string) $issuer_val)) > 0 ) {
return $issuer_val;
}
if ( $key_val !== null && $key_val !== '' && strlen(trim((string) $key_val)) > 0 ) {
return $key_val;
}
return null;
};
$sql = "SELECT I.*, K.key_id,
K.lms_client AS key_lms_client, K.lms_oidc_auth AS key_lms_oidc_auth,
K.lms_keyset_url AS key_lms_keyset_url, K.lms_token_url AS key_lms_token_url,
K.lms_token_audience AS key_lms_token_audience,
C.keys_per_issuer
FROM {$issuer_table} AS I
INNER JOIN {$CFG->dbprefix}lti_key AS K ON I.issuer_id = K.issuer_id
AND (K.deleted IS NULL OR K.deleted = 0)
INNER JOIN (
SELECT I2.issuer_id, COUNT(K2.key_id) AS keys_per_issuer
FROM {$issuer_table} AS I2
LEFT JOIN {$CFG->dbprefix}lti_key AS K2 ON I2.issuer_id = K2.issuer_id
AND (K2.deleted IS NULL OR K2.deleted = 0)
WHERE (I2.deleted IS NULL OR I2.deleted = 0)
GROUP BY I2.issuer_id
) AS C ON C.issuer_id = I.issuer_id
WHERE (I.deleted IS NULL OR I.deleted = 0)
AND K.issuer_id IS NOT NULL AND K.issuer_id > 0
ORDER BY I.issuer_id ASC, K.key_id ASC";
$stmt = $PDOX->queryReturnError($sql, false, false);
$moved = 0;
if ( ! $stmt || ! $stmt->success ) {
$err = ($stmt && isset($stmt->errorImplode)) ? $stmt->errorImplode : 'unknown error';
echo("lti_issuer migration SELECT failed: ".htmlentities($err)."
\n");
error_log('lti_issuer migration SELECT failed: '.$err);
} else {
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$row_count = is_array($rows) ? count($rows) : 0;
if ( is_array($rows) && $row_count > 0 ) {
$multi_issuers = array();
foreach ( $rows as $row ) {
$keys_per_issuer = (int) $row['keys_per_issuer'];
if ( $keys_per_issuer > 1 ) {
$multi_issuers[$row['issuer_id']] = $keys_per_issuer;
}
}
echo("lti_issuer migration: {$row_count} lti_key row(s) still linked to lti_issuer
\n");
error_log("lti_issuer migration: {$row_count} lti_key row(s) still linked to lti_issuer");
if ( count($multi_issuers) > 0 ) {
foreach ( $multi_issuers as $mid => $mcount ) {
echo("lti_issuer migration WARNING: lti_issuer issuer_id={$mid}"
." has {$mcount} lti_key rows pointing to it (multi-key issuer)
\n");
error_log("lti_issuer migration WARNING: lti_issuer issuer_id={$mid}"
." has {$mcount} lti_key rows pointing to it (multi-key issuer)");
}
}
$update_sql = "UPDATE {$CFG->dbprefix}lti_key SET
issuer_id = NULL,
lms_issuer = NULL,
lms_issuer_sha256 = NULL,
lms_client = :lms_client,
lms_oidc_auth = :lms_oidc_auth,
lms_keyset_url = :lms_keyset_url,
lms_token_url = :lms_token_url,
lms_token_audience = :lms_token_audience,
updated_at = NOW()
WHERE key_id = :ID AND issuer_id = :old_issuer_id";
foreach ( $rows as $row ) {
$key_id = $row['key_id'];
$old_issuer_id = $row['issuer_id'];
$values = array(
':ID' => $key_id,
':old_issuer_id' => $old_issuer_id,
':lms_client' => $lti_migration_coalesce($row['issuer_client'], $row['key_lms_client']),
':lms_oidc_auth' => $lti_migration_coalesce($row['lti13_oidc_auth'], $row['key_lms_oidc_auth']),
':lms_keyset_url' => $lti_migration_coalesce($row['lti13_keyset_url'], $row['key_lms_keyset_url']),
':lms_token_url' => $lti_migration_coalesce($row['lti13_token_url'], $row['key_lms_token_url']),
':lms_token_audience' => $lti_migration_coalesce($row['lti13_token_audience'], $row['key_lms_token_audience']),
);
$q = $PDOX->queryReturnError($update_sql, $values);
if ( ! $q->success ) {
echo("lti_issuer migration UPDATE failed for lti_key key_id={$key_id}"
." (issuer_id was {$old_issuer_id}): "
.htmlentities($q->errorImplode)."
\n");
error_log("lti_issuer migration UPDATE failed for lti_key key_id={$key_id}"
." (issuer_id was {$old_issuer_id}): ".$q->errorImplode);
} else if ( $q->rowCount() > 0 ) {
$moved++;
}
}
}
}
if ( $moved > 0 ) {
$summary = 'lti_issuer migration complete: broke FK on '.$moved.' lti_key row(s)'
.' (issuer_id nulled, LMS endpoints copied from lti_issuer)';
echo($summary."
\n");
error_log($summary);
}
}
// Issue #226 phase 3: drop lti_issuer table and issuer_id column (on or after 2026-10-01 UTC)
$issuer_drop_after = gmmktime(0, 0, 0, 10, 1, 2026);
if ( time() >= $issuer_drop_after ) {
$key_table = "{$CFG->dbprefix}lti_key";
$have_issuer_id = $PDOX->columnExists('issuer_id', $key_table);
if ( $have_issuer_table || $have_issuer_id ) {
if ( $have_issuer_id ) {
$linked_stmt = $PDOX->queryReturnError(
"SELECT COUNT(*) AS linked_key_count FROM {$key_table}
WHERE issuer_id IS NOT NULL AND issuer_id > 0
AND (deleted IS NULL OR deleted = 0)",
false,
false
);
if ( $linked_stmt && $linked_stmt->success ) {
$linked_row = $linked_stmt->fetch(\PDO::FETCH_ASSOC);
$linked_key_count = (int) \Tsugi\Util\U::get($linked_row, 'linked_key_count', 0);
if ( $linked_key_count > 0 ) {
$warn = "lti_issuer phase 3 WARNING: {$linked_key_count} lti_key row(s)"
." still have issuer_id set; dropping legacy schema anyway";
echo(htmlentities($warn)."
\n");
error_log($warn);
}
}
}
// InnoDB often has no index named lti_key_ibfk_1. The foreign key
// reuses unique index lti_key_const_2 (issuer_id, deploy_sha256),
// so SHOW INDEX never lists the constraint. Look it up by the
// referenced table, then drop it before the index and column.
$issuer_fks = $PDOX->allRowsDie(
"SELECT DISTINCT CONSTRAINT_NAME AS constraint_name
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :table_name
AND REFERENCED_TABLE_NAME = :ref_table",
array(
':table_name' => $key_table,
':ref_table' => $issuer_table,
)
);
foreach ( $issuer_fks as $fk_row ) {
$fk_name = \Tsugi\Util\U::get($fk_row, 'constraint_name');
if ( ! is_string($fk_name) || $fk_name === '' ) continue;
$sql = "ALTER TABLE {$key_table} DROP FOREIGN KEY `{$fk_name}`";
echo("Upgrading: ".htmlentities($sql)."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "lti_issuer phase 3 drop FK failed: ".$q->errorImplode;
error_log($message);
echo(htmlentities($message)."
\n");
}
}
$key_indexes = $PDOX->indexes($key_table);
$const2_name = "{$CFG->dbprefix}lti_key_const_2";
if ( in_array($const2_name, $key_indexes) ) {
$sql = "ALTER TABLE {$key_table} DROP INDEX `{$const2_name}`";
echo("Upgrading: ".htmlentities($sql)."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "lti_issuer phase 3 drop index failed: ".$q->errorImplode;
error_log($message);
echo(htmlentities($message)."
\n");
}
}
if ( $have_issuer_id ) {
$sql = "ALTER TABLE {$key_table} DROP COLUMN issuer_id";
echo("Upgrading: ".htmlentities($sql)."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "lti_issuer phase 3 drop issuer_id failed: ".$q->errorImplode;
error_log($message);
echo(htmlentities($message)."
\n");
}
}
if ( $have_issuer_table ) {
$sql = "DROP TABLE IF EXISTS {$issuer_table}";
echo("Upgrading: ".htmlentities($sql)."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "lti_issuer phase 3 drop table failed: ".$q->errorImplode;
error_log($message);
echo(htmlentities($message)."
\n");
} else {
$summary = 'lti_issuer phase 3 complete: dropped lti_issuer table'
.($have_issuer_id ? ' and lti_key.issuer_id column' : '');
echo(htmlentities($summary)."
\n");
error_log($summary);
}
}
}
}
// Existing courses gain an optional org, and (context_id, key_id) so a
// new-table foreign key can stay on that tenant. lti_org and lti_tool_*
// are created from $DATABASE_INSTALL in their final form. The two foreign
// keys below name lti_context, so they wait until that key exists.
$p = $CFG->dbprefix;
$context_table = "{$p}lti_context";
$org_table = "{$p}lti_org";
$deployment_table = "{$p}lti_tool_deployment";
$constraint_exists = function($table, $name) use ($PDOX) {
$sql = "SELECT CONSTRAINT_NAME AS constraint_name
FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :table_name
AND CONSTRAINT_NAME = :constraint_name";
$row = $PDOX->rowDie($sql, array(
':table_name' => $table,
':constraint_name' => $name,
));
return is_array($row);
};
// ON DELETE SET NULL: removing a registration detaches its keys.
$key_table = "{$p}lti_key";
$inbound_table = "{$p}lti_registration";
$key_registration_fk = "{$p}lti_key_ibfk_1";
if ( $PDOX->metadata($key_table) !== false
&& $PDOX->metadata($inbound_table) !== false
&& $PDOX->columnExists('lti_registration_id', $key_table)
&& ! $constraint_exists($key_table, $key_registration_fk) ) {
$sql = "ALTER TABLE {$key_table} ADD CONSTRAINT `{$key_registration_fk}`
FOREIGN KEY (`lti_registration_id`)
REFERENCES `{$inbound_table}` (`lti_registration_id`)
ON DELETE SET NULL ON UPDATE CASCADE";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add {$key_registration_fk}: ".$q->errorImplode."
\n");
}
if ( $PDOX->metadata($org_table) !== false && $PDOX->columnExists('org_id', $context_table) ) {
$org_index = "{$p}lti_context_indx_1";
if ( ! $PDOX->indexExists($org_index, $context_table) ) {
$sql = "ALTER TABLE {$context_table} ADD INDEX `{$org_index}` (`org_id`)";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to index lti_context.org_id: ".$q->errorImplode."
\n");
}
$context_key = "{$p}lti_context_const_2";
if ( ! $PDOX->indexExists($context_key, $context_table) ) {
$sql = "ALTER TABLE {$context_table} ADD CONSTRAINT `{$context_key}` UNIQUE (`context_id`, `key_id`)";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add lti_context (context_id, key_id) key: ".$q->errorImplode."
\n");
}
$token_table = "{$p}lti_tool_registration_token";
$token_context_fk = "{$p}lti_tool_registration_token_ibfk_3";
if ( $PDOX->metadata($token_table) !== false && ! $constraint_exists($token_table, $token_context_fk) ) {
$sql = "ALTER TABLE {$token_table} ADD CONSTRAINT `{$token_context_fk}`
FOREIGN KEY (`owner_context_id`, `key_id`)
REFERENCES `{$context_table}` (`context_id`, `key_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add {$token_context_fk}: ".$q->errorImplode."
\n");
}
$content_table = "{$p}lti_content";
$content_context_fk = "{$p}lti_content_ibfk_3";
if ( $PDOX->metadata($content_table) !== false && ! $constraint_exists($content_table, $content_context_fk) ) {
$sql = "ALTER TABLE {$content_table} ADD CONSTRAINT `{$content_context_fk}`
FOREIGN KEY (`context_id`, `key_id`)
REFERENCES `{$context_table}` (`context_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add {$content_context_fk}: ".$q->errorImplode."
\n");
}
$context_fk = "{$p}lti_context_ibfk_3";
if ( ! $constraint_exists($context_table, $context_fk) ) {
$sql = "ALTER TABLE {$context_table} ADD CONSTRAINT `{$context_fk}`
FOREIGN KEY (`org_id`) REFERENCES `{$org_table}` (`org_id`)
ON DELETE SET NULL ON UPDATE CASCADE";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add lti_context.org_id foreign key: ".$q->errorImplode."
\n");
}
}
$registration_table = "{$p}lti_tool_registration";
$scope_context_table = "{$p}lti_tool_deployment_context";
// ON UPDATE RESTRICT: the registration CHECK names owner_context_id, and
// MySQL error 3823 rejects any other referential action on that column.
if ( $PDOX->metadata($registration_table) !== false ) {
$owner_context_fk = "{$p}lti_tool_registration_ibfk_4";
if ( ! $constraint_exists($registration_table, $owner_context_fk) ) {
$sql = "ALTER TABLE {$registration_table} ADD CONSTRAINT `{$owner_context_fk}`
FOREIGN KEY (`owner_context_id`, `key_id`)
REFERENCES `{$context_table}` (`context_id`, `key_id`)
ON DELETE RESTRICT ON UPDATE RESTRICT";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add {$owner_context_fk}: ".$q->errorImplode."
\n");
}
}
if ( $PDOX->metadata($registration_table) !== false && $PDOX->metadata($deployment_table) !== false ) {
// Data only. An LTI 1.1 registration that has no deployment yet gets
// one, with a null external deployment_id. Credentials are not rewritten.
\Tsugi\Services\Outbound\ToolDeploymentService::ensureLti11Deployments();
}
if ( $PDOX->metadata($scope_context_table) !== false && $PDOX->metadata($deployment_table) !== false ) {
$scope_context = "{$p}lti_tool_deployment_context_ibfk_2";
if ( ! $constraint_exists($scope_context_table, $scope_context) ) {
$sql = "ALTER TABLE {$scope_context_table} ADD CONSTRAINT `{$scope_context}`
FOREIGN KEY (`context_id`, `key_id`)
REFERENCES `{$context_table}` (`context_id`, `key_id`)
ON DELETE CASCADE ON UPDATE RESTRICT";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add {$scope_context}: ".$q->errorImplode."
\n");
}
}
// lti_category is created from $DATABASE_INSTALL. Existing links gain
// a nullable category_id here, then the ON DELETE SET NULL key.
$category_table = "{$p}lti_category";
$link_table = "{$p}lti_link";
$link_category_fk = "{$p}lti_link_ibfk_2";
if ( $PDOX->metadata($category_table) !== false
&& $PDOX->columnExists('category_id', $link_table)
&& ! $constraint_exists($link_table, $link_category_fk) ) {
$sql = "ALTER TABLE {$link_table} ADD CONSTRAINT `{$link_category_fk}`
FOREIGN KEY (`category_id`)
REFERENCES `{$category_table}` (`category_id`)
ON DELETE SET NULL ON UPDATE CASCADE";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) die("Unable to add {$link_category_fk}: ".$q->errorImplode."
\n");
}
// Existing tables only. A fresh CREATE already has the expression default
// and the unique key. This adds a nullable column with neither. The unique
// key is added in the next block. It does not add the expression default,
// and it does not alter a column that is already there. Existing rows stay
// NULL until admin/lti-maint/backfill-guid.php. MySQL 8.0.12+, Aurora MySQL 8, and
// MariaDB 10.3.2+ add the column with ALGORITHM=INSTANT. MySQL 5.6/5.7
// and MySQL 8.0 before 8.0.12 use ALGORITHM=INPLACE, LOCK=NONE so the
// copy does not block reads or writes. Any other server gets a plain
// ALTER TABLE, which may lock the table while it copies.
$guid_tables = array('lti_user', 'lti_context', 'lti_key', 'lti_link');
$guid_missing = array();
foreach ( $guid_tables as $guid_table ) {
$guid_physical = "{$p}{$guid_table}";
if ( $PDOX->metadata($guid_physical) === false ) {
echo("Skipping guid column, table missing: {$guid_physical}
\n");
continue;
}
$guid_column = $PDOX->rowDie(
"SELECT COLUMN_TYPE AS column_type, IS_NULLABLE AS is_nullable
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :table_name
AND COLUMN_NAME = 'guid'",
array(':table_name' => $guid_physical));
if ( $guid_column === false ) {
$guid_missing[] = $guid_physical;
continue;
}
$guid_type = strtolower((string) $guid_column['column_type']);
$guid_nullable = strtoupper((string) $guid_column['is_nullable']);
if ( $guid_type !== 'binary(16)' || $guid_nullable !== 'YES' ) {
die("guid on {$guid_physical} is {$guid_type} nullable={$guid_nullable}; expected binary(16) YES. Not altering it.
\n");
}
}
if ( count($guid_missing) > 0 ) {
$guid_server = $PDOX->serverVersion();
foreach ( $guid_missing as $guid_physical ) {
$sql = "ALTER TABLE {$guid_physical} ADD COLUMN guid BINARY(16) NULL";
if ( $guid_server['add_column'] === 'instant' ) {
$sql .= ', ALGORITHM=INSTANT';
} else if ( $guid_server['add_column'] === 'inplace' ) {
$sql .= ', ALGORITHM=INPLACE, LOCK=NONE';
}
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success && $guid_server['add_column'] !== '' ) {
$plain = "ALTER TABLE {$guid_physical} ADD COLUMN guid BINARY(16) NULL";
$warn = "guid add with ".$guid_server['add_column']." failed: ".$q->errorImplode."; retrying: ".$plain;
echo(htmlentities($warn)."
\n");
error_log($warn);
$q->closeCursor();
$q = $PDOX->queryReturnError($plain);
}
if ( ! $q->success ) die("Unable to add guid on {$guid_physical}: ".$q->errorImplode."
\n");
}
}
// Unique key on guid. A fresh CREATE already has it. This adds it once the
// column is there. Multiple NULLs are allowed, so this can run before
// backfill. A repeated non-NULL guid stops the upgrade. The expression
// default stays on fresh CREATE only.
//
// A secondary unique index is INPLACE on MySQL 5.6+ and MariaDB 10.0+ and
// does not copy the table. LOCK=NONE lets reads and writes continue. MySQL
// 5.5 and older MariaDB get a plain ALTER TABLE, which may lock the table
// while it copies. If INPLACE is rejected, this retries that plain
// statement. A duplicate guid is not retried.
foreach ( $guid_tables as $guid_table ) {
$guid_physical = "{$p}{$guid_table}";
if ( $PDOX->metadata($guid_physical) === false ) {
continue;
}
if ( ! $PDOX->columnExists('guid', $guid_physical) ) {
continue;
}
$guid_index = "{$p}{$guid_table}_const_guid";
if ( $PDOX->indexExists($guid_index, $guid_physical) ) {
continue;
}
$plain = "ALTER TABLE {$guid_physical} ADD CONSTRAINT `{$guid_index}` UNIQUE (`guid`)";
$sql = $plain.', ALGORITHM=INPLACE, LOCK=NONE';
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$err = (string) $q->errorImplode;
$duplicate = (stripos($err, '1062') !== false) || (stripos($err, 'Duplicate entry') !== false);
if ( $duplicate ) {
die("Unable to add {$guid_index} on {$guid_physical}: duplicate guid values. ".$err."
\n");
}
$warn = "guid unique index with INPLACE failed: ".$err."; retrying: ".$plain;
echo(htmlentities($warn)."
\n");
error_log($warn);
$q->closeCursor();
$q = $PDOX->queryReturnError($plain);
}
if ( ! $q->success ) {
$err = (string) $q->errorImplode;
$duplicate = (stripos($err, '1062') !== false) || (stripos($err, 'Duplicate entry') !== false);
if ( $duplicate ) {
die("Unable to add {$guid_index} on {$guid_physical}: duplicate guid values. ".$err."
\n");
}
die("Unable to add {$guid_index} on {$guid_physical}: ".$err."
\n");
}
}
// email is TEXT. A 255-char prefix covers an address and lets
// unsubscribe opt-out match email = :E instead of scanning LOWER(email).
$email_index = "{$CFG->dbprefix}lti_user_indx_email";
if ( ! $PDOX->indexExists($email_index, "{$CFG->dbprefix}lti_user") ) {
$sql = "CREATE INDEX `{$email_index}` ON {$CFG->dbprefix}lti_user (email(255))";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating index: ".$q->errorImplode;
error_log($message);
echo($message."
\n");
}
}
// Admin profile list counts lti_user rows per profile. profile_id has no key,
// so each count scanned lti_user.
$profile_index = "{$CFG->dbprefix}lti_user_indx_profile";
if ( ! $PDOX->indexExists($profile_index, "{$CFG->dbprefix}lti_user") ) {
$sql = "CREATE INDEX `{$profile_index}` ON {$CFG->dbprefix}lti_user (profile_id)";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating index: ".$q->errorImplode;
error_log($message);
echo($message."
\n");
}
}
// Google login: WHERE key_id AND email ORDER BY updated_at DESC LIMIT 1.
// UNIQUE(key_id, user_sha256) finds the key but then walks every user on it.
$key_email_index = "{$CFG->dbprefix}lti_user_indx_key_email";
if ( ! $PDOX->indexExists($key_email_index, "{$CFG->dbprefix}lti_user") ) {
$sql = "CREATE INDEX `{$key_email_index}` ON {$CFG->dbprefix}lti_user (key_id, email(255), updated_at)";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal error creating index: ".$q->errorImplode;
error_log($message);
echo($message."
\n");
}
}
// 2026-11-20 Drop the unused outbound analytics queue.
$legacy_names = array();
foreach ( array('cal_event', 'cal_key', 'cal_context') as $legacy_table ) {
$legacy_names[$legacy_table] = "{$CFG->dbprefix}{$legacy_table}";
}
$legacy_present = array();
$legacy_rows = $PDOX->allRows(
"SELECT TABLE_NAME AS table_name
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME IN (:a, :b, :c)",
array(
':a' => $legacy_names['cal_event'],
':b' => $legacy_names['cal_key'],
':c' => $legacy_names['cal_context'],
),
false
);
if ( is_array($legacy_rows) ) {
foreach ( $legacy_rows as $legacy_row ) {
$legacy_present[\Tsugi\Util\U::get($legacy_row, 'table_name')] = true;
}
}
foreach ( $legacy_names as $legacy_table => $physical ) {
if ( empty($legacy_present[$physical]) ) continue;
$sql = "DROP TABLE {$physical}";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal drop {$legacy_table}: ".$q->errorImplode;
error_log($message);
echo($message."
\n");
}
}
$key_table = "{$CFG->dbprefix}lti_key";
foreach ( array('caliper_url', 'caliper_key', 'xapi_url', 'xapi_user', 'xapi_password') as $legacy_column ) {
if ( ! $PDOX->columnExists($legacy_column, $key_table) ) continue;
$sql = "ALTER TABLE {$key_table} DROP COLUMN {$legacy_column}";
echo("Upgrading: ".$sql."
\n");
error_log("Upgrading: ".$sql);
$q = $PDOX->queryReturnError($sql);
if ( ! $q->success ) {
$message = "Non-Fatal drop {$legacy_column}: ".$q->errorImplode;
error_log($message);
echo($message."
\n");
}
}
// Notice only. A failed count query must not stop the upgrade.
try {
// Notice only. These rows share an issuer, client id, and deployment id.
foreach ( \Tsugi\Services\Admin\AdminService::issuerClientDuplicateRows() as $identity_row ) {
$stored_deploy = \Tsugi\Util\U::get($identity_row, 'deploy_key');
$deploy_label = (is_string($stored_deploy) && trim($stored_deploy) !== '') ? trim($stored_deploy) : '(none)';
$message = 'Duplicate (client id, issuer, deployment id): client_id='.\Tsugi\Util\U::get($identity_row, 'lms_client')
.' issuer='.\Tsugi\Util\U::get($identity_row, 'lms_issuer')
.' deployment_id='.$deploy_label
.' key_id='.\Tsugi\Util\U::get($identity_row, 'key_id');
error_log($message);
echo(htmlentities($message)."
\n");
}
// Notice only. These rows share an issuer and client id but disagree on
// configuration URLs that would collapse onto one client row.
foreach ( \Tsugi\Services\Admin\AdminService::clientConfigConflictGroups() as $group ) {
$client_id = \Tsugi\Util\U::get($group, 'lms_client');
$issuer = \Tsugi\Util\U::get($group, 'lms_issuer');
$fields = \Tsugi\Util\U::get($group, 'fields', array());
if ( ! is_array($fields) ) $fields = array();
$keys = \Tsugi\Util\U::get($group, 'keys', array());
if ( ! is_array($keys) ) continue;
foreach ( $keys as $keyrow ) {
$parts = array();
foreach ( $fields as $column => $label ) {
$value = \Tsugi\Util\U::get($keyrow, $column);
$shown = (is_string($value) && trim($value) !== '') ? trim($value) : '(blank)';
$parts[] = $label.'='.$shown;
}
$message = 'Conflicting configuration URLs: client_id='.$client_id
.' issuer='.$issuer
.' key_id='.\Tsugi\Util\U::get($keyrow, 'key_id')
.' '.implode(' ', $parts);
error_log($message);
echo(htmlentities($message)."
\n");
}
}
// Notice only. A key with more than one deployment id cannot drop the
// copies on context and read the key.
foreach ( \Tsugi\Services\Admin\AdminService::keyDeploymentConflictGroups() as $deploy_group ) {
$deploy_values = \Tsugi\Util\U::get($deploy_group, 'values', array());
if ( ! is_array($deploy_values) ) continue;
$deploy_parts = array();
foreach ( $deploy_values as $deploy_value ) {
$deploy_places = \Tsugi\Util\U::get($deploy_value, 'places', array());
if ( ! is_array($deploy_places) ) $deploy_places = array();
$place_bits = array();
foreach ( $deploy_places as $deploy_place ) {
$place_label = (string) \Tsugi\Util\U::get($deploy_place, 'label', '');
$place_count = (int) \Tsugi\Util\U::get($deploy_place, 'count', 0);
$place_example = (int) \Tsugi\Util\U::get($deploy_place, 'example_id', 0);
if ( $place_label === 'Key' ) {
$place_bits[] = 'Key';
} else if ( $place_count <= 1 ) {
$place_bits[] = $place_label.' '.$place_example;
} else {
$place_bits[] = $place_label.' x'.$place_count.' example '.$place_example;
}
}
$deploy_parts[] = 'deployment_id='.\Tsugi\Util\U::get($deploy_value, 'deployment_id')
.' ('.implode(', ', $place_bits).')';
}
$message = 'Non-unique (key id, deployment id): key_id='.\Tsugi\Util\U::get($deploy_group, 'key_id')
.' '.implode(' ', $deploy_parts);
error_log($message);
echo(htmlentities($message)."
\n");
}
$long_rows = \Tsugi\Services\Admin\AdminService::valuesLongerThan255();
foreach ( $long_rows as $long_row ) {
$message = 'Value longer than 255: field='.\Tsugi\Util\U::get($long_row, 'label')
.' table='.\Tsugi\Util\U::get($long_row, 'table')
.' column='.\Tsugi\Util\U::get($long_row, 'column')
.' key_id='.\Tsugi\Util\U::get($long_row, 'key_id')
.' row_id='.\Tsugi\Util\U::get($long_row, 'row_id')
.' length='.\Tsugi\Util\U::get($long_row, 'length');
error_log($message);
echo(htmlentities($message)."
\n");
}
$non_ascii_rows = \Tsugi\Services\Admin\AdminService::nonAsciiValues();
foreach ( $non_ascii_rows as $non_ascii_row ) {
$message = 'Value outside ASCII: field='.\Tsugi\Util\U::get($non_ascii_row, 'label')
.' table='.\Tsugi\Util\U::get($non_ascii_row, 'table')
.' column='.\Tsugi\Util\U::get($non_ascii_row, 'column')
.' key_id='.\Tsugi\Util\U::get($non_ascii_row, 'key_id')
.' row_id='.\Tsugi\Util\U::get($non_ascii_row, 'row_id')
.' length='.\Tsugi\Util\U::get($non_ascii_row, 'length')
.' bytes='.\Tsugi\Util\U::get($non_ascii_row, 'bytes');
error_log($message);
echo(htmlentities($message)."
\n");
}
} catch (\Throwable $e) {
$message = 'Client id check failed: '.$e->getMessage();
error_log($message);
echo(htmlentities($message)."
\n");
}
// One column at a time. Count values longer than 255 characters and values
// with a character outside ASCII. Alter only when both counts are zero and
// the column is not already varchar(255) ascii_bin. A column already in
// that form is reported and left alone. A dirty column is reported and
// left alone so a later upgrade can alter it after the data is cleaned.
$identity_note = function($message) {
error_log($message);
echo(htmlentities($message)."
\n");
};
$identity_ascii_columns = \Tsugi\Services\Admin\AdminService::identityAsciiColumns();
$identity_note('Checking identity columns for varchar(255) character set ascii collation ascii_bin.');
$identity_described = array();
foreach ( $identity_ascii_columns as $identity_column ) {
$identity_table = $identity_column[0];
$identity_field = $identity_column[1];
$identity_id = $identity_column[2];
$identity_label = 'Identity column '.$identity_table.'.'.$identity_field;
$identity_physical = $CFG->dbprefix.$identity_table;
if ( ! array_key_exists($identity_physical, $identity_described) ) {
$identity_meta = $PDOX->describe($identity_physical);
$identity_described[$identity_physical] = is_array($identity_meta) ? $identity_meta : false;
}
if ( $identity_described[$identity_physical] === false ) {
$identity_note($identity_label.': table '.$identity_table.' is absent. Left unchanged.');
continue;
}
$identity_field_meta = null;
foreach ( $identity_described[$identity_physical] as $identity_field_row ) {
if ( \Tsugi\Util\U::getIgnoreCase($identity_field_row, 'Field') === $identity_field ) {
$identity_field_meta = $identity_field_row;
break;
}
}
if ( ! is_array($identity_field_meta) ) {
$identity_note($identity_label.': column is absent. Left unchanged.');
continue;
}
$identity_count_sql = "SELECT COALESCE(SUM(CASE WHEN CHAR_LENGTH({$identity_field}) > 255 THEN 1 ELSE 0 END), 0) AS too_long,
COALESCE(SUM(CASE WHEN {$identity_field} IS NOT NULL AND CHAR_LENGTH({$identity_field}) <> LENGTH({$identity_field}) THEN 1 ELSE 0 END), 0) AS non_ascii
FROM {$identity_physical}";
$identity_counts = $PDOX->allRows($identity_count_sql, false, false);
if ( ! is_array($identity_counts) || ! isset($identity_counts[0]) ) {
$identity_note($identity_label.': could not count values. Left unchanged.');
continue;
}
$identity_too_long = (int) \Tsugi\Util\U::get($identity_counts[0], 'too_long', 0);
$identity_non_ascii = (int) \Tsugi\Util\U::get($identity_counts[0], 'non_ascii', 0);
$identity_long_word = $identity_too_long === 1 ? 'value' : 'values';
$identity_ascii_word = $identity_non_ascii === 1 ? 'value' : 'values';
$identity_summary = $identity_label.': '.$identity_too_long.' '.$identity_long_word.' longer than 255 characters, '.$identity_non_ascii.' '.$identity_ascii_word.' outside ASCII.';
// SHOW COLUMNS on this server does not return the collation.
$identity_schema_sql = "SELECT DATA_TYPE AS data_type,
CHARACTER_MAXIMUM_LENGTH AS char_length,
CHARACTER_SET_NAME AS charset_name,
COLLATION_NAME AS collation_name
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :table_name
AND COLUMN_NAME = :column_name";
$identity_schema_rows = $PDOX->allRows($identity_schema_sql, array(
':table_name' => $identity_physical,
':column_name' => $identity_field,
), false);
if ( ! is_array($identity_schema_rows) || ! isset($identity_schema_rows[0]) ) {
$identity_note($identity_label.': could not read the column type. Left unchanged.');
continue;
}
$identity_schema = $identity_schema_rows[0];
$identity_already = strtolower((string) \Tsugi\Util\U::getIgnoreCase($identity_schema, 'data_type')) === 'varchar'
&& (int) \Tsugi\Util\U::getIgnoreCase($identity_schema, 'char_length') === 255
&& strtolower((string) \Tsugi\Util\U::getIgnoreCase($identity_schema, 'charset_name')) === 'ascii'
&& strtolower((string) \Tsugi\Util\U::getIgnoreCase($identity_schema, 'collation_name')) === 'ascii_bin';
if ( $identity_too_long > 0 || $identity_non_ascii > 0 ) {
$identity_example_sql = "SELECT {$identity_id} AS row_id,
CHAR_LENGTH({$identity_field}) AS value_length,
LENGTH({$identity_field}) AS value_bytes
FROM {$identity_physical}
WHERE CHAR_LENGTH({$identity_field}) > 255
OR ({$identity_field} IS NOT NULL AND CHAR_LENGTH({$identity_field}) <> LENGTH({$identity_field}))
ORDER BY CHAR_LENGTH({$identity_field}) DESC, {$identity_id}
LIMIT 5";
$identity_examples = $PDOX->allRows($identity_example_sql, false, false);
$identity_example_bits = array();
if ( is_array($identity_examples) ) {
foreach ( $identity_examples as $identity_example ) {
$identity_example_bits[] = $identity_id.'='.\Tsugi\Util\U::get($identity_example, 'row_id')
.' length='.\Tsugi\Util\U::get($identity_example, 'value_length')
.' bytes='.\Tsugi\Util\U::get($identity_example, 'value_bytes');
}
}
$identity_example_text = count($identity_example_bits) > 0 ? ' Examples: '.implode('; ', $identity_example_bits).'.' : '';
$identity_note($identity_summary.$identity_example_text.' Left unchanged.');
continue;
}
if ( $identity_already ) {
$identity_note($identity_summary.' Already varchar(255) character set ascii collation ascii_bin.');
continue;
}
$identity_nullable = strtoupper((string) \Tsugi\Util\U::getIgnoreCase($identity_field_meta, 'Null')) === 'YES';
$identity_null_sql = $identity_nullable ? 'NULL' : 'NOT NULL';
$identity_alter_sql = "ALTER TABLE {$identity_physical} MODIFY {$identity_field} VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin {$identity_null_sql}";
$identity_note($identity_summary.' Altering to varchar(255) character set ascii collation ascii_bin.');
$identity_note('Upgrading: '.$identity_alter_sql);
$identity_alter = $PDOX->queryReturnError($identity_alter_sql, false, false);
if ( ! $identity_alter->success ) {
$identity_note($identity_label.': alter failed: '.$identity_alter->errorImplode.'. Left unchanged.');
continue;
}
$identity_note($identity_label.': altered to varchar(255) character set ascii collation ascii_bin.');
}
// When you increase this number in any database.php file,
// make sure to update the global value in setup.php
return 202611200002;
}; // Don't forget the semicolon on anonymous functions :)
// Do the actual migration if we are not in admin/upgrade.php
if ( isset($CURRENT_FILE) ) {
include $CFG->dirroot."/admin/migrate-run.php";
}