Courses
extends Tool
in package
Base class for LMS tool controllers
Provides common functionality for controllers that need LMS utilities like instructor checking, analytics recording, etc.
Table of Contents
Constants
- FLYOUT_LIMIT : mixed = 5
- Courses shown in the site-menu flyout (fits on screen; no scrollbar).
- ROUTE : mixed = '/courses'
- SESSION_LESSONS_GRADE_REFRESH_AFTER_LAUNCH : mixed = 'tsugi_lessons_refresh_grades_on_view'
- When set after an outbound LTI 1.1 launch, the next {@see \Tsugi\Controllers\Lessons::get()} or {@see \Tsugi\Controllers\LaunchController::returnFromTool()} run clears the grade cache via {@see applyGradeRefreshAfterLaunchReturn()}.
- SESSION_SITE_CONTEXT_ID : mixed = 'site_context_id'
- Session key for the Google site-login course (never overwritten by /courses/{id}).
Properties
- $dispatchingNested : bool
Methods
- appHomeUrl() : string
- App home (home_path, else apphome, else wwwroot).
- applyGradeRefreshAfterLaunchReturn() : mixed
- After an outbound LTI launch, if {@see SESSION_LESSONS_GRADE_REFRESH_AFTER_LAUNCH} is set, invalidate the current user's grade cache and clear the flag (next page load / return handler).
- checkCsrf() : bool
- True when the CSRF token is valid (fail closed). Flashes on failure.
- configuredHomeUrl() : string
- Site home for redirects: {@see ConfigInfo::$apphome} when set and non-empty, else {@see ConfigInfo::$wwwroot}.
- courseHomeUrl() : mixed
- Course Home URL after switching into /courses/{id}.
- courseIdFromRequest() : mixed
- Context id from a course-mounted REQUEST_URI, or 0.
- courseLocalPrefixes() : array<string|int, string>
- First path segments under the course base that are course content.
- courseUrlPrefix() : mixed
- Absolute or path prefix for /courses/{id} with no trailing slash.
- createForm() : mixed
- Form to create a new site-login course with a starter manifest.
- createGateResponse() : Response|null
- Login + Google session + allow_course_create + course.create (or site admin).
- createPost() : mixed
- POST: insert context + starter manifest, enter the course.
- csrfField() : string
- Hidden CSRF_TOKEN input for cookie-session HTML forms that POST to Tsugi.
- csrfOk() : bool
- True when POST CSRF_TOKEN (or X-CSRF-TOKEN) matches the session token, or the browser marks this POST as same-origin.
- csrfRedirect() : bool
- For classic PHP tools that redirect with header('Location').
- determineParentPath() : string
- Static helper to determine the parent path dynamically from the request
- determineToolHome() : string
- Static form of {@see toolHome()} for launch methods that have no instance.
- dropActiveContext() : void
- Forget $context_id when it is the course in this session.
- ensureActiveContext() : true|string
- Switch the Google-login session to $context_id when needed.
- enter() : mixed
- exitPlusLeftCourse() : mixed
- Stop a Plus launch that opened a site tool.
- gateResponse() : Response|null
- Google site-login, or the Plus launch for this same course.
- getjson() : mixed
- image() : mixed
- Serve a course hero or icon.
- index() : mixed
- innerRequest() : mixed
- Build an inner request whose pathInfo is /{rest}.
- isAnonymousLessonRest() : bool
- GET /courses/{id}/lessons, /content, or /outline, or one module under any of them.
- isAnonymousPageRest() : bool
- A published-page GET: /courses/{id}/pages or /courses/{id}/pages/{key}.
- isCourseMountedRequest() : mixed
- True when REQUEST_URI is /courses/{id} or /courses/{id}/…
- isCourseRoute() : mixed
- True when this request is /courses/{id}{route}... (not the unprefixed tool URL).
- isGoogleLoginSession() : mixed
- True when this session is a Google site login (not an LMS LTI launch).
- joinToolHome() : string
- Join a mounted tool home and a suffix without producing `//path`.
- lessonsUrl() : string
- Absolute URL of /courses/{id}/lessons.
- membershipHref() : mixed
- Where a membership card opens. The Google site-login course opens the app home, not /courses/{id}.
- nested() : mixed
- outboundContextTitle() : mixed
- Course title for an outbound LTI launch.
- plusLeftCourseApplies() : mixed
- True when this request is a Plus launch on a site URL.
- releaseContextAfterDelete() : void
- Drop a deleted course from the session and return to the site-login course when one remains.
- releaseUnmountedCourse() : mixed
- A site URL is not the launch course. Drop the top-level course fields.
- requestPath() : string
- REQUEST_URI path with query stripped and a single leading slash.
- requireCsrf() : RedirectResponse|null
- Redirect back to $redirect when the CSRF token is missing or invalid.
- requireCsrfJson() : JsonResponse|null
- JSON 403 when the CSRF token is missing or invalid (no flash).
- requireOutboundLti11LaunchSession() : RedirectResponse|null
- Require LTI consumer session fields needed to sign an outbound LTI 1.1 launch.
- restoreSiteLoginContext() : mixed
- On site URLs (buildmenu world), drop a leftover /courses/{id} sandbox and put the Google-login course back in the session.
- routes() : mixed
- sameOriginPost() : bool
- True when this request is a same-origin navigation (not a cross-site CSRF POST).
- sendLti11LaunchFromContent() : RedirectResponse|string
- Sign a lesson launch from an lti_content row.
- sendLti11LaunchFromLessonsItem() : RedirectResponse|string
- Build and print the auto-submit HTML for an LTI 1.1 basic-lti-launch-request to a tool URL described by a lessons.json / lessons-items item (same shape as {@see \Tsugi\Services\Lessons\LessonsService::getLtiByRlid()}).
- showCoursesWidget() : mixed
- Site top-menu waffle. Off unless $CFG->show_courses_widget is set.
- siteLoginContextId() : mixed
- Google site-login context id, or 0.
- siteLoginRedirect() : RedirectResponse|null
- Redirect the Google site-login course to the app home.
- toolPathPrefix() : mixed
- Path prefix for this request: '' or '/courses/{id}' (no trailing slash).
- wireLaunchConnection() : mixed
- Point Context/Output at $TSUGI_LAUNCH and ensure it has a PDOX connection.
- withImageUrls() : array<int, array<string, mixed>>
- Replace image byte metadata with versioned URLs. Does not touch BLOBs.
- assetUrl() : mixed
- Alias for staticUrl() for backward compatibility
- controllerUrl() : string
- Generate URL to another controller
- courseFileBaseUrl() : string
- Current course base URL for Common Cartridge file-base rewriting.
- courseRequiredHtml() : string
- exitCourseRequired() : mixed
- A site tool such as grades was opened with no course.
- externalLinkAttrs() : array<string|int, mixed>
- Get link attributes for external vs same-site URLs
- isAdmin() : bool
- Check if the current user is a site administrator
- isInstructor() : bool
- Check if the current logged-in user is an instructor/admin for the current context
- leavePageReturnScript() : string
- Point Continue at this tab's launch return before footer scripts replace TSUGI_SESSION_DATA with the current page.
- lmsAnalyticsKey() : string
- Build a stable key for LMS analytics, distinct from LTI resource_link_id values.
- lmsAnalyticsPath() : string
- Build a stable path identifier for LMS tools (no query/session params).
- lmsEnsureAnalyticsLink() : int|false
- Ensure there is an `lti_link` row for a local LMS page/tool and return link_id.
- lmsRecordLaunchAnalytics() : int|false
- Record LMS page/tool "launch" into Tsugi internal analytics, mirroring LTIX behavior.
- plusLeftCourseHtml() : string
- renderLeavePage() : string
- Error page with Close Tab and Continue.
- requireAuth() : mixed
- Check authentication and context
- requireGlobalRoute() : RedirectResponse|null
- Bounce a course-mounted URL to a global (unprefixed) URL.
- requireInstructor() : bool
- Check if user is instructor/admin, redirect if not
- showAnalytics() : string
- Display analytics for an LMS tool
- staticUrl() : string
- Generate URL for a controller-specific static file (JS, CSS, etc.)
- toolHome() : string
- Get the base path for this tool (e.g., '/py4e/pages' or '/courses/2/pages')
- toolParent() : string
- Get the parent path one level above the tool home
- viewDueDates() : bool
- Whether the current user may see due dates in this context (lti_membership.viewDueDates).
- anonymousContentRequest() : bool
- Lessons outline or a published page for an anonymous reader.
- anonymousLessonsOpen() : bool
- This course's lti_context.anonymous_lessons is on, and it is a live manifest course.
- clearActiveContext() : void
- Forget the current course in this session.
-
courseSwitchErrorCopy()
: array{title: string, paragraphs: array
, home: string} - deniedCourseHome() : mixed
- Home after a course URL refuses the logged-in user.
- dispatchAnonymousLessons() : mixed
- Render lessons, or a published page, for someone who is not in the course.
- establishReqScope() : mixed
- User, course, and role for this request. The session course write stays.
- filesForCreate() : array<string, mixed>
- FileBag turns empty inputs into null; Request::create() rejects null.
- flyoutMembershipSql() : mixed
- Flyout memberships: never-visited rows use created_at so new enrollments still surface. Caller adds WHERE extras and LIMIT.
- imageResponse() : mixed
- JPEG bytes with a versioned ETag, or 404.
- isAnonymousLessonTail() : bool
- launchErrorRedirect() : RedirectResponse|null
- Redirect to the platform error return, or null when this session has none.
- launchErrorReturnUrl() : string|null
- Platform URL for a Plus or LTI launch, or null.
- listedCourseSql() : mixed
- Courses with no manifest stay off Courses and the flyout.
- loginRedirectForCourse() : mixed
- Send a logged-out /courses/{id} visitor to login, and bring them back here.
- noteCourseLogin() : mixed
- Last access for this course. A visit inside five minutes leaves the stamp.
- plusOwnsCourseUrl() : mixed
- True when this request is /courses/{id} for the Plus launch in the session.
- renderCourseSwitchError() : mixed
- sanitizeFilesForCreate() : array<string|int, mixed>
- switchFailedResponse() : mixed
- viewerAlreadyInCourse() : bool
- Logged-in member (or site admin) who can already open this course.
Constants
FLYOUT_LIMIT
Courses shown in the site-menu flyout (fits on screen; no scrollbar).
public
mixed
FLYOUT_LIMIT
= 5
ROUTE
public
mixed
ROUTE
= '/courses'
SESSION_LESSONS_GRADE_REFRESH_AFTER_LAUNCH
When set after an outbound LTI 1.1 launch, the next {@see \Tsugi\Controllers\Lessons::get()} or {@see \Tsugi\Controllers\LaunchController::returnFromTool()} run clears the grade cache via {@see applyGradeRefreshAfterLaunchReturn()}.
public
mixed
SESSION_LESSONS_GRADE_REFRESH_AFTER_LAUNCH
= 'tsugi_lessons_refresh_grades_on_view'
SESSION_SITE_CONTEXT_ID
Session key for the Google site-login course (never overwritten by /courses/{id}).
public
mixed
SESSION_SITE_CONTEXT_ID
= 'site_context_id'
Properties
$dispatchingNested
private
static bool
$dispatchingNested
= false
Guard against re-dispatch loops.
Methods
appHomeUrl()
App home (home_path, else apphome, else wwwroot).
public
static appHomeUrl() : string
Return values
stringapplyGradeRefreshAfterLaunchReturn()
After an outbound LTI launch, if {@see SESSION_LESSONS_GRADE_REFRESH_AFTER_LAUNCH} is set, invalidate the current user's grade cache and clear the flag (next page load / return handler).
public
static applyGradeRefreshAfterLaunchReturn() : mixed
checkCsrf()
True when the CSRF token is valid (fail closed). Flashes on failure.
public
static checkCsrf() : bool
Return values
boolconfiguredHomeUrl()
Site home for redirects: {@see ConfigInfo::$apphome} when set and non-empty, else {@see ConfigInfo::$wwwroot}.
public
static configuredHomeUrl() : string
Return values
string —Non-empty path or URL (defaults to '/')
courseHomeUrl()
Course Home URL after switching into /courses/{id}.
public
static courseHomeUrl(mixed $context_id) : mixed
GET /courses/{id} used to bounce to the site apphome (bare /). That
leaves the course URL space and shows buildmenu.php. Send people to
/courses/{id}/home so the course nav owns the next page.
Parameters
- $context_id : mixed
courseIdFromRequest()
Context id from a course-mounted REQUEST_URI, or 0.
public
static courseIdFromRequest() : mixed
courseLocalPrefixes()
First path segments under the course base that are course content.
public
static courseLocalPrefixes() : array<string|int, string>
Passed into CCFileBase so that util does not know about controllers. Login, logout, admin, profile, and similar non-content routes are omitted.
Return values
array<string|int, string>courseUrlPrefix()
Absolute or path prefix for /courses/{id} with no trailing slash.
public
static courseUrlPrefix(mixed $context_id) : mixed
Parameters
- $context_id : mixed
createForm()
Form to create a new site-login course with a starter manifest.
public
static createForm(Application $app, Request $request) : mixed
Parameters
- $app : Application
- $request : Request
createGateResponse()
Login + Google session + allow_course_create + course.create (or site admin).
public
static createGateResponse(mixed $home) : Response|null
Parameters
- $home : mixed
Return values
Response|nullcreatePost()
POST: insert context + starter manifest, enter the course.
public
static createPost(Application $app, Request $request) : mixed
Parameters
- $app : Application
- $request : Request
csrfField()
Hidden CSRF_TOKEN input for cookie-session HTML forms that POST to Tsugi.
public
static csrfField() : string
Mints a session token if the current session does not have one yet (Google site login historically did not set CSRF_TOKEN; LTI launch does). Do not use this on LTI launches or signed webhooks.
Return values
stringcsrfOk()
True when POST CSRF_TOKEN (or X-CSRF-TOKEN) matches the session token, or the browser marks this POST as same-origin.
public
static csrfOk() : bool
Cookie-session pages (admin unlock) can lose the GET session cookie on the following POST; Chrome still sends Sec-Fetch-Site/Origin, which is enough to reject cross-site CSRF. LTI launches must not use this helper.
Return values
boolcsrfRedirect()
For classic PHP tools that redirect with header('Location').
public
static csrfRedirect(string $url) : bool
Parameters
- $url : string
-
Already session-bearing Location target.
Return values
bool —True when the caller should return (token was bad).
determineParentPath()
Static helper to determine the parent path dynamically from the request
public
static determineParentPath([string|null $route = null ]) : string
This is useful for static methods that need to determine the base path without having a Tool instance. It uses the same logic as toolParent() but works as a static method.
Parameters
- $route : string|null = null
-
Optional route to look for (if null, tries to detect from request)
Return values
string —The parent path (e.g., '/py4e' or '/ca4e/tsugi')
determineToolHome()
Static form of {@see toolHome()} for launch methods that have no instance.
public
static determineToolHome(string $route) : string
On a course-mounted page, a sibling tool keeps /courses/{id} even when
$route is not in this REQUEST_URI (Lessons → Quiz1).
Parameters
- $route : string
-
The route constant (e.g., '/discussions')
Return values
string —The mounted tool path (e.g., '/courses/2/discussions')
dropActiveContext()
Forget $context_id when it is the course in this session.
public
static dropActiveContext(int $context_id) : void
Leaves login, CSRF, and the stored LTI return URL in place.
Parameters
- $context_id : int
ensureActiveContext()
Switch the Google-login session to $context_id when needed.
public
static ensureActiveContext(mixed $context_id[, bool $recordAccess = false ]) : true|string
$recordAccess is for /courses/{id} navigation. It refreshes the course login_at when the stored time is older than five minutes.
Parameters
- $context_id : mixed
- $recordAccess : bool = false
Return values
true|string —true on success, error message otherwise
enter()
public
static enter(Application $app, Request $request, mixed $id) : mixed
Parameters
- $app : Application
- $request : Request
- $id : mixed
exitPlusLeftCourse()
Stop a Plus launch that opened a site tool.
public
static exitPlusLeftCourse() : mixed
The Tsugi router calls this before every Tool action. A route that is a closure has to call it itself. The page offers the launch course, Log out, and Close Tab. Close Tab is disabled while the browser tries to close the window. If the tab is still open after three seconds, that button is removed and the page says it could not close.
gateResponse()
Google site-login, or the Plus launch for this same course.
public
static gateResponse() : Response|null
Every /courses route uses this, including nested tools and /courses/{id}/image/{kind}, except a read-only lessons GET and a published page when this course allows anonymous lesson viewing. Course file URLs stay on this gate. An ordinary LMS launch already has its course and cannot switch. A Plus launch may open /courses/{id} when that id is the context it just launched, so each tab's address is the course. It cannot open a different id, the course list, or create.
Return values
Response|nullgetjson()
public
static getjson(Application $app) : mixed
Parameters
- $app : Application
image()
Serve a course hero or icon.
public
static image(Application $app, Request $request, mixed $id, mixed $kind) : mixed
Same Google gate as the rest of /courses (gateResponse). Membership is also required. Does not switch context. LMS LTI sessions do not use this URL; course nav and Settings Images are course-mounted.
Parameters
- $app : Application
- $request : Request
- $id : mixed
- $kind : mixed
index()
public
static index(Application $app, Request $request) : mixed
Parameters
- $app : Application
- $request : Request
innerRequest()
Build an inner request whose pathInfo is /{rest}.
public
static innerRequest(Request $request, mixed $rest) : mixed
PHP $_SERVER is unchanged, so toolHome() still sees the nested URL.
Parameters
- $request : Request
- $rest : mixed
isAnonymousLessonRest()
GET /courses/{id}/lessons, /content, or /outline, or one module under any of them.
public
static isAnonymousLessonRest(mixed $rest) : bool
Author, launch, and deeper paths stay on the membership gate.
Parameters
- $rest : mixed
Return values
boolisAnonymousPageRest()
A published-page GET: /courses/{id}/pages or /courses/{id}/pages/{key}.
public
static isAnonymousPageRest(mixed $rest) : bool
Add, edit, manage, history, and analytics stay on the membership gate.
Parameters
- $rest : mixed
Return values
boolisCourseMountedRequest()
True when REQUEST_URI is /courses/{id} or /courses/{id}/…
public
static isCourseMountedRequest() : mixed
This is the course vs site menu split. Do not use ReqScope::currentContextId().
isCourseRoute()
True when this request is /courses/{id}{route}... (not the unprefixed tool URL).
public
static isCourseRoute([string|null $route = null ]) : mixed
Nested course dispatch rewrites pathInfo to $route but leaves REQUEST_URI unchanged, so this is the reliable split between a global tool URL and a course-mounted one. Do not use ReqScope::currentContextId() here — a global visit can still have a course in session.
Uses static::ROUTE unless $route is passed. Controllers without ROUTE return false unless $route is given.
Parameters
- $route : string|null = null
-
Tool path including leading slash (e.g. '/settings')
isGoogleLoginSession()
True when this session is a Google site login (not an LMS LTI launch).
public
static isGoogleLoginSession() : mixed
joinToolHome()
Join a mounted tool home and a suffix without producing `//path`.
public
static joinToolHome(string $home, string $suffix) : string
Parameters
- $home : string
-
toolHome() result
- $suffix : string
-
id or extra path (leading slash optional)
Return values
stringlessonsUrl()
Absolute URL of /courses/{id}/lessons.
public
static lessonsUrl(mixed $context_id) : string
Parameters
- $context_id : mixed
Return values
stringmembershipHref()
Where a membership card opens. The Google site-login course opens the app home, not /courses/{id}.
public
static membershipHref(mixed $context_id, mixed $listHome, mixed $siteContextId, mixed $siteHomeUrl) : mixed
Parameters
- $context_id : mixed
- $listHome : mixed
- $siteContextId : mixed
- $siteHomeUrl : mixed
nested()
public
static nested(Application $app, Request $request, mixed $id, mixed $rest) : mixed
Parameters
- $app : Application
- $request : Request
- $id : mixed
- $rest : mixed
outboundContextTitle()
Course title for an outbound LTI launch.
public
static outboundContextTitle() : mixed
Precedence: $_SESSION['context_title'], then the LTI session context_title, then $CFG->context_title.
Sending the site default here used to overwrite lti_context.title via adjustData.
plusLeftCourseApplies()
True when this request is a Plus launch on a site URL.
public
static plusLeftCourseApplies() : mixed
/courses/{id}/… still belongs to the launch. The course id stays in the session. A site tool that needs a course does not use it.
releaseContextAfterDelete()
Drop a deleted course from the session and return to the site-login course when one remains.
public
static releaseContextAfterDelete(int $deleted_id) : void
Parameters
- $deleted_id : int
releaseUnmountedCourse()
A site URL is not the launch course. Drop the top-level course fields.
public
static releaseUnmountedCourse() : mixed
The LTI row stays, so /courses/{id} for that launch can match it again. Google site login keeps its own course. A Plus session keeps its course too; a site tool asks isPlusSession() and sends the launch back. A course-mounted URL is that course.
requestPath()
REQUEST_URI path with query stripped and a single leading slash.
public
static requestPath() : string
//courses is a protocol-relative URL (host "courses"). Apache/proxies
sometimes leave a doubled slash in REQUEST_URI; collapse it so tool
links stay /courses/123 instead of //courses/123.
Return values
stringrequireCsrf()
Redirect back to $redirect when the CSRF token is missing or invalid.
public
static requireCsrf(string $redirect) : RedirectResponse|null
Parameters
- $redirect : string
Return values
RedirectResponse|null —Null when the token is valid.
requireCsrfJson()
JSON 403 when the CSRF token is missing or invalid (no flash).
public
static requireCsrfJson([array<string|int, mixed>|null $payload = null ]) : JsonResponse|null
Parameters
- $payload : array<string|int, mixed>|null = null
Return values
JsonResponse|null —Null when the token is valid.
requireOutboundLti11LaunchSession()
Require LTI consumer session fields needed to sign an outbound LTI 1.1 launch.
public
static requireOutboundLti11LaunchSession(Application $app, mixed $redirect_path) : RedirectResponse|null
Parameters
- $app : Application
- $redirect_path : mixed
Return values
RedirectResponse|null —Null if session is sufficient; redirect with flash otherwise.
restoreSiteLoginContext()
On site URLs (buildmenu world), drop a leftover /courses/{id} sandbox and put the Google-login course back in the session.
public
static restoreSiteLoginContext() : mixed
Course-mounted URLs, the Settings cartridge uploader, and LMS LTI launches are left alone. Idempotent. Does not call touchVisited() — bouncing back to the Google home course on site URLs must not steal the flyout's recency list.
routes()
public
static routes(Application $app[, mixed $prefix = self::ROUTE ]) : mixed
Parameters
- $app : Application
- $prefix : mixed = self::ROUTE
sameOriginPost()
True when this request is a same-origin navigation (not a cross-site CSRF POST).
public
static sameOriginPost() : bool
Return values
boolsendLti11LaunchFromContent()
Sign a lesson launch from an lti_content row.
public
static sendLti11LaunchFromContent(Application $app, array<string, mixed> $row, string $launch_presentation_return_url, string $redirect_path_on_error[, string|null $grade_refresh_session_key = null ]) : RedirectResponse|string
Parameters
- $app : Application
- $row : array<string, mixed>
- $launch_presentation_return_url : string
- $redirect_path_on_error : string
- $grade_refresh_session_key : string|null = null
Return values
RedirectResponse|stringsendLti11LaunchFromLessonsItem()
Build and print the auto-submit HTML for an LTI 1.1 basic-lti-launch-request to a tool URL described by a lessons.json / lessons-items item (same shape as {@see \Tsugi\Services\Lessons\LessonsService::getLtiByRlid()}).
public
static sendLti11LaunchFromLessonsItem(Application $app, object $lti, string $launch_presentation_return_url, string $redirect_path_on_error[, string $fallback_resource_link_title = '' ][, string|null $grade_refresh_session_key = null ]) : RedirectResponse|string
Parameters
- $app : Application
- $lti : object
-
Must have resource_link_id; launch is required for LTI tools (discussions POST to {wwwroot}/tool/tdiscus)
- $launch_presentation_return_url : string
-
Return URL after the external tool
- $redirect_path_on_error : string
-
Session addSession path for flash+redirect on failure
- $fallback_resource_link_title : string = ''
-
Used when $lti->title is missing
- $grade_refresh_session_key : string|null = null
-
If non-null, GradeUtil::invalidateGradesCurrentUser() and set this session key (typically self::SESSION_LESSONS_GRADE_REFRESH_AFTER_LAUNCH)
Return values
RedirectResponse|string —Empty string after HTML is printed; RedirectResponse on session failure only (caller handles other errors)
showCoursesWidget()
Site top-menu waffle. Off unless $CFG->show_courses_widget is set.
public
static showCoursesWidget() : mixed
siteLoginContextId()
Google site-login context id, or 0.
public
static siteLoginContextId() : mixed
siteLoginRedirect()
Redirect the Google site-login course to the app home.
public
static siteLoginRedirect(mixed $context_id) : RedirectResponse|null
Parameters
- $context_id : mixed
Return values
RedirectResponse|nulltoolPathPrefix()
Path prefix for this request: '' or '/courses/{id}' (no trailing slash).
public
static toolPathPrefix() : mixed
Follows REQUEST_URI. Parent site menus should not call this.
wireLaunchConnection()
Point Context/Output at $TSUGI_LAUNCH and ensure it has a PDOX connection.
public
static wireLaunchConnection() : mixed
lms_lib.php may have created a dummy $LAUNCH without pdox.
withImageUrls()
Replace image byte metadata with versioned URLs. Does not touch BLOBs.
public
static withImageUrls(array<int, mixed> $rows) : array<int, array<string, mixed>>
Parameters
- $rows : array<int, mixed>
Return values
array<int, array<string, mixed>>assetUrl()
Alias for staticUrl() for backward compatibility
protected
assetUrl(mixed $filename[, mixed $controllerName = null ]) : mixed
Use staticUrl() instead
Parameters
- $filename : mixed
- $controllerName : mixed = null
controllerUrl()
Generate URL to another controller
protected
controllerUrl(string $controllerRoute[, string|null $currentRoute = null ]) : string
Parameters
- $controllerRoute : string
-
The route of the target controller (e.g., '/pages', '/announcements')
- $currentRoute : string|null = null
-
Optional current route (defaults to detecting from context)
Return values
string —Full URL to the controller
courseFileBaseUrl()
Current course base URL for Common Cartridge file-base rewriting.
protected
courseFileBaseUrl(string $route) : string
Example: https://host/py4e or https://host/courses/2
Parameters
- $route : string
-
The route constant for this tool (e.g. '/pages')
Return values
string —Course base with no trailing slash
courseRequiredHtml()
protected
courseRequiredHtml() : string
Return values
stringexitCourseRequired()
A site tool such as grades was opened with no course.
protected
exitCourseRequired() : mixed
Continue uses this tab's LTI return URL when one is stored, and the app home when it is not. A Plus launch never reaches this: the router stops it before the tool action.
externalLinkAttrs()
Get link attributes for external vs same-site URLs
protected
externalLinkAttrs(string $url[, string $linkLabel = 'Learn more' ]) : array<string|int, mixed>
Same-site links open in the current tab; external links get target="_blank" and rel="noopener noreferrer". Uses $CFG->apphome to determine same-site.
Parameters
- $url : string
-
The link URL
- $linkLabel : string = 'Learn more'
-
Optional label for aria-label (default: 'Learn more')
Return values
array<string|int, mixed> —['attrs' => string, 'aria_label' => string, 'external' => bool]
isAdmin()
Check if the current user is a site administrator
protected
isAdmin() : bool
Return values
bool —True if user is admin, false otherwise
isInstructor()
Check if the current logged-in user is an instructor/admin for the current context
protected
isInstructor() : bool
This method checks:
- If user is site admin (passphrase session)
- If user has instructor role or role_override in lti_membership table
- If user owns the context or its key
Reads context via ReqScope::currentContextId(); user id via ReqScope::loggedInUserId() (session or globals). Delegates to Membership::ensureInSession(), which caches a Membership instance in context-scoped session cache via Membership::ensureInSession() (single lti_membership SELECT when missing; ownership query only when role must be resolved).
Return values
bool —True if user is instructor/admin for the context, false otherwise
leavePageReturnScript()
Point Continue at this tab's launch return before footer scripts replace TSUGI_SESSION_DATA with the current page.
protected
static leavePageReturnScript(string $detail) : string
Same read and preference as Output::htmlError: error return, then return URL.
Parameters
- $detail : string
Return values
stringlmsAnalyticsKey()
Build a stable key for LMS analytics, distinct from LTI resource_link_id values.
protected
lmsAnalyticsKey([string|null $path = null ]) : string
Parameters
- $path : string|null = null
Return values
stringlmsAnalyticsPath()
Build a stable path identifier for LMS tools (no query/session params).
protected
lmsAnalyticsPath() : string
Examples:
- /lms/pages
- /lms/assignments
Return values
stringlmsEnsureAnalyticsLink()
Ensure there is an `lti_link` row for a local LMS page/tool and return link_id.
protected
lmsEnsureAnalyticsLink(int $context_id, string $link_key[, string|null $title = null ][, string|null $path = null ]) : int|false
We intentionally store LMS "tools" as synthetic lti_link records scoped to the
already-selected lti_context, so we can reuse the existing analytics tables
(lti_link_activity, lti_link_user_activity) without schema changes.
Parameters
- $context_id : int
- $link_key : string
- $title : string|null = null
- $path : string|null = null
Return values
int|falselmsRecordLaunchAnalytics()
Record LMS page/tool "launch" into Tsugi internal analytics, mirroring LTIX behavior.
protected
lmsRecordLaunchAnalytics(string $analytics_path[, string|null $title = null ]) : int|false
- Only records for learners (i.e., not instructors/admins)
- Stores data in lti_link_activity / lti_link_user_activity with event=0
Parameters
- $analytics_path : string
-
Required stable path for this tool (e.g., '/lms/pages')
- $title : string|null = null
-
Optional display title for this synthetic link
Return values
int|false —The link_id if successful, false otherwise
plusLeftCourseHtml()
protected
static plusLeftCourseHtml() : string
Return values
stringrenderLeavePage()
Error page with Close Tab and Continue.
protected
static renderLeavePage(array{title: string, paragraphs: array, home: string} $copy) : string
Continue starts at the app home. The page script points it at this tab's launch return when session storage has one.
Parameters
-
$copy
: array{title: string, paragraphs: array
, home: string}
Return values
stringrequireAuth()
Check authentication and context
protected
requireAuth() : mixed
Tags
requireGlobalRoute()
Bounce a course-mounted URL to a global (unprefixed) URL.
protected
requireGlobalRoute(string $globalUrl) : RedirectResponse|null
Parameters
- $globalUrl : string
-
Already session-bearing when the caller wants a session cookie
Return values
RedirectResponse|nullrequireInstructor()
Check if user is instructor/admin, redirect if not
protected
requireInstructor([string $redirectUrl = null ]) : bool
Parameters
- $redirectUrl : string = null
-
URL to redirect to if not authorized
Return values
bool —True if user is instructor/admin, false otherwise (and redirects)
showAnalytics()
Display analytics for an LMS tool
protected
showAnalytics(string $route[, string|null $title = null ]) : string
Automatically derives back_url and stable_path from the route.
Parameters
- $route : string
-
The route constant (e.g., '/pages', '/announcements')
- $title : string|null = null
-
Optional display title (defaults to route without leading slash, capitalized)
Return values
string —Empty string (outputs HTML directly)
staticUrl()
Generate URL for a controller-specific static file (JS, CSS, etc.)
protected
staticUrl(string $filename[, string|null $controllerName = null ]) : string
Static files are served from tsugi/lib/src/Controllers/static/{ControllerName}/ This method generates the proper URL for accessing these static files.
Parameters
- $filename : string
-
Static filename (e.g., 'tsugi-announce.js')
- $controllerName : string|null = null
-
Optional controller name (defaults to current controller)
Return values
string —Full URL to the static file
toolHome()
Get the base path for this tool (e.g., '/py4e/pages' or '/courses/2/pages')
protected
toolHome(string $route) : string
Looks at the current request URI and finds the tool's route within it, so nested mounts keep generating nested URLs.
Parameters
- $route : string
-
The route constant for this tool (e.g., '/pages', '/announcements')
Return values
string —The base path including the route (e.g., '/py4e/pages')
toolParent()
Get the parent path one level above the tool home
protected
toolParent([string $route = null ]) : string
This is useful for shared resources like static files that are mounted at a common path above individual controllers.
Parameters
- $route : string = null
-
The route constant for this tool (e.g., '/pages', '/announcements')
Return values
string —The parent path (e.g., '/py4e' if toolHome is '/py4e/pages')
viewDueDates()
Whether the current user may see due dates in this context (lti_membership.viewDueDates).
protected
viewDueDates() : bool
Loads Membership via ensureInSession(); for non-admins also calls isInstructor() so the same cached object is used for role checks in mixed call order.
Return values
boolanonymousContentRequest()
Lessons outline or a published page for an anonymous reader.
private
static anonymousContentRequest(Request $request, mixed $rest) : bool
Course files are not included. A file URL under /courses/{id}/files stays on the login gate.
Parameters
- $request : Request
- $rest : mixed
Return values
boolanonymousLessonsOpen()
This course's lti_context.anonymous_lessons is on, and it is a live manifest course.
private
static anonymousLessonsOpen(mixed $context_id) : bool
Parameters
- $context_id : mixed
Return values
boolclearActiveContext()
Forget the current course in this session.
private
static clearActiveContext() : void
courseSwitchErrorCopy()
private
static courseSwitchErrorCopy(string $message) : array{title: string, paragraphs: array, home: string}
Parameters
- $message : string
Return values
array{title: string, paragraphs: arraydeniedCourseHome()
Home after a course URL refuses the logged-in user.
private
static deniedCourseHome() : mixed
dispatchAnonymousLessons()
Render lessons, or a published page, for someone who is not in the course.
private
static dispatchAnonymousLessons(Application $app, Request $request, mixed $id, mixed $rest) : mixed
The session is restored afterward so this read does not switch their course or leave a membership behind.
Parameters
- $app : Application
- $request : Request
- $id : mixed
- $rest : mixed
establishReqScope()
User, course, and role for this request. The session course write stays.
private
static establishReqScope(int $context_id) : mixed
A failure here does not undo the session switch.
Parameters
- $context_id : int
filesForCreate()
FileBag turns empty inputs into null; Request::create() rejects null.
private
static filesForCreate(Request $request) : array<string, mixed>
Parameters
- $request : Request
Return values
array<string, mixed>flyoutMembershipSql()
Flyout memberships: never-visited rows use created_at so new enrollments still surface. Caller adds WHERE extras and LIMIT.
private
static flyoutMembershipSql(mixed $p[, mixed $extraWhere = '' ]) : mixed
Requires :SITE, the site-login course id (0 if there is none).
Parameters
- $p : mixed
- $extraWhere : mixed = ''
imageResponse()
JPEG bytes with a versioned ETag, or 404.
private
static imageResponse(array{bytes: string, mime: string, updated_at: ?string}|null $row, mixed $kind, mixed $context_id) : mixed
Parameters
- $row : array{bytes: string, mime: string, updated_at: ?string}|null
- $kind : mixed
- $context_id : mixed
isAnonymousLessonTail()
private
static isAnonymousLessonTail(string $rest, string $head) : bool
Parameters
- $rest : string
- $head : string
Return values
boollaunchErrorRedirect()
Redirect to the platform error return, or null when this session has none.
private
static launchErrorRedirect(string $message) : RedirectResponse|null
Parameters
- $message : string
Return values
RedirectResponse|nulllaunchErrorReturnUrl()
Platform URL for a Plus or LTI launch, or null.
private
static launchErrorReturnUrl() : string|null
Same preference as an aborted launch: launch_presentation_error_return_url, then launch_presentation_return_url. Only the stored launch is used. The current request body is not a launch.
Return values
string|nulllistedCourseSql()
Courses with no manifest stay off Courses and the flyout.
private
static listedCourseSql() : mixed
The site-wide course for $CFG->context_title is the exception (:SITE).
loginRedirectForCourse()
Send a logged-out /courses/{id} visitor to login, and bring them back here.
private
static loginRedirectForCourse() : mixed
A Plus or LTI launch with a platform return URL goes back to that platform instead. The error return is preferred, then the launch return.
noteCourseLogin()
Last access for this course. A visit inside five minutes leaves the stamp.
private
static noteCourseLogin(int $context_id, array<string, mixed> $context_row) : mixed
Parameters
- $context_id : int
- $context_row : array<string, mixed>
plusOwnsCourseUrl()
True when this request is /courses/{id} for the Plus launch in the session.
private
static plusOwnsCourseUrl() : mixed
The URL id must be the context this /plus launch opened. The resource link id is not the check. Another tool's session does not carry the flag.
renderCourseSwitchError()
private
static renderCourseSwitchError(array{title: string, paragraphs: array, home: string} $copy) : mixed
Parameters
-
$copy
: array{title: string, paragraphs: array
, home: string}
sanitizeFilesForCreate()
private
static sanitizeFilesForCreate(array<string|int, mixed> $files) : array<string|int, mixed>
Parameters
- $files : array<string|int, mixed>
Return values
array<string|int, mixed>switchFailedResponse()
private
static switchFailedResponse(mixed $message) : mixed
Parameters
- $message : mixed
viewerAlreadyInCourse()
Logged-in member (or site admin) who can already open this course.
private
static viewerAlreadyInCourse(mixed $context_id) : bool
Parameters
- $context_id : mixed