File:  [LON-CAPA] / loncom / lti / ltiauth.pm
Revision 1.43: download - view: text, annotated - select for diffs
Fri Aug 18 22:14:34 2023 UTC (8 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, version_2_11_4_msu, HEAD
- Fix typo.

# The LearningOnline Network
# Basic LTI Authentication Module
#
# $Id: ltiauth.pm,v 1.43 2023/08/18 22:14:34 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#

package Apache::ltiauth;

use strict;
use LONCAPA qw(:DEFAULT :match);
use Encode;
use Apache::Constants qw(:common :http :remotehost);
use Apache::lonlocal;
use Apache::lonnet;
use Apache::loncommon;
use Apache::lonacc;
use Apache::lonrequestcourse;
use LONCAPA::ltiutils;

sub handler {
    my $r = shift;
    my $requri = $r->uri;
    my $hostname = $r->hostname;
#
# Check for existing session, and temporarily delete any form items
# in %env, if session exists
#
    my %savedform;
    my $handle = &Apache::lonnet::check_for_valid_session($r);
    if ($handle ne '') {
        foreach my $key (sort(keys(%env))) {
            if ($key =~ /^form\.(.+)$/) {
                $savedform{$1} = $env{$key};
                delete($env{$key});
            }
        }
    }
#
# Retrieve data POSTed by LTI launch
#
    &Apache::lonacc::get_posted_cgi($r);
    my $params = {};
    foreach my $key (sort(keys(%env))) {
        if ($key =~ /^form\.(.+)$/) {
            $params->{$1} = &Encode::decode('UTF-8',$env{$key});
        }
    }
#
# Check for existing session, and restore temporarily
# deleted form items to %env, if session exists.
#
    if ($handle ne '') {
        if (keys(%savedform)) {
            foreach my $key (sort(keys(%savedform))) {
                $env{'form.'.$key} = $savedform{$key};
            }
        }
    }

    unless (keys(%{$params})) {
        &invalid_request($r,'No parameters included in launch request');
        return OK;
    }

    unless ($params->{'oauth_consumer_key'} &&
            $params->{'oauth_nonce'} &&
            $params->{'oauth_timestamp'} &&
            $params->{'oauth_version'} &&
            $params->{'oauth_signature'} &&
            $params->{'oauth_signature_method'}) {
        &invalid_request($r,'One or more required parameters missing from launch request');
        return OK;
    }

#
# Retrieve "internet domains" for all this institution's LON-CAPA
# nodes.
#
    my @intdoms;
    my $lonhost = $r->dir_config('lonHostID');
    my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
    if (ref($internet_names) eq 'ARRAY') {
        @intdoms = @{$internet_names};
    }
#
# Determine course's domain in LON-CAPA
# for basic launch using key and secret managed
# in LON-CAPA course (i.e., uri begins /adm/launch)
#

   my ($cdom,$cnum);

# Note: "internet domain" for course's domain must be one of the
# internet domains for the institution's LON-CAPA servers.
#
    if ($requri =~ m{^/adm/launch(|/.*)$}) {
        my $tail = $1;
        if ($tail =~ m{^/tiny/$match_domain/\w+$}) {
            my ($urlcdom,$urlcnum) = &course_from_tinyurl($tail);
            if (($urlcdom ne '') && ($urlcnum ne '')) {
                $cdom = $urlcdom;
                $cnum = $urlcnum;
                my $primary_id = &Apache::lonnet::domain($cdom,'primary');
                if ($primary_id ne '') {
                    my $intdom = &Apache::lonnet::internet_dom($primary_id);
                    if (($intdom ne '') && (grep(/^\Q$intdom\E$/,@intdoms))) {
#
# Verify the signed request using the secret for LTI link
# protectors for which the key in the POSTed data matches
# keys in the course configuration.
#
# Request is invalid if the signed request could not be verified
# for the key and secret from LON-CAPA course configuration for
# LTI link protectors or from LON-CAPA configuration for the
# course's domain if there are LTI Providers which may be used.
#
# Determine if nonce in POSTed data has expired.
# If unexpired, confirm it has not already been used.
#
# Retrieve information for LTI link protectors in course
# where url was /adm/launch/tiny/$cdom/$uniqueid
#

                        my ($itemid,$ltitype,%crslti,%lti_in_use,$ltiuser);
                        $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,$cnum,'linkprot');
                        if ($itemid) {
                            %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
                        }
                        if (($itemid) && (ref($crslti{$itemid}) eq 'HASH')) {
                            $ltitype = 'c';
                            if (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
                                                                $crslti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
                                %lti_in_use = %{$crslti{$itemid}};
                            } else {
                                &invalid_request($r,'Time limit exceeded for launch request credentials');
                                return OK;
                            }
                        } else {
                            $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,'','linkprot');
                            my %lti;
                            if ($itemid) {
                                %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
                            }
                            if (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {
                                $ltitype = 'd';
                                if (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
                                                                        $lti{$itemid}{'lifetime'},$cdom,
                                                                        $r->dir_config('lonLTIDir'))) {
                                    %lti_in_use = %{$lti{$itemid}};
                                } else {
                                    &invalid_request($r,'Time limit exceeded for launch request credentials');
                                    return OK;
                                }
                            }
                        }
                        my $exiturl;
                        if (($itemid) && ($lti_in_use{'returnurl'} ne '')) {
                            if (exists($params->{$lti_in_use{'returnurl'}})) {
                                $exiturl = $params->{$lti_in_use{'returnurl'}};
                            } elsif (exists($params->{'custom_'.$lti_in_use{'returnurl'}})) {
                                $exiturl = $params->{'custom_'.$lti_in_use{'returnurl'}};
                            }
                        }
                        my ($pbid,$pburl);
                        if ($params->{'lis_result_sourcedid'}) {
                            $pbid = $params->{'lis_result_sourcedid'};
                        }
                        if ($params->{'lis_outcome_service_url'}) {
                            $pburl = $params->{'lis_outcome_service_url'};
                        }
                        if (($itemid) && ($lti_in_use{'requser'})) {
                            my %courseinfo = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                            my $ltiauth;
                            if (exists($courseinfo{'internal.ltiauth'})) {
                                $ltiauth = $courseinfo{'internal.ltiauth'};
                            } else {
                                my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
                                $ltiauth = $domdefs{'crsltiauth'};
                            }
                            if ($ltiauth) {
                                my $possuname;
                                my $mapuser = $lti_in_use{'mapuser'};
                                if ($mapuser eq 'sourcedid') {
                                    if ($params->{'lis_person_sourcedid'} =~ /^$match_username$/) {
                                        $possuname = $params->{'lis_person_sourcedid'};
                                    }
                                } elsif ($mapuser eq 'email') {
                                    if ($params->{'lis_person_contact_email_primary'} =~ /^$match_username$/) {
                                        $possuname = $params->{'lis_person_contact_email_primary'};
                                    }
                                } elsif (exists($params->{$mapuser})) {
                                    if ($params->{$mapuser} =~ /^$match_username$/) {
                                        $possuname = $params->{$mapuser};
                                    }
                                }
                                if ($possuname ne '') {
                                    my $uhome = &Apache::lonnet::homeserver($possuname,$cdom);
                                    unless ($uhome eq 'no_host') {
                                        my $uname = $possuname;
                                        my ($is_student,$is_nonstudent);
                                        my %course_roles =
                                            &Apache::lonnet::get_my_roles($uname,$cdom,'userroles',['active'],
                                                                          ['cc','co','in','ta','ep','ad','st','cr'],
                                                                          [$cdom]);
                                        foreach my $key (keys(%course_roles)) {
                                            my ($trest,$tdomain,$trole,$sec) = split(/:/,$key);
                                            if (($trest eq $cnum) && ($tdomain eq $cdom)) {
                                                if ($trole eq 'st') {
                                                    $is_student = 1;
                                                } else {
                                                    $is_nonstudent = 1;
                                                    last;
                                                }
                                            }
                                        }
                                        if (($is_student) && (!$is_nonstudent)) {
                                            unless (&Apache::lonnet::is_advanced_user($uname,$cdom)) {
                                                foreach my $key (%{$params}) {
                                                    delete($env{'form.'.$key});
                                                }
                                                &linkprot_session($r,$uname,$cnum,$cdom,$uhome,$itemid,$ltitype,
                                                                  $tail,$lonhost,$exiturl,$pbid,$pburl);
                                                return OK;
                                            }
                                        }
                                        $ltiuser = $uname.':'.$cdom;
                                    }
                                }
                                if ($lti_in_use{'notstudent'} eq 'reject') {
                                    &invalid_request($r,'Information for valid user missing from launch request');
                                    return OK;
                                }
                            }
                        }
                        if ($itemid) {
                            foreach my $key (%{$params}) {
                                delete($env{'form.'.$key});
                            }
                            my %info = (
                                          'linkprot' => $itemid.$ltitype.':'.$tail,
                                       );
                            if ($ltiuser ne '') {
                                $info{'linkprotuser'} = $ltiuser;
                            }
                            if ($exiturl ne '') {
                                $info{'linkprotexit'} = $exiturl; 
                            }
                            if ($pbid ne '') {
                                $info{'linkprotpbid'} = $pbid;
                            }
                            if ($pburl ne '') {
                                $info{'linkprotpburl'} = $pburl;
                            }
                            my $ltoken = &Apache::lonnet::tmpput(\%info,$lonhost,'link');
                            if (($ltoken eq 'con_lost') || ($ltoken eq 'refused') || ($ltoken =~ /^error:/) ||
                                ($ltoken eq 'unknown_cmd') || ($ltoken eq 'no_such_host') ||
                                ($ltoken eq '')) {
                                &invalid_request($r,'Failed to store information from launch request');
                            } else {
                                $r->internal_redirect($tail.'?ltoken='.$ltoken);
                                $r->set_handlers('PerlHandler'=> undef);
                            }
                        } else {
                            &invalid_request($r,'Launch request could not be validated');
                        }
                    } else {
                        &invalid_request($r,'Launch unavailable on this LON-CAPA server');
                    }
                } else {
                    &invalid_request($r,'Launch unavailable for this domain');
                }
            } else {
                &invalid_request($r,'Invalid launch URL');
            }
        } else {
            &invalid_request($r,'Invalid launch URL');
        }
        return OK;
    }

    my ($udom,$uname,$uhome,$symb,$mapurl);

#
# For user who launched LTI in Consumer, determine user's domain in 
# LON-CAPA.
#
# Order is:
#
# (a) from custom_userdomain item in POSTed data
# (b) from lis_person_sourcedid in POSTed data
# (c) from default "log-in" domain for node
#     (can support multidomain servers, where specific domain is 
#      first part of hostname).
#
# Note: "internet domain" for user's domain must be one of the
# "internet domain(s)" for the institution's LON-CAPA servers.
#
    if (exists($params->{'custom_userdomain'})) {
        if ($params->{'custom_userdomain'} =~ /^$match_domain$/) {
            my $uprimary_id = &Apache::lonnet::domain($params->{'custom_userdomain'},'primary');
            if ($uprimary_id ne '') {
                my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) {
                    $udom = $params->{'custom_userdomain'};
                }
            }
        }
    }
    my $defdom = &Apache::lonnet::default_login_domain();
    my ($domain,$possuname,$possudom,$possmapuser);
    if ($env{'form.lis_person_sourcedid'} =~ /^($match_username)\:($match_domain)$/) {
        ($possuname,$possudom) = ($1,$2);
        if ($udom eq '') {
            my $uintdom = &Apache::lonnet::domain($possudom,'primary');
            if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) {
                $udom = $possudom;
                $possmapuser = 'lis_person_sourcedid';
            } else {
                $udom = $defdom;
            }
        } elsif ($udom eq $possudom) {
            $possmapuser = 'lis_person_sourcedid';
        }
    }
    unless ($possuname) {
        if ($env{'form.lis_person_sourcedid'} =~ /^$match_username$/) {
            $possuname = $env{'form.lis_person_sourcedid'};
            $possmapuser = 'lis_person_sourcedid';
        } elsif ($env{'form.lis_person_contact_email_primary'} =~ /^$match_username$/) {
            $possuname = $env{'form.lis_person_contact_email_primary'};
            $possmapuser = 'lis_person_contact_email_primary';
        }
        unless ($udom) {
            $udom = $defdom;
        }
    }

#
# Determine course's domain in LON-CAPA
#
# Order is:
#
# (a) from custom_coursedomain item in POSTed data
# (b) from tail of requested URL (after /adm/lti/) if it has format of a symb  
# (c) from tail of requested URL (after /adm/lti) if it has format of a map 
# (d) from tail of requested URL (after /adm/lti) if it has format /domain/courseID
# (e) from tail of requested URL (after /adm/lti) if it has format /tiny/domain/\w+
#     i.e., a shortened URL (see bug #6400).
# (f) same as user's domain 
#
# Request invalid if custom_coursedomain is defined and is inconsistent with
# domain contained in requested URL.
#
# Note: "internet domain" for course's domain must be one of the
# internet domains for the institution's LON-CAPA servers.
#

    if (exists($params->{'custom_coursedomain'})) {
        if ($params->{'custom_coursedomain'} =~ /^$match_domain$/) {
            my $cprimary_id = &Apache::lonnet::domain($params->{'custom_coursedomain'},'primary');
            if ($cprimary_id ne '') {
                my $cintdom = &Apache::lonnet::internet_dom($cprimary_id);
                if (($cintdom ne '') && (grep(/^\Q$cintdom\E$/,@intdoms))) {
                    $cdom = $params->{'custom_coursedomain'};
                }
            }
        }
    }

    my ($tail) = ($requri =~ m{^/adm/lti(|/.*)$});
    my $urlcnum;
    if ($tail ne '') {
        my $urlcdom;
        if ($tail =~ m{^/uploaded/($match_domain)/($match_courseid)/(?:default|supplemental)(?:|_\d+)\.(?:sequence|page)(|___\d+___.+)$}) {
            ($urlcdom,$urlcnum,my $rest) = ($1,$2,$3);
            if (($cdom ne '') && ($cdom ne $urlcdom)) {
                &invalid_request($r,'Incorrect domain in requested URL');
                return OK;
            }
            if ($rest eq '') {
                $mapurl = $tail;
            } else {
                $symb = $tail;
                $symb =~ s{^/}{};
            }
        } elsif ($tail =~ m{^/res/(?:$match_domain)/(?:$match_username)/.+\.(?:sequence|page)(|___\d+___.+)$}) {
            if ($1 eq '') {
                $mapurl = $tail;
            } else {
                $symb = $tail;
                $symb =~ s{^/res/}{};
            }
        } elsif ($tail =~ m{^/($match_domain)/($match_courseid)$}) {
            ($urlcdom,$urlcnum) = ($1,$2);
            if (($cdom ne '') && ($cdom ne $urlcdom)) {
                &invalid_request($r,'Incorrect domain in requested URL');
                return OK;
            }
        } elsif ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
            ($urlcdom,$urlcnum) = &course_from_tinyurl($tail);
            if (($urlcdom eq '') || ($urlcnum eq '')) {
                &invalid_request($r,'Invalid URL shortcut');
                return OK;
            }
        }
        if (($cdom eq '') && ($urlcdom ne '')) { 
            my $cprimary_id = &Apache::lonnet::domain($urlcdom,'primary');
            if ($cprimary_id ne '') {
                my $cintdom = &Apache::lonnet::internet_dom($cprimary_id);
                if (($cintdom ne '') && (grep(/^\Q$cintdom\E$/,@intdoms))) {
                    $cdom = $urlcdom;
                }
            } else {
                $urlcnum = '';
            }
        }
    }
    if ($cdom eq '') {
        if ($udom ne '') {
            $cdom = $udom;
        } else {
            $cdom = $defdom;
        }
    }

#
# Retrieve information for LTI Consumers in course's domain
# defined in domain configuration for LTI.
#
# Verify the signed request using the secret for those
# Consumers for which the key in the POSTed data matches
# keys in the course configuration or the domain configuration
# for LTI.
#

    my %lti;
    my $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,'','provider');
    if ($itemid) {
        %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
    }

#
# Request is invalid if the signed request could not be verified
# for the Consumer key and Consumer secret from the domain
# configuration in LON-CAPA for that LTI Consumer.
#
    unless (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {
        &invalid_request($r,'Launch request could not be validated');
        return OK;
    }

#
# Determine if nonce in POSTed data has expired.
# If unexpired, confirm it has not already been used.
#
    unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
                                            $lti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
        &invalid_request($r,'Time limit exceeded for launch request credentials');
        return OK;
    }

#
# Determine if a username is required from the domain
# configuration for the specific LTI Consumer
#

    if (!$lti{$itemid}{'requser'}) {
        if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
            my $ltitype = 'd';
            foreach my $key (%{$params}) {
                delete($env{'form.'.$key});
            }
            my $ltoken = &Apache::lonnet::tmpput({'linkprot' => $itemid.$ltitype.':'.$tail},
                                                   $lonhost);
            if ($ltoken) {
                $r->internal_redirect($tail.'?ltoken='.$ltoken);
                $r->set_handlers('PerlHandler'=> undef);
            } else {
                &invalid_request($r,'Failed to store information from launch request');
            }
        } else {
            &invalid_request($r,'Launch URL invalid for matched launch credentials');
        }
        return OK;
    }

#
# Determine if source of username matches requirement from the 
# domain configuration for the specific LTI Consumer.
# 

    if ($lti{$itemid}{'mapuser'} eq $possmapuser) {
        $uname = $possuname;
    } elsif ($lti{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
        if ($params->{'lis_person_sourcedid'} =~ /^$match_username$/) {
            $uname = $possuname;
        }
    } elsif ($lti{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
        if ($params->{'lis_person_contact_email_primary'} =~ /^$match_username$/) {
            $uname = $params->{'lis_person_contact_email_primary'};
        }
    } elsif (exists($params->{$lti{$itemid}{'mapuser'}})) {
        if ($params->{$lti{$itemid}{'mapuser'}} =~ /^$match_username$/) {
            $uname = $params->{$lti{$itemid}{'mapuser'}};
        }
    }

#
# Determine the courseID of the LON-CAPA course to which the
# launch of LON-CAPA should provide access.
#
# Order is:
#
# (a) from course mapping (if the link between Consumer "course" and 
# Provider "course" has been established previously).
# (b) from tail of requested URL (after /adm/lti/) if it has format of a symb
# (c) from tail of requested URL (after /adm/lti) if it has format of a map
# (d) from tail of requested URL (after /adm/lti) if it has format /domain/courseID
# (e) from tail of requested URL (after /adm/lti) if it has format /tiny/domain/\w+
#     i.e., a shortened URL (see bug #6400).
#
# If Consumer course included in POSTed data points as a target course which
# has a format which matches a LON-CAPA courseID, but the course does not
# exist, the request is invalid.
# 

    my ($sourcecrs,%consumers);
    if ($lti{$itemid}{'mapcrs'} eq 'course_offering_sourcedid') {
        $sourcecrs = $params->{'course_offering_sourcedid'};
    } elsif ($lti{$itemid}{'mapcrs'} eq 'context_id') {
        $sourcecrs = $params->{'context_id'};
    } elsif ($lti{$itemid}{'mapcrs'} ne '') {
        $sourcecrs = $params->{$lti{$itemid}{'mapcrs'}};
    }

    my $posscnum;
    if ($sourcecrs ne '') {
        %consumers = &Apache::lonnet::get_dom('lticonsumers',[$sourcecrs],$cdom);
        if (exists($consumers{$sourcecrs})) {
            if ($consumers{$sourcecrs} =~ /^\Q$itemid:\E($match_courseid)$/) {
                my $storedcnum = $1;
                my $crshome = &Apache::lonnet::homeserver($storedcnum,$cdom);
                if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
                    &invalid_request($r,'Invalid courseID included in launch data');
                    return OK;
                } else {
                    $posscnum = $storedcnum;
                }
            }
        }
    }

    if ($urlcnum ne '') {
        if ($posscnum ne '') {
            if ($posscnum ne $urlcnum) {
                &invalid_request($r,'Course ID included in launch data incompatible with URL');
                return OK;
            } else {
                $cnum = $posscnum;
            }
        } else {
            my $crshome = &Apache::lonnet::homeserver($urlcnum,$cdom);
            if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
                &invalid_request($r,'Valid course ID could not be extracted from requested URL');
                return OK;
            } else {
                $cnum = $urlcnum;
            }
        }
    } elsif ($posscnum ne '') {
        $cnum = $posscnum;
    }

#
# Get LON-CAPA role(s) to use from role-mapping of Consumer roles
# defined in domain configuration for the appropriate LTI
# Consumer.
#
# If multiple LON-CAPA roles are indicated for the current user,
# ordering (from first to last) is: cc/co, in, ta, ep, st.
#

    my (@ltiroles,@lcroles);
    my @lcroleorder = ('cc','in','ta','ep','st');
    my ($lcrolesref,$ltirolesref) = 
        &LONCAPA::ltiutils::get_lc_roles($params->{'roles'},
                                         \@lcroleorder,
                                         $lti{$itemid}{maproles});
    if (ref($lcrolesref) eq 'ARRAY') {
        @lcroles = @{$lcrolesref};
    }
    if (ref($ltirolesref) eq 'ARRAY') {
        @ltiroles = @{$ltirolesref};
    }

#
# If no LON-CAPA username  -- is user allowed to create one?
#

    my $selfcreate;
    if (($uname ne '') && ($udom ne '')) {
        $uhome = &Apache::lonnet::homeserver($uname,$udom);
        if ($uhome =~ /(con_lost|no_host|no_such_host)/) {
            &Apache::lonnet::logthis(" LTI authorized unknown user $uname:$udom ");
            if (ref($lti{$itemid}{'makeuser'}) eq 'ARRAY') {
                if (@{$lti{$itemid}{'makeuser'}} > 0) {
                    foreach my $ltirole (@ltiroles) {
                        if (grep(/^\Q$ltirole\E$/,@{$lti{$itemid}{'makeuser'}})) {
                            $selfcreate = 1;
                            last;
                        }
                    }
                }
            }
            if ($selfcreate) {
                my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
                my $domdesc = &Apache::lonnet::domain($udom,'description');
                my %data = (
                    'permanentemail' => $env{'form.lis_person_contact_email_primary'},
                    'firstname'      => $env{'form.lis_person_name_given'},
                    'lastname'       => $env{'form.lis_person_name_family'},
                    'fullname'       => $env{'form.lis_person_name_full'},
                );
                my $result =
                    &LONCAPA::ltiutils::create_user($lti{$itemid},$uname,$udom,
                                                    $domdesc,\%data,\%alerts,\%rulematch,
                                                    \%inst_results,\%curr_rules,%got_rules);
                if ($result eq 'notallowed') {
                    &invalid_request($r,'Account creation not permitted for this user');
                } elsif ($result eq 'ok') {
                    if (($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'mapcrs'}) &&
                        ($lti{$itemid}{'makecrs'})) {
                        unless (&Apache::lonnet::usertools_access($uname,$udom,'lti','reload','requestcourses')) {
                            &Apache::lonnet::put('environment',{ 'requestcourses.lti' => 'autolimit=', },$udom,$uname);
                        }
                    }
                } else {
                    &invalid_request($r,'An error occurred during account creation');
                    return OK;
                }
            } else {
                &invalid_request($r,'Account creation not permitted');
                return OK;
            }
        }
    } else {
        &invalid_request($r,'Could not determine username and/or domain for user');
        return OK;
    }

#
# If no LON-CAPA course available, check if domain's configuration
# for the specific LTI Consumer allows a new course to be created 
# (requires role in Consumer to be: Instructor and Instructor to map to CC)
#

    my $reqcrs;
    if ($cnum eq '') {
        if ($lti{$itemid}{'crsinc'}) {
            if ((@ltiroles) && ($lti{$itemid}{'mapcrs'}) &&
                ($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'makecrs'})) {
                my (%can_request,%request_domains);
                &Apache::lonnet::check_can_request($cdom,\%can_request,\%request_domains,$uname,$udom);
                if ($can_request{'lti'}) {
                    $reqcrs = 1;
                    &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,
                                 $symb,$cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,
                                 $reqcrs,$sourcecrs);
                } else {
                    &invalid_request($r,'No LON-CAPA course available, and creation is not permitted for this user');
                }
            } else {
                &invalid_request($r,'No LON-CAPA course available, and creation is not permitted');
            }
        } else {
            &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,
                         $symb,$cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,
                         $reqcrs,$sourcecrs);
        }
        return OK;
    }

#
# If LON-CAPA course is a Community, and LON-CAPA role
# indicated is cc, change role indicated to co.
#

    my %crsenv;
    if ($lcroles[0] eq 'cc') {
        if (($cdom ne '') && ($cnum ne '')) {
            %crsenv = &Apache::lonnet::coursedescription($cdom.'_'.$cnum,{ 'one_time' => 1,});
            if ($crsenv{'type'} eq 'Community') {
                $lcroles[0] = 'co';
            }
        }
    }

#
# Determine if user has a LON-CAPA role in the mapped LON-CAPA course.
# If multiple LON-CAPA roles are available for the user's assigned LTI roles,
# choose the first available LON-CAPA role in the order: cc/co, in, ta, ep, st
#

    my ($role,$usec,$withsec);
    unless ((($lcroles[0] eq 'cc') || ($lcroles[0] eq 'co')) && (@lcroles == 1)) {
        if ($lti{$itemid}{'section'} ne '') {
            if ($lti{$itemid}{'section'} eq 'course_section_sourcedid') {
                if ($env{'form.course_section_sourcedid'} !~ /\W/) {
                    $usec = $env{'form.course_section_sourcedid'};
                }
            } elsif ($env{'form.'.$lti{$itemid}{'section'}} !~ /\W/) {
                $usec = $env{'form.'.$lti{$itemid}{'section'}};
            }
        }
        if ($usec ne '') {
            $withsec = 1;
        }
    }

    if (@lcroles) {
        my %crsroles = &Apache::lonnet::get_my_roles($uname,$udom,'userroles',undef,\@lcroles,
                                                     [$cdom],$withsec);
        foreach my $reqrole (@lcroles) {
            if ($withsec) {
                my $incsec;
                if (($reqrole eq 'cc') || ($reqrole eq 'co')) {
                    $incsec = '';
                } else {
                    $incsec = $usec;
                }
                if (exists($crsroles{$cnum.':'.$cdom.':'.$reqrole.':'.$incsec})) {
                    $role = $reqrole.'./'.$cdom.'/'.$cnum;
                    if ($incsec ne '') {
                        $role .= '/'.$usec;
                    }
                    last;
                }
            } else {
                if (exists($crsroles{$cnum.':'.$cdom.':'.$reqrole})) {
                    $role = $reqrole.'./'.$cdom.'/'.$cnum;
                    last;
                }
            }
        }
    }

#
# Determine if user can selfenroll
#

    my ($reqrole,$selfenrollrole);
    if ($role eq '') {
        if ((@ltiroles) && (ref($lti{$itemid}{'selfenroll'}) eq 'ARRAY')) {
            foreach my $ltirole (@ltiroles) {
                if (grep(/^\Q$ltirole\E$/,@{$lti{$itemid}{'selfenroll'}})) {
                    if (ref($lti{$itemid}{maproles}) eq 'HASH') {
                        $reqrole = $lti{$itemid}{maproles}{$ltirole};
                        last;
                    }
                }
            }
        }
        if ($reqrole eq '') {
            &invalid_request($r,'No matching role available in LON-CAPA course, and not permitted to self-enroll');
            return OK;
        } else {
            unless (%crsenv) {
                %crsenv = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
            }
            my $default_enrollment_start_date = $crsenv{'default_enrollment_start_date'};
            my $default_enrollment_end_date   = $crsenv{'default_enrollment_end_date'};
            my $now = time;
            if ($default_enrollment_end_date && $default_enrollment_end_date <= $now) {
                &invalid_request($r,'No active role available in LON-CAPA course, and past end date for self-enrollment');
                return OK;
            } elsif ($default_enrollment_start_date && $default_enrollment_start_date >$now) {
                &invalid_request($r,'No active role available in LON-CAPA course, and brefor start date for self-enrollment');
                return OK;
            } else {
                $selfenrollrole = $reqrole.'./'.$cdom.'/'.$cnum;
                if (($withsec) && ($reqrole ne 'cc') && ($reqrole ne 'co')) {
                    if ($usec ne '') {
                        $selfenrollrole .= '/'.$usec;
                    }
                }
            }
        }
    }

#
# Retrieve course type of LON-CAPA course to check if mapping from a Consumer
# course identifier permitted for this type of course (one of: official,
# unofficial, community, textbook, placement or lti.
#

    unless (%crsenv) {
        %crsenv = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
    }
    my $crstype = lc($crsenv{'type'});
    if ($crstype eq '') {
        $crstype = 'course';
    }
    if ($crstype eq 'course') {
        if ($crsenv{'internal.coursecode'}) {
            $crstype = 'official';
        } elsif ($crsenv{'internal.textbook'}) {
            $crstype = 'textbook';
        } elsif ($crsenv{'internal.lti'}) {
            $crstype = 'lti';
        } else {
            $crstype = 'unofficial';
        }
    }

#
# Store consumer-to-LON-CAPA course mapping if permitted
#

    if (($lti{$itemid}{'storecrs'}) && ($sourcecrs ne '') && 
        ($consumers{$sourcecrs} eq '') && ($cnum ne '')) {
        if (ref($lti{$itemid}{'mapcrstype'}) eq 'ARRAY') {
            if (grep(/^$crstype$/,@{$lti{$itemid}{'mapcrstype'}})) {
                &Apache::lonnet::put_dom('lticonsumers',{ $sourcecrs => $itemid.':'.$cnum },$cdom);
            }
        }
    }

#
# Start user session
#

    &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,$role,$mapurl,$tail,$symb,
                 $cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,undef,$sourcecrs,
                 $selfenrollrole);
    return OK;
}

sub get_lti_itemid {
    my ($requri,$hostname,$params,$cdom,$cnum,$context) = @_;
    return unless (ref($params) eq 'HASH');
    my $protocol = 'http';
    if ($ENV{'SERVER_PORT'} == 443) {
        $protocol = 'https';
    }
    my $url = $protocol.'://'.$hostname.$requri;
    my $method = $env{'request.method'};
    if ($cnum ne '') {
        return &Apache::lonnet::courselti_itemid($cnum,$cdom,$url,$method,$params,$context);
    } else {
        return &Apache::lonnet::domainlti_itemid($cdom,$url,$method,$params,$context);
    }
}

sub lti_enroll {
    my ($uname,$udom,$selfenrollrole) = @_;
    my $enrollresult;
    my ($role,$cdom,$cnum,$sec) =
           ($selfenrollrole =~ m{^(\w+)\./($match_domain)/($match_courseid)(?:|/(\w*))$});
    if (($cnum ne '') && ($cdom ne '')) {
        my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
        if ($chome ne 'no_host') {
            my %coursehash = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
            my $start = $coursehash{'default_enrollment_start_date'};
            my $end = $coursehash{'default_enrollment_end_date'};
            $enrollresult = &LONCAPA::ltiutils::enrolluser($udom,$uname,$role,$cdom,$cnum,$sec,
                                                           $start,$end,1);
        }
    }
    return $enrollresult;
}

sub lti_reqcrs {
    my ($r,$cdom,$form,$uname,$udom) = @_;
    my (%can_request,%request_domains);
    &Apache::lonnet::check_can_request($cdom,\%can_request,\%request_domains,$uname,$udom);
    if ($can_request{'lti'}) {
        my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$cdom);
        my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
        &Apache::lonrequestcourse::print_textbook_form($r,$cdom,[$cdom],\%domdefs,
                                                       $domconfig{'requestcourses'},
                                                       \%can_request,'lti',$form);
    } else {
        $r->print(
              &Apache::loncommon::start_page('Invalid LTI call',undef,{'only_body' => 1}).
              &mt('Invalid LTI call').
              &Apache::loncommon::end_page()
        );
    }
}

sub lti_session {
    my ($r,$itemid,$uname,$udom,$uhome,$lonhost,$role,$mapurl,$tail,$symb,$cdom,$cnum,
        $params,$ltiroles,$ltihash,$lcroles,$reqcrs,$sourcecrs,$selfenrollrole) = @_;
    return unless ((ref($params) eq 'HASH') && (ref($ltiroles) eq 'ARRAY') &&
                   (ref($ltihash) eq 'HASH') && (ref($lcroles) eq 'ARRAY'));
#
# Check if user should be hosted here or switched to another server.
#
    $r->user($uname);
    if ($cnum) {
        if ($role) {
            &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, role: $role, course: $cdom\_$cnum");
        } elsif ($selfenrollrole =~ m{^(\w+)\./$cdom/$cnum}) {
            &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, desired role: $1 course: $cdom\_$cnum");
        }
    } else {
        &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, course dom: $cdom");
    }
    my ($is_balancer,$otherserver,$hosthere) = &check_balancer($r,$uname,$udom);
    my $protocol = 'http';
    if ($ENV{'SERVER_PORT'} == 443) {
        $protocol = 'https';
    }
    if (($is_balancer) && (!$hosthere)) {
        # login but immediately go to switch server.
        &Apache::lonauth::success($r,$uname,$udom,$uhome,'noredirect');
        if (($ltihash->{'callback'}) && ($params->{$ltihash->{'callback'}})) {
            &LONCAPA::ltiutils::setup_logout_callback($cdom,$cnum,'',$itemid,$ltihash->{'cipher'},
                                                      $uname,$udom,$otherserver,
                                                      $params->{$ltihash->{'callback'}},
                                                      $r->dir_config('ltiIDsDir'),
                                                      $protocol,$r->hostname);
        }
        if ($symb) {
            $env{'form.symb'} = $symb;
            $env{'request.lti.uri'} = $tail;
        } else {
            if ($mapurl) {
                $env{'form.origurl'} = $mapurl;
                $env{'request.lti.uri'} = $mapurl;
            } elsif ($tail =~ m{^\Q/tiny/$cdom/\E\w+$}) {
                $env{'form.origurl'} = $tail;
                $env{'request.lti.uri'} = $tail;
            } elsif ($tail eq "/$cdom/$cnum") {
                $env{'form.origurl'} = '/adm/navmaps';
                $env{'request.lti.uri'} = $tail;
            } else {
                unless ($tail eq '/adm/roles') {
                    if ($cnum) {
                        $env{'form.origurl'} = '/adm/navmaps';
                    }
                }
            }
        }
        if ($role) {
            $env{'form.role'} = $role;
        }
        if (($lcroles->[0] eq 'cc') && ($reqcrs)) {
            $env{'request.lti.reqcrs'} = 1;
            $env{'request.lti.reqrole'} = 'cc';
            $env{'request.lti.sourcecrs'} = $sourcecrs;
        }
        if ($selfenrollrole) {
            $env{'request.lti.selfenrollrole'} = $selfenrollrole;
            $env{'request.lti.sourcecrs'} = $sourcecrs;
        }
        if ($ltihash->{'passback'}) {
            if ($params->{'lis_result_sourcedid'}) {
                $env{'request.lti.passbackid'} = $params->{'lis_result_sourcedid'};
            }
            if ($params->{'lis_outcome_service_url'}) {
                $env{'request.lti.passbackurl'} = $params->{'lis_outcome_service_url'};
            }
        }
        if (($ltihash->{'roster'}) && (grep(/^Instructor$/,@{$ltiroles}))) {
            if ($params->{'ext_ims_lis_memberships_id'}) {
                $env{'request.lti.rosterid'} = $params->{'ext_ims_lis_memberships_id'};
            }
            if ($params->{'ext_ims_lis_memberships_url'}) {
                $env{'request.lti.rosterurl'} = $params->{'ext_ims_lis_memberships_url'};
            }
        }
        $env{'request.lti.login'} = $itemid;
        if ($params->{'launch_presentation_document_target'}) {
            $env{'request.lti.target'} = $params->{'launch_presentation_document_target'};
        }
        foreach my $key (keys(%{$params})) {
            delete($env{'form.'.$key});
        }
        my $redirecturl = '/adm/switchserver';
        if ($otherserver ne '') {
            $redirecturl .= '?otherserver='.$otherserver;
        }
        $r->internal_redirect($redirecturl);
        $r->set_handlers('PerlHandler'=> undef);
    } else {
        # need to login them in, so generate the data migrate expects to do login
        foreach my $key (keys(%{$params})) {
            delete($env{'form.'.$key});
        }
        if (($ltihash->{'callback'}) && ($params->{$ltihash->{'callback'}})) {
            &LONCAPA::ltiutils::setup_logout_callback($cdom,$cnum,'',$itemid,$ltihash->{'cipher'},
                                                      $uname,$udom,$lonhost,
                                                      $params->{$ltihash->{'callback'}},
                                                      $r->dir_config('ltiIDsDir'),
                                                      $protocol,$r->hostname);
        }
        my $ip = &Apache::lonnet::get_requestor_ip($r,REMOTE_NOLOOKUP);
        my %info=('ip'        => $ip,
                  'domain'    => $udom,
                  'username'  => $uname,
                  'server'    => $lonhost,
                  'lti.login' => $itemid,
                  'lti.uri'   => $tail,
                 );
        if ($role) {
            $info{'role'} = $role;
        }
        if ($symb) {
            $info{'symb'} = $symb;
        }
        if (($lcroles->[0] eq 'cc') && ($reqcrs)) {
            $info{'lti.reqcrs'} = 1;
            $info{'lti.reqrole'} = 'cc';
            $info{'lti.sourcecrs'} = $sourcecrs;
        }
        if ($selfenrollrole) {
            $info{'lti.selfenrollrole'} = $selfenrollrole;
        }
        if ($ltihash->{'passback'}) {
            if ($params->{'lis_result_sourcedid'}) {
                $info{'lti.passbackid'} = $params->{'lis_result_sourcedid'}
            }
            if ($params->{'lis_outcome_service_url'}) {
                $info{'lti.passbackurl'} = $params->{'lis_outcome_service_url'}
            }
        }
        if (($ltihash->{'roster'}) && (grep(/^Instructor$/,@{$ltiroles}))) {
            if ($params->{'ext_ims_lis_memberships_id'}) {
                $info{'lti.rosterid'} = $params->{'ext_ims_lis_memberships_id'};
            }
            if ($params->{'ext_ims_lis_memberships_url'}) {
                $info{'lti.rosterurl'} = $params->{'ext_ims_lis_memberships_url'};
            }
        }
        if ($params->{'launch_presentation_document_target'}) {
            $info{'lti.target'} = $params->{'launch_presentation_document_target'};
        }

        unless ($info{'symb'}) {
            if ($mapurl) {
                $info{'origurl'} = $mapurl;
            } elsif ($tail =~ m{^\Q/tiny/$cdom/\E\w+$}) {
                $info{'origurl'} = $tail;
            } else {
                unless ($tail eq '/adm/roles') {
                    if ($cnum) {
                        $info{'origurl'} = '/adm/navmaps';
                    }
                }
            }
        }
        if (($is_balancer) && ($hosthere)) {
            $info{'noloadbalance'} = $hosthere;
        }
        my $token = &Apache::lonnet::tmpput(\%info,$lonhost);
        $env{'form.token'} = $token;
        $r->internal_redirect('/adm/migrateuser');
        $r->set_handlers('PerlHandler'=> undef);
    }
    return;
}

sub linkprot_session {
    my ($r,$uname,$cnum,$cdom,$uhome,$itemid,$ltitype,$dest,$lonhost,$exiturl,$pbid,$pburl) = @_;
    $r->user($uname);
    if ($ltitype eq 'c') {
        &Apache::lonnet::logthis("Course Link Protector ($itemid) authorized student: $uname:$cdom, course: $cdom\_$cnum");
    } elsif ($ltitype eq 'd') {
        &Apache::lonnet::logthis("Domain LTI for link protection ($itemid) authorized student: $uname:$cdom, course: $cdom\_$cnum");
    }
    my ($is_balancer,$otherserver,$hosthere) = &check_balancer($r,$uname,$cdom);
    if (($is_balancer) && (!$hosthere)) {
        # login but immediately go to switch server
        &Apache::lonauth::success($r,$uname,$cdom,$uhome,'noredirect');
        $env{'form.origurl'} = $dest;
        $env{'request.linkprot'} = $itemid.$ltitype.':'.$dest;
        $env{'request.linkprotuser'} = $uname.':'.$cdom;
        $env{'request.deeplink.login'} = $dest;
        if ($exiturl ne '') {
            $env{'request.linkprotexit'} = $exiturl;
        }
        if ($pbid ne '') {
            $env{'request.linkprotpbid'} = $pbid;
        }
        if ($pburl ne '') {
            $env{'request.linkprotpburl'} = $pburl;
        }
        my $redirecturl = '/adm/switchserver';
        if ($otherserver ne '') {
            $redirecturl .= '?otherserver='.$otherserver;
        }
        $r->internal_redirect($redirecturl);
        $r->set_handlers('PerlHandler'=> undef);
    } else {
        # need to login them in, so generate the data migrate expects to do login
        my $ip = &Apache::lonnet::get_requestor_ip($r,REMOTE_NOLOOKUP);
        my %info=('ip'             => $ip,
                  'domain'         => $cdom,
                  'username'       => $uname,
                  'server'         => $lonhost,
                  'linkprot'       => $itemid.$ltitype.':'.$dest,
                  'linkprotuser'   => $uname.':'.$cdom,
                  'home'           => $uhome,
                  'origurl'        => $dest,
                  'deeplink.login' => $dest,
                 );
        if ($pbid ne '') {
            $info{'linkprotpbid'} = $pbid;
        }
        if ($pburl ne '') {
            $info{'linkprotpburl'} = $pburl;
        }
        if ($exiturl ne '') {
            $info{'linkprotexit'} = $exiturl; 
        }
        my $token = &Apache::lonnet::tmpput(\%info,$lonhost);
        $env{'form.token'} = $token;
        $r->internal_redirect('/adm/migrateuser');
        $r->set_handlers('PerlHandler'=> undef);
    }
    return;
}

sub check_balancer {
    my ($r,$uname,$udom) = @_;
    my ($is_balancer,$otherserver,$hosthere);
    ($is_balancer,$otherserver) =
        &Apache::lonnet::check_loadbalancing($uname,$udom,'login');
    if ($is_balancer) {
        # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
        my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
        if (($found_server) && ($balancer_cookie =~ /^\Q$udom\E_\Q$uname\E_/)) {
            $otherserver = $found_server;
        }
        if ($otherserver eq '') {
            my $lowest_load;
            ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($udom);
            if ($lowest_load > 100) {
                $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$udom);
            }
        }
        if ($otherserver ne '') {
            my @hosts = &Apache::lonnet::current_machine_ids();
            if (grep(/^\Q$otherserver\E$/,@hosts)) {
                $hosthere = $otherserver;
            }
        }
    }
    return ($is_balancer,$otherserver,$hosthere);
}

sub invalid_request {
    my ($r,$msg) = @_;
    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;
    if ($r->header_only) {
        return;
    }
    &Apache::lonlocal::get_language_handle($r);
    $r->print(
        &Apache::loncommon::start_page('Invalid LTI call','',{ 'only_body' => 1,}).
        '<h3>'.&mt('Invalid LTI launch request').'</h3>'.
        '<p class="LC_warning">'.
        &mt('Launch of LON-CAPA is unavailable from the "external tool" link you had followed in another web application.').
        ' '.&mt('Launch failed for the following reason:').
        '</p>'.
        '<p class="LC_error">'.$msg.'</p>'.
        &Apache::loncommon::end_page());
    return;
}

sub course_from_tinyurl {
    my ($tail) = @_;
    my ($urlcdom,$urlcnum);
    if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
        ($urlcdom,my $key) = ($1,$2);
        my $tinyurl;
        my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$urlcdom."\0".$key);
        if (defined($cached)) {
            $tinyurl = $result;
        } else {
            my $configuname = &Apache::lonnet::get_domainconfiguser($urlcdom);
            my %currtiny = &Apache::lonnet::get('tiny',[$key],$urlcdom,$configuname);
            if ($currtiny{$key} ne '') {
                $tinyurl = $currtiny{$key};
                &Apache::lonnet::do_cache_new('tiny',$urlcdom."\0".$key,$currtiny{$key},600);
            }
        }
        if ($tinyurl ne '') {
            $urlcnum = (split(/\&/,$tinyurl))[0];
        }
    }
    return ($urlcdom,$urlcnum);
}

1;

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>