>|null */
private static $issuerClientDuplicateRows = null;
// admin/admin_util.php
// TODO: deal with headers sent...
public static function requireLogin() {
global $CFG, $OUTPUT;
if ( $CFG->google_glient_id && ! isset($_SESSION['user_id']) ) {
U::flashError('Login required');
$OUTPUT->doRedirect(\Tsugi\Controllers\Login::loginUrl()) ;
exit();
}
}
public static function isAdmin() {
return isset( $_SESSION['admin']) && $_SESSION['admin'] == 'yes';
}
/**
* Whether the current session email may attempt admin unlock.
* Unset / empty $CFG->adminemails keeps legacy "any email" behavior.
*/
public static function adminEmailAllowed() {
global $CFG;
$allowed = $CFG->adminemails ?? false;
if ( is_string($allowed) && U::strlen(trim($allowed)) > 0 ) {
$allowed = array($allowed);
}
if ( ! is_array($allowed) || count($allowed) < 1 ) return true;
$email = strtolower(trim((string) U::get($_SESSION, 'email', '')));
if ( $email === '' ) return false;
foreach ( $allowed as $one ) {
if ( strtolower(trim((string) $one)) === $email ) return true;
}
return false;
}
// One small APCu int per wwwroot (any IP). Session is only used if APCu is off.
public static function adminUnlockCacheKey() {
global $CFG;
return 'admin_unlock_'.md5((string) $CFG->wwwroot);
}
public static function adminUnlockCount() {
if ( U::apcuAvailable() ) {
return (int) U::appCacheGet(self::adminUnlockCacheKey(), 0);
}
$until = $_SESSION['_admin_unlock_exp'] ?? 0;
if ( ! is_int($until) || $until < time() ) {
unset($_SESSION['_admin_unlock'], $_SESSION['_admin_unlock_exp']);
return 0;
}
return (int) ($_SESSION['_admin_unlock'] ?? 0);
}
public static function adminUnlockBanned() {
return self::adminUnlockCount() >= 2;
}
public static function adminUnlockRecordFail() {
$n = self::adminUnlockCount() + 1;
$ttl = ($n >= 2) ? 300 : 600;
if ( U::apcuAvailable() ) {
U::appCacheSet(self::adminUnlockCacheKey(), $n, $ttl);
} else {
$_SESSION['_admin_unlock'] = $n;
$_SESSION['_admin_unlock_exp'] = time() + $ttl;
}
return $n >= 2;
}
public static function adminUnlockClearFails() {
if ( U::apcuAvailable() ) {
U::appCacheDelete(self::adminUnlockCacheKey());
}
unset($_SESSION['_admin_unlock'], $_SESSION['_admin_unlock_exp']);
}
public static function requireAdmin() {
global $CFG, $OUTPUT;
if ( $CFG->google_glient_id && $_SESSION['admin'] != 'yes' ) {
U::flashError('Login required');
$OUTPUT->doRedirect(\Tsugi\Controllers\Login::loginUrl()) ;
exit();
}
}
public static function findTools($dir, &$retval, $filenames=array("index.php", "tsugi.php")) {
if ( ! is_array($filenames) ) $filenames = array($filenames);
if ( is_dir($dir) ) {
if ($dh = opendir($dir)) {
while (($sub = readdir($dh)) !== false) {
if ( strpos($sub, ".") === 0 ) continue;
if ( in_array($sub, $filenames) ) {
$retval[] = $dir ."/";
}
$path = $dir . '/' . $sub;
if ( ! is_dir($path) ) continue;
if ( $sh = opendir($path)) {
while (($file = readdir($sh)) !== false) {
if ( in_array($file, $filenames) ) {
$retval[] = $path ."/" ;
break;
}
}
closedir($sh);
}
}
closedir($dh);
}
}
}
public static function findAllFolders($paths)
{
$folders = array();
if ( is_string($paths) ) $paths = array($paths);
foreach( $paths as $path) {
if ( ! is_dir($path) ) continue;
$files = scandir($path);
foreach($files as $file) {
if ( strpos($file,'.') === 0 ) continue;
if ( strpos($file,'_') === 0 ) continue;
$abs = self::addSlash($path).$file;
if ( ! is_dir($abs) ) continue;
$folders[] = $abs;
}
}
return $folders;
}
public static function addSlash($path)
{
if ( U::strlen($path) < 1 ) return $path;
if ( substr($path,strlen($path)-1) == DIRECTORY_SEPARATOR ) return $path;
return $path . DIRECTORY_SEPARATOR;
}
public static function findAllTools()
{
global $CFG;
// Load tools from various folders
$tools = array();
foreach( $CFG->tool_folders AS $tool_folder) {
if ( $tool_folder == 'core' ) continue;
if ( $tool_folder == 'admin' ) continue;
self::findTools($CFG->dirroot.'/'.$tool_folder,$tools);
}
return $tools;
}
public static function findAllRegistrations($folders=false, $appStore=false)
{
global $CFG, $PDOX;
$regCode = $CFG->dirroot . '/../load_registrations.php';
if ( file_exists($regCode) ) {
require_once($regCode);
return loadRegistrations();
}
return self::findAllRegistrationsInternal($folders, $appStore);
}
public static function findAllRegistrationsInternal($folders=false, $appStore=false)
{
global $CFG, $PDOX;
// Scan the tools folders for registration settings
if ( $folders == false ) $folders = $CFG->tool_folders;
if ( is_string($folders) ) $folders = array($folders);
$tools = array();
foreach( $folders AS $tool_folder) {
if ( $tool_folder == 'core' ) continue;
if ( $tool_folder == 'admin' ) continue;
$some = self::findFiles('register.php', $CFG->dirroot . '/');
foreach($some as $reg_file) {
// Take off the $CFG->dirroot
$relative = substr($reg_file,strlen($CFG->dirroot)+1);
$url = $CFG->wwwroot . '/' . $relative;
$url = U::remove_relative_path($url);
$pieces = explode('/', $url);
if ( count($pieces) < 2 || $pieces[count($pieces)-1] != 'register.php') {
error_log('Unable to load tool registration from '.$tool_folder);
continue;
}
$key = $pieces[count($pieces)-2];
unset($REGISTER_LTI);
unset($REGISTER_LTI2);
require($reg_file);
if ( ! isset($REGISTER_LTI) && isset($REGISTER_LTI2) ) $REGISTER_LTI = $REGISTER_LTI2;
if ( ! isset($REGISTER_LTI) ) continue;
if ( ! is_array($REGISTER_LTI) ) continue;
if ( isset($REGISTER_LTI['name']) && isset($REGISTER_LTI['short_name']) &&
isset($REGISTER_LTI['description']) ) {
// Valid LTI Registration
// If Appstore - Check if the registration is marked as hidden
if ($appStore && isset($REGISTER_LTI['hide_from_store']) && $REGISTER_LTI['hide_from_store']) {
// Skip hidden app
continue;
}
} else {
error_log("Missing required name, short_name, and description in ".$tool_folder);
}
// Make an icon URL
$fa_icon = isset($REGISTER_LTI['FontAwesome']) ? $REGISTER_LTI['FontAwesome'] : false;
if ( $fa_icon !== false ) {
$REGISTER_LTI['icon'] = $CFG->fontawesome.'/png/'.str_replace('fa-','',$fa_icon).'.png';
}
$launch_url = str_replace('/register.php','/',$url);
$REGISTER_LTI['url'] = $launch_url;
$screen_shots = U::get($REGISTER_LTI, 'screen_shots');
if ( is_array($screen_shots) && count($screen_shots) > 0 ) {
$new = array();
foreach($screen_shots as $screen_shot ) {
$new[] = str_replace('/register.php','/'.$screen_shot, $url);
}
$REGISTER_LTI['screen_shots'] = $new;
}
$submissionReview = U::get($REGISTER_LTI, 'submissionReview');
if ( is_array($submissionReview) && U::get($submissionReview, 'url')) {
// Make the URL absolute
$submissionUrl = U::get($submissionReview, 'url');
$submissionReview['url'] = str_replace('/register.php','/'.$submissionUrl, $url);
$REGISTER_LTI['submissionReview'] = $submissionReview;
}
$tools[$key] = $REGISTER_LTI;
}
}
// Find external applications
$stmt = $PDOX->queryReturnError("SELECT * FROM {$CFG->dbprefix}lti_external");
$rows = array();
if ( $stmt->success ) while ( $row = $stmt->fetch(\PDO::FETCH_ASSOC) ) {
array_push($rows, $row);
}
foreach($rows as $row) {
// echo("
\n");var_dump($row['json']);echo("
\n");
$REGISTER_LTI = json_decode($row['json'], true);
if ( ! is_array($REGISTER_LTI) ) $REGISTER_LTI = array();
$REGISTER_LTI['url'] = $CFG->wwwroot . '/ext/' . $row['endpoint'];
// Make an icon URL
$fa_icon = isset($row['fa_icon']) ? $row['fa_icon'] : false;
if ( $fa_icon !== false ) {
$REGISTER_LTI['FontAwesome'] = $fa_icon;
$REGISTER_LTI['icon'] = $CFG->fontawesome.'/png/'.str_replace('fa-','',$fa_icon).'.png';
}
$REGISTER_LTI['name'] = $row['name'];
$REGISTER_LTI['short_name'] = $row['name'];
$REGISTER_LTI['description'] = $row['description'];
$key = 'ext-' . $row['endpoint'];
$tools[$key] = $REGISTER_LTI;
}
return $tools;
}
public static function findFiles($filename="index.php", $reldir=false) {
global $CFG;
$files = array();
foreach ( $CFG->tool_folders as $dir ) {
if ( $reldir !== false ) $dir = $reldir . $dir;
if ( is_dir($dir) ) {
if ($dh = opendir($dir)) {
while (($sub = readdir($dh)) !== false) {
if ( strpos($sub, ".") === 0 ) continue;
if ( $sub == $filename ) {
$files[] = $dir . '/' . $sub;
continue;
}
$path = $dir . '/' . $sub;
if ( ! is_dir($path) ) continue;
if ( $sh = opendir($path)) {
while (($file = readdir($sh)) !== false) {
if ( $file == $filename ) {
$files[] = $path ."/" . $file;
break;
}
}
closedir($sh);
}
}
closedir($dh);
}
}
}
return $files;
}
public static function findToolFiles($filename="index.php", $reldir=false) {
global $CFG;
$retval = array();
foreach ( $CFG->tool_folders as $dir ) {
if ( $reldir !== false ) $dir = $reldir . '/' . $dir;
$files = self::searchTwoLevels($filename, $dir);
$retval = array_merge($retval, $files);
}
return $retval;
}
public static function searchTwoLevels($filename, $dir) {
$files = array();
if ( is_dir($dir) ) {
if ($dh = opendir($dir)) {
while (($sub = readdir($dh)) !== false) {
if ( strpos($sub, ".") === 0 ) continue;
if ( $sub == $filename ) {
$files[] = $dir . '/' . $sub;
continue;
}
$path = $dir . '/' . $sub;
if ( ! is_dir($path) ) continue;
if ( $sh = opendir($path)) {
while (($file = readdir($sh)) !== false) {
if ( $file == $filename ) {
$files[] = $path ."/" . $file;
break;
}
}
closedir($sh);
}
}
closedir($dh);
}
}
return $files;
}
// path = /x/y/z
// root = /x/y
// retval = z
public static function trimAsMuchAsYouCan($path, $root) {
$path_pieces = explode('/', $path);
$root_pieces = explode('/', $root);
for($i=0; $i < count($path_pieces) && $i < count($root_pieces) ; $i++) {
if ( $path_pieces[$i] != $root_pieces[$i] ) break;
}
$pieces = array();
for(;$i < count($path_pieces); $i++) {
if ( U::strlen($path_pieces[$i] ) < 1 ) continue;
$pieces[] = $path_pieces[$i];
}
$remainder = implode('/', $pieces);
return $remainder;
}
// admin/key/key-util.php
/**
* Normalize LTI 1.3 deployment id from a form field for database storage.
*
* Empty string, whitespace only, or the literal "null" are stored as NULL.
* Leaving the field blank means the key accepts any deployment id sent by the LMS;
* Tsugi still uses the deployment id from the launch JWT for LTI 1.3 services (for example grading).
* Any other non-empty string is trimmed and stored as the specific deployment id.
*
* @param mixed $v Raw POST value
* @return string|null
*/
public static function normalize_deploy_key_input($v) {
if ( $v === null ) {
return null;
}
if ( ! is_string($v) ) {
return null;
}
$t = trim($v);
if ( $t === '' || strcasecmp($t, 'null') === 0 ) {
return null;
}
return $t;
}
/**
* Resolve the LTI 1.3 (issuer URL, client id) pair for a tenant key.
*
* @return array{issuer_sha256:string,issuer_client:string}|null
*/
public static function resolve_lti13_issuer_client($lms_issuer, $lms_client) {
if ( U::isNotEmpty($lms_issuer) && U::isNotEmpty($lms_client) ) {
$issuer_sha256 = U::lti_sha256($lms_issuer);
if ( ! $issuer_sha256 ) {
return null;
}
return array(
'issuer_sha256' => $issuer_sha256,
'issuer_client' => $lms_client,
);
}
return null;
}
/**
* Rows for a client id check. A failed query throws so the caller can
* keep going. allRowsDie() would end the upgrade.
*
* @return array>
*/
private static function diagnosticRows($sql) {
global $PDOX;
$rows = $PDOX->allRows($sql);
if ( ! is_array($rows) ) {
throw new \RuntimeException('client id check query failed');
}
return $rows;
}
/**
* Column names for lti_key. A failed describe throws so an unread table
* is not reported as an empty result.
*
* @return array
*/
private static function ltiKeyColumnNames($table) {
global $PDOX;
$columns = $PDOX->describe($table);
if ( ! is_array($columns) ) {
throw new \RuntimeException('client id check query failed');
}
$names = array();
foreach ( $columns as $column ) {
if ( is_array($column) && isset($column['Field']) ) $names[] = $column['Field'];
}
return $names;
}
/**
* Tenant keys that share an issuer, client id, and deployment id.
* A blank deployment id is its own value in that tuple. This does not change any unique key.
*
* The cache is set only after the query returns. A throw leaves it unset
* so a later call retries instead of reporting zero duplicates.
*
* @return array>
*/
public static function issuerClientDuplicateRows() {
global $PDOX, $CFG;
if ( is_array(self::$issuerClientDuplicateRows) ) {
return self::$issuerClientDuplicateRows;
}
$table = "{$CFG->dbprefix}lti_key";
if ( ! is_object($PDOX) ) {
return array();
}
$names = self::ltiKeyColumnNames($table);
if ( ! in_array('lms_issuer', $names, true) || ! in_array('lms_client', $names, true) ) {
return array();
}
if ( in_array('deploy_key', $names, true) ) {
$deploy_sql = 'k.deploy_key';
$deploy_group = "CASE WHEN deploy_key IS NULL OR TRIM(deploy_key) = '' OR LOWER(TRIM(deploy_key)) = 'null' THEN '' ELSE TRIM(deploy_key) END";
$deploy_group_k = "CASE WHEN k.deploy_key IS NULL OR TRIM(k.deploy_key) = '' OR LOWER(TRIM(k.deploy_key)) = 'null' THEN '' ELSE TRIM(k.deploy_key) END";
} else {
$deploy_sql = 'NULL';
$deploy_group = "''";
$deploy_group_k = "''";
}
$deleted_sql = in_array('deleted', $names, true) ? 'k.deleted' : '0';
$rows = self::diagnosticRows(
"SELECT k.key_id, k.key_title, TRIM(k.lms_issuer) AS lms_issuer,
TRIM(k.lms_client) AS lms_client, {$deploy_sql} AS deploy_key, {$deleted_sql} AS deleted
FROM {$table} AS k
INNER JOIN (
SELECT TRIM(lms_issuer) AS lms_issuer, TRIM(lms_client) AS lms_client,
{$deploy_group} AS deploy_group
FROM {$table}
WHERE lms_issuer IS NOT NULL AND TRIM(lms_issuer) <> ''
AND lms_client IS NOT NULL AND TRIM(lms_client) <> ''
GROUP BY TRIM(lms_issuer), TRIM(lms_client), {$deploy_group}
HAVING COUNT(*) > 1
) AS d
ON TRIM(k.lms_issuer) = d.lms_issuer
AND TRIM(k.lms_client) = d.lms_client
AND {$deploy_group_k} = d.deploy_group
ORDER BY k.lms_issuer, k.lms_client, {$deploy_group_k}, k.key_id"
);
self::$issuerClientDuplicateRows = $rows;
return self::$issuerClientDuplicateRows;
}
/**
* How many (client id, issuer, deployment id) tuples are used by more than one key.
*/
public static function issuerClientDuplicateCount() {
$groups = array();
foreach ( self::issuerClientDuplicateRows() as $row ) {
$issuer = trim((string) U::get($row, 'lms_issuer', ''));
$client = trim((string) U::get($row, 'lms_client', ''));
if ( $issuer === '' || $client === '' ) continue;
$deploy = U::get($row, 'deploy_key');
$deploy = is_string($deploy) ? trim($deploy) : '';
if ( strcasecmp($deploy, 'null') === 0 ) $deploy = '';
$groups[$issuer."\n".$client."\n".$deploy] = true;
}
return count($groups);
}
/**
* Red warning for the admin console and the key list. Empty when there are no duplicates.
*/
public static function issuerClientDuplicateNotice() {
$count = self::issuerClientDuplicateCount();
if ( $count < 1 ) {
return '';
}
$tuples = $count === 1 ? 'tuple' : 'tuples';
$verb = $count === 1 ? 'is' : 'are';
return '
'."\n"
.'
There '.$verb.' '.$count.' duplicate (client id, issuer, deployment id) '.$tuples.".
\n"
."
\n";
}
/**
* Red warning for the admin console and the key list. Empty when URLs agree.
*
* Same lti_key scan shape as the duplicate notice. Not a per-launch query.
*/
public static function clientConfigConflictNotice() {
$count = count(self::clientConfigConflictGroups());
if ( $count < 1 ) {
return '';
}
$pairs = $count === 1 ? 'pair' : 'pairs';
return '
'."\n"
.'
'.$count.' issuer and client id '.$pairs.' will collide when collapsed.
'."\n"
."
\n";
}
/**
* Red warning for the admin console and the key list. Empty when each key
* has a single deployment id.
*
* Reads lti_key and the contexts that stored a deployment id. Admin only.
*/
public static function keyDeploymentConflictNotice() {
$count = count(self::keyDeploymentConflictGroups());
if ( $count < 1 ) {
return '';
}
$verb = $count === 1 ? 'key has' : 'keys have';
return '
'."\n"
.'
'.$count.' '.$verb.' more than one deployment id.
'."\n"
."
\n";
}
/**
* Red warning for the admin console and the key list. Empty when every
* issuer, client id, deployment id, context id, resource link id,
* consumer key, and secret fits in varchar(255).
*
* Same admin-only scan as the other Client ID Check notices.
*/
public static function valuesLongerThan255Notice() {
$count = count(self::valuesLongerThan255());
if ( $count < 1 ) {
return '';
}
$verb = $count === 1 ? 'value is' : 'values are';
return '
'."\n"
.'
'.$count.' '.$verb.' longer than 255 characters.
'."\n"
."
\n";
}
/**
* Red warning for the admin console and the key list. Empty when every
* checked identifier is ASCII.
*
* Same columns and same admin-only scan as the varchar(255) length notice.
*/
public static function nonAsciiValuesNotice() {
$count = count(self::nonAsciiValues());
if ( $count < 1 ) {
return '';
}
$verb = $count === 1 ? 'value contains' : 'values contain';
return '
'."\n"
.'
'.$count.' '.$verb.' a character outside ASCII.
'."\n"
."
\n";
}
/**
* The five client id warnings, or one warning when a check cannot run.
*/
public static function clientIdCheckNotices() {
try {
return self::issuerClientDuplicateNotice()
.self::clientConfigConflictNotice()
.self::keyDeploymentConflictNotice()
.self::valuesLongerThan255Notice()
.self::nonAsciiValuesNotice();
} catch (\Throwable $e) {
error_log('Client id check failed: '.$e->getMessage());
return '
'."\n"
.'
Client id check failed.
'."\n"
."
\n";
}
}
/**
* URL columns that would move onto one client row for an issuer and client id.
*
* @return array column => label
*/
public static function clientConfigColumns() {
return array(
'lms_oidc_auth' => 'OIDC auth URL',
'lms_keyset_url' => 'Keyset URL',
'lms_token_url' => 'Token URL',
'lms_token_audience' => 'Token audience',
);
}
/**
* Value used to decide whether two configuration URLs are the same.
*
* Scheme and host are case-insensitive. The path, query, and fragment are
* compared as stored, so a path that differs only by case still conflicts.
*/
private static function clientConfigCompareValue($value) {
$value = trim((string) $value);
if ( ! preg_match('#^([a-z][a-z0-9+.-]*:)(//[^/?\#]*)#i', $value, $match) ) {
return $value;
}
$scheme = strtolower($match[1]);
$authority = $match[2];
$rest = substr($value, strlen($match[0]));
if ( preg_match('#^(//(?:[^@/]*@)?)(\[[^\]]+\]|[^:/]*)(:[0-9]+)?$#', $authority, $parts) ) {
$authority = $parts[1].strtolower($parts[2]).(isset($parts[3]) ? $parts[3] : '');
}
return $scheme.$authority.$rest;
}
/**
* Keys that share an issuer and client id but disagree on URL configuration.
*
* A blank value is ignored. Two different non-blank values for one column
* collide when those keys collapse onto one client row. Scheme and host
* case does not. Path, query, and fragment case does.
*
* @return array, keys:array>}>
*/
public static function clientConfigConflictGroups() {
global $PDOX, $CFG;
$empty = array();
$table = "{$CFG->dbprefix}lti_key";
if ( ! is_object($PDOX) ) {
return $empty;
}
$names = self::ltiKeyColumnNames($table);
if ( ! in_array('lms_issuer', $names, true) || ! in_array('lms_client', $names, true) ) {
return $empty;
}
$present = array();
foreach ( self::clientConfigColumns() as $column => $label ) {
if ( in_array($column, $names, true) ) $present[$column] = $label;
}
if ( count($present) < 1 ) {
return $empty;
}
$having = array();
$select = array();
foreach ( $present as $column => $label ) {
// The column collation folds case, including the path. Compare the
// bytes here so a path that differs only by case still reaches PHP.
$having[] = "COUNT(DISTINCT CAST(NULLIF(TRIM({$column}), '') AS BINARY)) > 1";
$select[] = "NULLIF(TRIM(k.{$column}), '') AS {$column}";
}
$deleted_sql = in_array('deleted', $names, true) ? 'k.deleted' : '0';
$rows = self::diagnosticRows(
"SELECT k.key_id, k.key_title, {$deleted_sql} AS deleted,
TRIM(k.lms_issuer) AS lms_issuer, TRIM(k.lms_client) AS lms_client,
".implode(",\n ", $select)."
FROM {$table} AS k
INNER JOIN (
SELECT TRIM(lms_issuer) AS lms_issuer, TRIM(lms_client) AS lms_client
FROM {$table}
WHERE lms_issuer IS NOT NULL AND TRIM(lms_issuer) <> ''
AND lms_client IS NOT NULL AND TRIM(lms_client) <> ''
GROUP BY TRIM(lms_issuer), TRIM(lms_client)
HAVING ".implode("\n OR ", $having)."
) AS d
ON TRIM(k.lms_issuer) = d.lms_issuer
AND TRIM(k.lms_client) = d.lms_client
ORDER BY TRIM(k.lms_issuer), TRIM(k.lms_client), k.key_id"
);
if ( ! is_array($rows) || count($rows) < 1 ) {
return $empty;
}
$grouped = array();
foreach ( $rows as $row ) {
$issuer = trim((string) U::get($row, 'lms_issuer', ''));
$client = trim((string) U::get($row, 'lms_client', ''));
$bucket = $issuer."\n".$client;
if ( ! isset($grouped[$bucket]) ) {
$grouped[$bucket] = array(
'lms_issuer' => $issuer,
'lms_client' => $client,
'keys' => array(),
);
}
$grouped[$bucket]['keys'][] = $row;
}
$groups = array();
foreach ( $grouped as $group ) {
$fields = array();
foreach ( $present as $column => $label ) {
$values = array();
foreach ( $group['keys'] as $keyrow ) {
$value = U::get($keyrow, $column);
if ( ! is_string($value) ) continue;
$value = trim($value);
if ( $value === '' ) continue;
$values[self::clientConfigCompareValue($value)] = true;
}
if ( count($values) > 1 ) $fields[$column] = $label;
}
if ( count($fields) < 1 ) continue;
$group['fields'] = $fields;
$groups[] = $group;
}
return $groups;
}
/**
* Tables that store an LTI deployment id which should be a function of key_id.
*
* lti_link has no deployment id column. lti_tool_deployment.deployment_id is
* an outbound tool id. One key may have many.
*
* @return array
*/
private static function deploymentIdCopies() {
return array(
array(
'table' => 'lti_key',
'column' => 'deploy_key',
'id_column' => 'key_id',
'label' => 'Key',
),
array(
'table' => 'lti_context',
'column' => 'lti13_deployment_id',
'id_column' => 'context_id',
'label' => 'Context',
),
);
}
/**
* Keys whose deployment id is not a single value.
*
* The key's own deployment id and every copy on a context are read together.
* A blank value, or the literal
* word "null" in any ASCII case, does not count. That matches how the key
* form stores a blank deployment id. Every other value is compared as
* stored bytes, so a difference in case or accents is a conflict. Deleted
* rows are included.
*
* @return array}>}>
*/
public static function keyDeploymentConflictGroups() {
global $PDOX, $CFG;
$empty = array();
if ( ! is_object($PDOX) ) {
return $empty;
}
$prefix = $CFG->dbprefix;
$key_table = "{$prefix}lti_key";
$key_names = self::ltiKeyColumnNames($key_table);
$deleted_sql = in_array('deleted', $key_names, true) ? 'MIN(k.deleted)' : '0';
$title_sql = in_array('key_title', $key_names, true) ? 'MIN(k.key_title)' : "''";
$found_rows = array();
foreach ( self::deploymentIdCopies() as $copy ) {
$table = "{$prefix}{$copy['table']}";
if ( $copy['table'] === 'lti_key' ) {
$names = $key_names;
} else {
$described = $PDOX->describe($table);
if ( ! is_array($described) ) continue;
$names = array();
foreach ( $described as $column ) {
if ( is_array($column) && isset($column['Field']) ) $names[] = $column['Field'];
}
}
if ( ! in_array($copy['column'], $names, true) || ! in_array($copy['id_column'], $names, true) ) {
continue;
}
if ( ! in_array('key_id', $names, true) ) {
continue;
}
$expr = 't.'.$copy['column'];
$label_sql = str_replace("'", "''", $copy['label']);
$sql = "SELECT t.key_id AS key_id,
{$title_sql} AS key_title,
{$deleted_sql} AS deleted,
'{$label_sql}' AS source,
MIN(TRIM({$expr})) AS deployment_id,
COUNT(*) AS row_count,
MIN(t.{$copy['id_column']}) AS example_id
FROM {$table} AS t
INNER JOIN {$key_table} AS k ON k.key_id = t.key_id
WHERE {$expr} IS NOT NULL
AND TRIM({$expr}) <> ''
-- The word null, in any ASCII case, is a blank. Compare
-- those bytes so the column collation cannot fold an
-- accented value into that word. The GROUP BY below
-- keeps every other difference, including case.
AND CAST(LOWER(TRIM({$expr})) AS BINARY) <> 'null'
GROUP BY t.key_id, CAST(TRIM({$expr}) AS BINARY)";
$found = self::diagnosticRows($sql);
foreach ( $found as $row ) $found_rows[] = $row;
}
$by_key = array();
foreach ( $found_rows as $row ) {
$key_id = (int) U::get($row, 'key_id', 0);
if ( $key_id < 1 ) continue;
$raw = U::get($row, 'deployment_id');
$deployment = self::normalize_deploy_key_input(is_scalar($raw) ? (string) $raw : null);
if ( $deployment === null ) continue;
if ( ! isset($by_key[$key_id]) ) {
$title = U::get($row, 'key_title');
$by_key[$key_id] = array(
'key_id' => $key_id,
'key_title' => is_string($title) ? $title : '',
'deleted' => (int) U::get($row, 'deleted', 0),
'values' => array(),
);
}
if ( ! isset($by_key[$key_id]['values'][$deployment]) ) {
$by_key[$key_id]['values'][$deployment] = array(
'deployment_id' => $deployment,
'places' => array(),
);
}
$by_key[$key_id]['values'][$deployment]['places'][] = array(
'label' => (string) U::get($row, 'source', ''),
'count' => (int) U::get($row, 'row_count', 0),
'example_id' => (int) U::get($row, 'example_id', 0),
);
}
ksort($by_key);
$groups = array();
foreach ( $by_key as $group ) {
if ( count($group['values']) < 2 ) continue;
ksort($group['values']);
$group['values'] = array_values($group['values']);
$groups[] = $group;
}
return $groups;
}
/**
* Identity columns the upgrade narrows to varchar(255) character set ascii collation ascii_bin.
*
* @return array
*/
public static function identityAsciiColumns() {
return array(
array('lti_key', 'key_key', 'key_id'),
array('lti_key', 'secret', 'key_id'),
array('lti_key', 'new_secret', 'key_id'),
array('lti_key', 'deploy_key', 'key_id'),
array('lti_key', 'lms_issuer', 'key_id'),
array('lti_key', 'lms_client', 'key_id'),
array('lti_context', 'context_key', 'context_id'),
array('lti_context', 'lti13_deployment_id', 'context_id'),
array('lti_link', 'link_key', 'link_id'),
array('lti_content', 'resource_link_id', 'content_id'),
array('lti_domain', 'consumer_key', 'domain_id'),
array('lti_domain', 'secret', 'domain_id'),
array('lti_tool_registration', 'lti11_key', 'registration_id'),
array('lti_tool_registration', 'lti11_secret', 'registration_id'),
array('lti_tool_registration', 'lti13_client_id', 'registration_id'),
array('lti_tool_deployment', 'deployment_id', 'tool_deployment_id'),
);
}
/**
* Identity columns that are not yet varchar(255) character set ascii collation ascii_bin.
* A missing table or column is included. Names are table.column without the database prefix.
*
* @return array
*/
public static function columnsNotYetAscii255() {
global $PDOX, $CFG;
$wanted = array();
foreach ( self::identityAsciiColumns() as $column ) {
$wanted[$column[0].'.'.$column[1]] = true;
}
if ( ! is_object($PDOX) ) {
throw new \RuntimeException('could not read identity column types');
}
$prefix = isset($CFG->dbprefix) ? (string) $CFG->dbprefix : '';
$clauses = array();
$params = array();
$i = 0;
foreach ( self::identityAsciiColumns() as $column ) {
$clauses[] = '(TABLE_NAME = :t'.$i.' AND COLUMN_NAME = :c'.$i.')';
$params[':t'.$i] = $prefix.$column[0];
$params[':c'.$i] = $column[1];
$i++;
}
$rows = $PDOX->allRows(
"SELECT TABLE_NAME AS table_name, COLUMN_NAME AS column_name,
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 (".implode(' OR ', $clauses).")",
$params,
false
);
if ( ! is_array($rows) ) {
throw new \RuntimeException('could not read identity column types');
}
$ready = array();
foreach ( $rows as $row ) {
$table = (string) U::getIgnoreCase($row, 'table_name');
$column = (string) U::getIgnoreCase($row, 'column_name');
if ( $prefix !== '' && str_starts_with($table, $prefix) ) {
$table = substr($table, strlen($prefix));
}
$name = $table.'.'.$column;
$ok = strtolower((string) U::getIgnoreCase($row, 'data_type')) === 'varchar'
&& (int) U::getIgnoreCase($row, 'char_length') === 255
&& strtolower((string) U::getIgnoreCase($row, 'charset_name')) === 'ascii'
&& strtolower((string) U::getIgnoreCase($row, 'collation_name')) === 'ascii_bin';
if ( $ok ) $ready[$name] = true;
}
$notYet = array();
foreach ( array_keys($wanted) as $name ) {
if ( ! isset($ready[$name]) ) $notYet[] = $name;
}
return $notYet;
}
/**
* TEXT columns that store an issuer, client id, deployment id, context id,
* resource link id, LTI 1.1 consumer key, or secret.
*
* These are the values a varchar(255) column would have to hold, and the
* values an ascii column would have to hold. The length check and the
* non-ASCII check both read this list. Outbound
* lti_tool_registration.lti13_client_id, lti_tool_registration.lti11_key,
* and lti_tool_deployment.deployment_id are already varchar(255). lti_link
* has no deployment id column, and one will not be added. A link's resource
* link id is link_key. lti_content keeps its own copy. A secret column is marked redact
* so a check can report the row without returning the secret.
*
* @return array
*/
private static function valuesLongerThan255Copies() {
return array(
array(
'table' => 'lti_key',
'column' => 'lms_issuer',
'label' => 'Issuer',
'id_column' => 'key_id',
),
array(
'table' => 'lti_key',
'column' => 'lms_client',
'label' => 'Client id',
'id_column' => 'key_id',
),
array(
'table' => 'lti_key',
'column' => 'deploy_key',
'label' => 'Deployment id',
'id_column' => 'key_id',
),
array(
'table' => 'lti_context',
'column' => 'lti13_deployment_id',
'label' => 'Deployment id',
'id_column' => 'context_id',
),
array(
'table' => 'lti_context',
'column' => 'context_key',
'label' => 'Context id',
'id_column' => 'context_id',
),
array(
'table' => 'lti_link',
'column' => 'link_key',
'label' => 'Resource link id',
'id_column' => 'link_id',
'via_context' => true,
),
array(
'table' => 'lti_content',
'column' => 'resource_link_id',
'label' => 'Resource link id',
'id_column' => 'content_id',
),
array(
'table' => 'lti_key',
'column' => 'key_key',
'label' => 'Consumer key',
'id_column' => 'key_id',
),
array(
'table' => 'lti_key',
'column' => 'secret',
'label' => 'Secret',
'id_column' => 'key_id',
'redact' => true,
),
array(
'table' => 'lti_key',
'column' => 'new_secret',
'label' => 'New secret',
'id_column' => 'key_id',
'redact' => true,
),
array(
'table' => 'lti_domain',
'column' => 'consumer_key',
'label' => 'Consumer key',
'id_column' => 'domain_id',
),
array(
'table' => 'lti_domain',
'column' => 'secret',
'label' => 'Secret',
'id_column' => 'domain_id',
'redact' => true,
),
array(
'table' => 'lti_tool_registration',
'column' => 'lti11_secret',
'label' => 'Secret',
'id_column' => 'registration_id',
'redact' => true,
),
);
}
/**
* Identity values that do not fit in varchar(255).
*
* CHAR_LENGTH counts characters, which is the varchar limit. Blank values
* are short, so they are absent. Deleted rows are included.
*
* @return array
*/
public static function valuesLongerThan255() {
global $PDOX, $CFG;
$empty = array();
if ( ! is_object($PDOX) ) {
return $empty;
}
$prefix = $CFG->dbprefix;
$found = array();
foreach ( self::valuesLongerThan255Copies() as $copy ) {
$table = "{$prefix}{$copy['table']}";
$described = $PDOX->describe($table);
if ( ! is_array($described) ) continue;
$names = array();
foreach ( $described as $column ) {
if ( is_array($column) && isset($column['Field']) ) $names[] = $column['Field'];
}
if ( ! in_array($copy['column'], $names, true) || ! in_array($copy['id_column'], $names, true) ) {
continue;
}
if ( ! empty($copy['via_context']) && ! in_array('context_id', $names, true) ) {
continue;
}
$expr = 't.'.$copy['column'];
$redact = ! empty($copy['redact']);
$key_sql = in_array('key_id', $names, true) ? 't.key_id' : '0';
$join = '';
if ( ! empty($copy['via_context']) ) {
$key_sql = 'ctx.key_id';
$join = "INNER JOIN {$prefix}lti_context AS ctx ON ctx.context_id = t.context_id";
}
$sample_sql = $redact ? 'NULL AS sample_value' : "SUBSTRING({$expr}, 1, 80) AS sample_value";
$rows = self::diagnosticRows(
"SELECT {$key_sql} AS key_id,
t.{$copy['id_column']} AS row_id,
CHAR_LENGTH({$expr}) AS value_length,
{$sample_sql}
FROM {$table} AS t
{$join}
WHERE {$expr} IS NOT NULL
AND CHAR_LENGTH({$expr}) > 255
ORDER BY CHAR_LENGTH({$expr}) DESC, t.{$copy['id_column']}"
);
foreach ( $rows as $row ) {
$length = (int) U::get($row, 'value_length', 0);
$sample = $redact ? '' : (string) U::get($row, 'sample_value', '');
if ( ! $redact && $length > 80 ) $sample .= '...';
$found[] = array(
'label' => $copy['label'],
'table' => $copy['table'],
'column' => $copy['column'],
'row_id' => (int) U::get($row, 'row_id', 0),
'key_id' => (int) U::get($row, 'key_id', 0),
'length' => $length,
'sample' => $sample,
'redacted' => $redact,
);
}
}
usort($found, function ($a, $b) {
if ( $a['length'] !== $b['length'] ) return $b['length'] - $a['length'];
if ( $a['key_id'] !== $b['key_id'] ) return $a['key_id'] - $b['key_id'];
return $a['row_id'] - $b['row_id'];
});
return $found;
}
/**
* Identity values that contain a character outside ASCII.
*
* These columns are utf8, so a character outside ASCII is more than one
* byte. LENGTH counts bytes and CHAR_LENGTH counts characters. An ascii
* column, including ascii_bin, cannot store that character. Blank values
* are ASCII, so they are absent. Deleted rows are included. A secret is
* reported by its lengths only.
*
* @return array
*/
public static function nonAsciiValues() {
global $PDOX, $CFG;
$empty = array();
if ( ! is_object($PDOX) ) {
return $empty;
}
$prefix = $CFG->dbprefix;
$found = array();
foreach ( self::valuesLongerThan255Copies() as $copy ) {
$table = "{$prefix}{$copy['table']}";
$described = $PDOX->describe($table);
if ( ! is_array($described) ) continue;
$names = array();
foreach ( $described as $column ) {
if ( is_array($column) && isset($column['Field']) ) $names[] = $column['Field'];
}
if ( ! in_array($copy['column'], $names, true) || ! in_array($copy['id_column'], $names, true) ) {
continue;
}
if ( ! empty($copy['via_context']) && ! in_array('context_id', $names, true) ) {
continue;
}
$expr = 't.'.$copy['column'];
$redact = ! empty($copy['redact']);
$key_sql = in_array('key_id', $names, true) ? 't.key_id' : '0';
$join = '';
if ( ! empty($copy['via_context']) ) {
$key_sql = 'ctx.key_id';
$join = "INNER JOIN {$prefix}lti_context AS ctx ON ctx.context_id = t.context_id";
}
$sample_sql = $redact ? 'NULL AS sample_value' : "SUBSTRING({$expr}, 1, 255) AS sample_value";
$rows = self::diagnosticRows(
"SELECT {$key_sql} AS key_id,
t.{$copy['id_column']} AS row_id,
CHAR_LENGTH({$expr}) AS value_length,
LENGTH({$expr}) AS value_bytes,
{$sample_sql}
FROM {$table} AS t
{$join}
WHERE {$expr} IS NOT NULL
AND CHAR_LENGTH({$expr}) <> LENGTH({$expr})
ORDER BY LENGTH({$expr}) DESC, t.{$copy['id_column']}"
);
foreach ( $rows as $row ) {
$length = (int) U::get($row, 'value_length', 0);
$bytes = (int) U::get($row, 'value_bytes', 0);
$sample = '';
if ( ! $redact ) {
$raw = (string) U::get($row, 'sample_value', '');
$sample = self::nonAsciiSample($raw, $length > 255);
}
$found[] = array(
'label' => $copy['label'],
'table' => $copy['table'],
'column' => $copy['column'],
'row_id' => (int) U::get($row, 'row_id', 0),
'key_id' => (int) U::get($row, 'key_id', 0),
'length' => $length,
'bytes' => $bytes,
'sample' => $sample,
'redacted' => $redact,
);
}
}
usort($found, function ($a, $b) {
if ( $a['bytes'] !== $b['bytes'] ) return $b['bytes'] - $a['bytes'];
if ( $a['key_id'] !== $b['key_id'] ) return $a['key_id'] - $b['key_id'];
return $a['row_id'] - $b['row_id'];
});
return $found;
}
/**
* A short window of a non-secret value, centered on the first character
* outside ASCII when that character is in the fetched prefix.
*/
private static function nonAsciiSample($raw, $truncated) {
$raw = (string) $raw;
$at_byte = null;
if ( $raw !== '' && preg_match('/[^\x00-\x7F]/u', $raw, $match, PREG_OFFSET_CAPTURE) ) {
$at_byte = $match[0][1];
}
if ( $at_byte === null ) {
$sample = mb_substr($raw, 0, 80);
if ( $truncated || mb_strlen($raw) > 80 ) $sample .= '...';
return $sample;
}
$char_at = mb_strlen(substr($raw, 0, $at_byte));
$start = max(0, $char_at - 20);
$sample = mb_substr($raw, $start, 60);
if ( $start > 0 ) $sample = '...'.$sample;
if ( $truncated || mb_strlen($raw) > $start + 60 ) $sample .= '...';
return $sample;
}
/**
* Reject a new or updated tenant when another live key already has this
* issuer, client id, and deployment id.
*
* A blank deployment id is its own value. Two blank deployment ids for the
* same issuer and client id collide. A specific deployment id collides
* only with that same deployment id.
*/
public static function validate_issuer_client_unique($lms_issuer, $lms_client, $deploy_key, $exclude_key_id=null) {
global $PDOX, $CFG;
$pair = self::resolve_lti13_issuer_client($lms_issuer, $lms_client);
if ( $pair === null ) {
return true;
}
$deploy = self::normalize_deploy_key_input($deploy_key);
$parms = array(
':issuer_sha256' => $pair['issuer_sha256'],
':issuer_client' => $pair['issuer_client'],
);
$exclude_sql = '';
if ( ! empty($exclude_key_id) && (int) $exclude_key_id > 0 ) {
$exclude_sql = ' AND k.key_id <> :exclude_key_id ';
$parms[':exclude_key_id'] = (int) $exclude_key_id;
}
if ( $deploy === null ) {
$deploy_sql = "AND (k.deploy_key IS NULL OR TRIM(k.deploy_key) = '' OR LOWER(TRIM(k.deploy_key)) = 'null')";
} else {
$deploy_sql = 'AND TRIM(k.deploy_key) = :deploy_key';
$parms[':deploy_key'] = $deploy;
}
$row = $PDOX->rowDie(
"SELECT k.key_id, k.key_title FROM {$CFG->dbprefix}lti_key AS k
WHERE (k.deleted IS NULL OR k.deleted = 0)
$exclude_sql
AND k.lms_issuer_sha256 = :issuer_sha256
AND k.lms_client = :issuer_client
$deploy_sql
LIMIT 1",
$parms
);
if ( $row ) {
$label = U::isNotEmpty($row['key_title']) ? $row['key_title'] : ('key_id '.$row['key_id']);
if ( $deploy === null ) {
U::flashError('A key with this LTI 1.3 issuer, client id, and a blank deployment id already exists ('.$label.')');
} else {
U::flashError('A key with this LTI 1.3 issuer, client id, and deployment id already exists ('.$label.')');
}
return false;
}
return true;
}
/**
* Status label for a tenant key on the admin list and detail page.
*
* A consumer key with a secret is LTI 1.1. A consumer key without a secret
* is LTI 1.1 and Draft. An issuer makes the key LTI 1.3. It stays Draft
* until the client id, OIDC login URL, keyset URL, and token URL are set.
*
* @param array $row
*/
public static function keyTypeLabel(array $row) {
$parts = array();
$draft = false;
if ( U::isNotEmpty(U::get($row, 'key_key')) ) {
$parts[] = 'LTI 1.1';
if ( ! U::isNotEmpty(U::get($row, 'secret')) ) {
$draft = true;
}
}
if ( U::isNotEmpty(U::get($row, 'lms_issuer')) ) {
$parts[] = 'LTI 1.3';
if ( ! U::isNotEmpty(U::get($row, 'lms_client'))
|| ! U::isNotEmpty(U::get($row, 'lms_oidc_auth'))
|| ! U::isNotEmpty(U::get($row, 'lms_keyset_url'))
|| ! U::isNotEmpty(U::get($row, 'lms_token_url')) ) {
$draft = true;
}
}
$registration_id = (int) U::get($row, 'lti_registration_id');
if ( $registration_id > 0 ) {
$parts[] = 'Registration';
}
if ( $draft || count($parts) < 1 ) {
$parts[] = 'Draft';
}
return implode(' / ', $parts);
}
/**
* keyTypeLabel with the Registration word linked to that registration.
*
* @param array $row
*/
public static function keyTypeHtml(array $row) {
$label = htmlspecialchars(self::keyTypeLabel($row), ENT_QUOTES, 'UTF-8');
$id = (int) U::get($row, 'lti_registration_id');
if ( $id < 1 ) {
return $label;
}
$href = 'registration-detail?lti_registration_id='.$id;
$link = 'Registration';
return str_replace('Registration', $link, $label);
}
/**
* Hand-entered inbound registrations for the key admin screens.
*
* @return array>
*/
public static function inboundRegistrationChoices() {
global $PDOX, $CFG;
$rows = $PDOX->allRowsDie(
"SELECT lti_registration_id, title, issuer, client_id
FROM {$CFG->dbprefix}lti_registration
ORDER BY title, issuer, client_id, lti_registration_id",
array()
);
return is_array($rows) ? $rows : array();
}
/**
* @param int $id
* @return array|null
*/
public static function inboundRegistrationById($id) {
global $PDOX, $CFG;
$id = (int) $id;
if ( $id < 1 ) {
return null;
}
$row = $PDOX->rowDie(
"SELECT lti_registration_id, title, notes, issuer, client_id, oidc_auth_url, keyset_url,
token_url, token_audience, unlock_code
FROM {$CFG->dbprefix}lti_registration
WHERE lti_registration_id = :id",
array(':id' => $id)
);
return is_array($row) ? $row : null;
}
/**
* Keys that point at one inbound registration.
*
* @param int $id
* @return array>
*/
public static function keysForInboundRegistration($id) {
global $PDOX, $CFG;
$id = (int) $id;
if ( $id < 1 ) {
return array();
}
$rows = $PDOX->allRowsDie(
"SELECT key_id, key_title, key_key, secret, lms_issuer, lms_client,
lms_oidc_auth, lms_keyset_url, lms_token_url, deploy_key, lti_registration_id
FROM {$CFG->dbprefix}lti_key
WHERE lti_registration_id = :id
ORDER BY key_title, key_id",
array(':id' => $id)
);
return is_array($rows) ? $rows : array();
}
/**
* Registrations with this key's issuer, client id, and platform URLs.
*
* @param array $key
* @return array>
*/
public static function registrationsMatchingKeyPlatform(array $key) {
global $PDOX, $CFG;
$issuer = self::trimToNull(U::get($key, 'lms_issuer'));
$client = self::trimToNull(U::get($key, 'lms_client'));
$oidc = self::trimToNull(U::get($key, 'lms_oidc_auth'));
$keyset = self::trimToNull(U::get($key, 'lms_keyset_url'));
$token = self::trimToNull(U::get($key, 'lms_token_url'));
if ( $issuer === null || $client === null || $oidc === null || $keyset === null || $token === null ) {
return array();
}
$rows = $PDOX->allRowsDie(
"SELECT lti_registration_id, title, issuer, client_id, oidc_auth_url, keyset_url, token_url
FROM {$CFG->dbprefix}lti_registration
WHERE issuer = :issuer AND client_id = :client",
array(':issuer' => $issuer, ':client' => $client)
);
if ( ! is_array($rows) ) {
return array();
}
$matches = array();
foreach ( $rows as $row ) {
if ( self::trimToNull(U::get($row, 'oidc_auth_url')) !== $oidc ) continue;
if ( self::trimToNull(U::get($row, 'keyset_url')) !== $keyset ) continue;
if ( self::trimToNull(U::get($row, 'token_url')) !== $token ) continue;
$matches[] = $row;
}
return $matches;
}
/**
* Note when a saved key already lines up with a registration.
*
* @param array $key
*/
public static function matchingRegistrationNote(array $key) {
$matches = self::registrationsMatchingKeyPlatform($key);
if ( count($matches) < 1 ) {
return '';
}
$links = array();
foreach ( $matches as $match ) {
$id = (int) U::get($match, 'lti_registration_id');
$href = 'registration-detail?lti_registration_id='.$id;
$label = htmlspecialchars(self::inboundRegistrationLabel($match), ENT_QUOTES, 'UTF-8');
$links[] = ''.$label.'';
}
$linked = (int) U::get($key, 'lti_registration_id');
$same = count($matches) === 1 && $linked > 0 && (int) U::get($matches[0], 'lti_registration_id') === $linked;
if ( $same ) {
$text = 'This registration matches this key\'s issuer, client id, and platform URLs: ';
} else if ( count($matches) === 1 ) {
$text = 'A registration already matches this key\'s issuer, client id, and platform URLs: ';
} else {
$text = 'These registrations match this key\'s issuer, client id, and platform URLs: ';
}
return '
'.$text.implode(', ', $links).'.
'."\n";
}
/**
* @param array $row
*/
public static function inboundRegistrationLabel(array $row) {
$issuer = (string) U::get($row, 'issuer', '');
$client = U::get($row, 'client_id');
$title = self::trimToNull(U::get($row, 'title'));
$client_label = U::isNotEmpty($client) ? (string) $client : '(no client id)';
$parts = array();
if ( $title !== null ) $parts[] = $title;
if ( $issuer !== '' ) $parts[] = $issuer;
$parts[] = $client_label;
return implode(' / ', $parts);
}
/**
* Platform columns copied onto a key. Emptying a registration link clears these.
*
* @return array
*/
public static function keyPlatformFields() {
return array('lms_issuer', 'lms_client', 'lms_oidc_auth', 'lms_keyset_url', 'lms_token_url', 'lms_token_audience');
}
/**
* Shown under the registration control. The rule separates it from the platform fields.
*
* @param bool $edit
* @param int $selectedId
*/
private static function registrationPlatformFieldsNote($edit, $selectedId = 0) {
$html = '';
if ( ! $edit ) {
$html .= "
The issuer, client id, and platform URLs below stay on this key unless you empty them.
After you have associated this key with a registration, you can empty the issuer, client id, and platform URLs on this key.
\n"
."
\n\n"
."
Checked, these fields are cleared when you save. Unchecked, they stay on the key.
\n"
."
\n"
."
\n"
."\n";
}
$html .= "\n";
return $html;
}
/**
* Select or read-only link for the key form. Does not show unused columns.
*
* @param int $selectedId
* @param bool $edit
*/
public static function inboundRegistrationControl($selectedId, $edit) {
$selectedId = (int) $selectedId;
if ( ! $edit ) {
if ( $selectedId < 1 ) {
return "