File:  [LON-CAPA] / loncom / lti / ltiauth.pm
Revision 1.31: download - view: text, annotated - select for diffs
Wed Feb 2 00:31:16 2022 UTC (2 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Typo

    1: # The LearningOnline Network
    2: # Basic LTI Authentication Module
    3: #
    4: # $Id: ltiauth.pm,v 1.31 2022/02/02 00:31:16 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::ltiauth;
   30: 
   31: use strict;
   32: use LONCAPA qw(:DEFAULT :match);
   33: use Apache::Constants qw(:common :http);
   34: use Apache::lonlocal;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonacc;
   38: use Apache::lonrequestcourse;
   39: use LONCAPA::ltiutils;
   40: 
   41: sub handler {
   42:     my $r = shift;
   43:     my $requri = $r->uri;
   44:     my $hostname = $r->hostname;
   45: #
   46: # Check for existing session, and temporarily delete any form items
   47: # in %env, if session exists
   48: #
   49:     my %savedform;
   50:     my $handle = &Apache::lonnet::check_for_valid_session($r);
   51:     if ($handle ne '') {
   52:         foreach my $key (sort(keys(%env))) {
   53:             if ($key =~ /^form\.(.+)$/) {
   54:                 $savedform{$1} = $env{$key};
   55:                 delete($env{$key});
   56:             }
   57:         }
   58:     }
   59: #
   60: # Retrieve data POSTed by LTI launch
   61: #
   62:     &Apache::lonacc::get_posted_cgi($r);
   63:     my $params = {};
   64:     foreach my $key (sort(keys(%env))) {
   65:         if ($key =~ /^form\.(.+)$/) {
   66:             $params->{$1} = $env{$key};
   67:         }
   68:     }
   69: #
   70: # Check for existing session, and restore temporarily
   71: # deleted form items to %env, if session exists.
   72: #
   73:     if ($handle ne '') {
   74:         if (keys(%savedform)) {
   75:             foreach my $key (sort(keys(%savedform))) {
   76:                 $env{'form.'.$key} = $savedform{$key};
   77:             }
   78:         }
   79:     }
   80: 
   81:     unless (keys(%{$params})) {
   82:         &invalid_request($r,1);
   83:         return OK;
   84:     }
   85: 
   86:     unless ($params->{'oauth_consumer_key'} &&
   87:             $params->{'oauth_nonce'} &&
   88:             $params->{'oauth_timestamp'} &&
   89:             $params->{'oauth_version'} &&
   90:             $params->{'oauth_signature'} &&
   91:             $params->{'oauth_signature_method'}) {
   92:         &invalid_request($r,2);
   93:         return OK;
   94:     }
   95: 
   96: #
   97: # Retrieve "internet domains" for all this institution's LON-CAPA
   98: # nodes.
   99: #
  100:     my @intdoms;
  101:     my $lonhost = $r->dir_config('lonHostID');
  102:     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
  103:     if (ref($internet_names) eq 'ARRAY') {
  104:         @intdoms = @{$internet_names};
  105:     }
  106: #
  107: # Determine course's domain in LON-CAPA
  108: # for basic launch using key and secret managed
  109: # in LON-CAPA course (i.e., uri begins /adm/launch)
  110: #
  111: 
  112:    my ($cdom,$cnum);
  113: 
  114: # Note: "internet domain" for course's domain must be one of the
  115: # internet domains for the institution's LON-CAPA servers.
  116: #
  117:     if ($requri =~ m{^/adm/launch(|/.*)$}) {
  118:         my $tail = $1;
  119:         if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
  120:             my ($urlcdom,$urlcnum) = &course_from_tinyurl($tail);
  121:             if (($urlcdom ne '') && ($urlcnum ne '')) {
  122:                 $cdom = $urlcdom;
  123:                 $cnum = $urlcnum;
  124:                 my $primary_id = &Apache::lonnet::domain($cdom,'primary');
  125:                 if ($primary_id ne '') {
  126:                     my $intdom = &Apache::lonnet::internet_dom($primary_id);
  127:                     if (($intdom ne '') && (grep(/^\Q$intdom\E$/,@intdoms))) {
  128: #
  129: # Verify the signed request using the secret for LTI link
  130: # protectors for which the key in the POSTed data matches
  131: # keys in the course configuration.
  132: #
  133: # Request is invalid if the signed request could not be verified
  134: # for the key and secret from LON-CAPA course configuration for
  135: # LTI link protectors or from LON-CAPA configuration for the
  136: # course's domain if there are LTI Providers which may be used.
  137: #
  138: # Determine if nonce in POSTed data has expired.
  139: # If unexpired, confirm it has not already been used.
  140: #
  141: # Retrieve information for LTI link protectors in course
  142: # where url was /adm/launch/tiny/$cdom/$uniqueid
  143: #
  144: 
  145:                         my ($itemid,$ltitype,%crslti);
  146:                         $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,$cnum,'deeplink');
  147:                         if ($itemid) {
  148:                             %crslti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
  149:                         }
  150:                         if (($itemid) && (ref($crslti{$itemid}) eq 'HASH')) {
  151:                             $ltitype = 'c';
  152:                             unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
  153:                                                                     $crslti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
  154:                                 &invalid_request($r,3);
  155:                                 return OK;
  156:                             }
  157:                         } else {
  158:                             my %lti;
  159:                             $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom,'','deeplink');
  160:                             if ($itemid) {
  161:                                 %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
  162:                             }
  163:                             if (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {
  164:                                 $ltitype = 'd';
  165:                                 unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
  166:                                                                         $lti{$itemid}{'lifetime'},$cdom,
  167:                                                                         $r->dir_config('lonLTIDir'))) {
  168:                                     &invalid_request($r,4);
  169:                                     return OK;
  170:                                 }
  171:                             }
  172:                         }
  173:                         if ($itemid) {
  174:                             foreach my $key (%{$params}) {
  175:                                 delete($env{'form.'.$key});
  176:                             }
  177:                             my $ltoken = &Apache::lonnet::tmpput({'linkprot' => $itemid.$ltitype.':'.$tail},
  178:                                                                  $lonhost,'link');
  179:                             if ($ltoken) {
  180:                                 $r->internal_redirect($tail.'?ltoken='.$ltoken);
  181:                                 $r->set_handlers('PerlHandler'=> undef);
  182:                             } else {
  183:                                 &invalid_request($r,5);
  184:                             }
  185:                         } else {
  186:                             &invalid_request($r,6);
  187:                         }
  188:                     } else {
  189:                         &invalid_request($r,7);
  190:                     }
  191:                 } else {
  192:                     &invalid_request($r,8);
  193:                 }
  194:             } else {
  195:                 &invalid_request($r,9);
  196:             }
  197:         } else {
  198:             &invalid_request($r,10);
  199:         }
  200:         return OK;
  201:     }
  202: 
  203:     my ($udom,$uname,$uhome,$symb,$mapurl);
  204: 
  205: #
  206: # For user who launched LTI in Consumer, determine user's domain in 
  207: # LON-CAPA.
  208: #
  209: # Order is:
  210: #
  211: # (a) from custom_userdomain item in POSTed data
  212: # (b) from lis_person_sourcedid in POSTed data
  213: # (c) from default "log-in" domain for node
  214: #     (can support multidomain servers, where specific domain is 
  215: #      first part of hostname).
  216: #
  217: # Note: "internet domain" for user's domain must be one of the
  218: # "internet domain(s)" for the institution's LON-CAPA servers.
  219: #
  220:     if (exists($params->{'custom_userdomain'})) {
  221:         if ($params->{'custom_userdomain'} =~ /^$match_domain$/) {
  222:             my $uprimary_id = &Apache::lonnet::domain($params->{'custom_userdomain'},'primary');
  223:             if ($uprimary_id ne '') {
  224:                 my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
  225:                 if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) {
  226:                     $udom = $params->{'custom_userdomain'};
  227:                 }
  228:             }
  229:         }
  230:     }
  231:     my $defdom = &Apache::lonnet::default_login_domain();
  232:     my ($domain,$possuname,$possudom,$possmapuser);
  233:     if ($env{'form.lis_person_sourcedid'} =~ /^($match_username)\:($match_domain)$/) {
  234:         ($possuname,$possudom) = ($1,$2);
  235:         if ($udom eq '') {
  236:             my $uintdom = &Apache::lonnet::domain($possudom,'primary');
  237:             if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) {
  238:                 $udom = $possudom;
  239:                 $possmapuser = 'lis_person_sourcedid';
  240:             } else {
  241:                 $udom = $defdom;
  242:             }
  243:         } elsif ($udom eq $possudom) {
  244:             $possmapuser = 'lis_person_sourcedid';
  245:         }
  246:     }
  247:     unless ($possuname) {
  248:         if ($env{'form.lis_person_sourcedid'} =~ /^$match_username$/) {
  249:             $possuname = $env{'form.lis_person_sourcedid'};
  250:             $possmapuser = 'lis_person_sourcedid';
  251:         } elsif ($env{'form.lis_person_contact_email_primary'} =~ /^$match_username$/) {
  252:             $possuname = $env{'form.lis_person_contact_email_primary'};
  253:             $possmapuser = 'lis_person_contact_email_primary';
  254:         }
  255:         unless ($udom) {
  256:             $udom = $defdom;
  257:         }
  258:     }
  259: 
  260: #
  261: # Determine course's domain in LON-CAPA
  262: #
  263: # Order is:
  264: #
  265: # (a) from custom_coursedomain item in POSTed data
  266: # (b) from tail of requested URL (after /adm/lti/) if it has format of a symb  
  267: # (c) from tail of requested URL (after /adm/lti) if it has format of a map 
  268: # (d) from tail of requested URL (after /adm/lti) if it has format /domain/courseID
  269: # (e) from tail of requested URL (after /adm/lti) if it has format /tiny/domain/\w+
  270: #     i.e., a shortened URL (see bug #6400).
  271: # (f) same as user's domain 
  272: #
  273: # Request invalid if custom_coursedomain is defined and is inconsistent with
  274: # domain contained in requested URL.
  275: #
  276: # Note: "internet domain" for course's domain must be one of the
  277: # internet domains for the institution's LON-CAPA servers.
  278: #
  279: 
  280:     if (exists($params->{'custom_coursedomain'})) {
  281:         if ($params->{'custom_coursedomain'} =~ /^$match_domain$/) {
  282:             my $cprimary_id = &Apache::lonnet::domain($params->{'custom_coursedomain'},'primary');
  283:             if ($cprimary_id ne '') {
  284:                 my $cintdom = &Apache::lonnet::internet_dom($cprimary_id);
  285:                 if (($cintdom ne '') && (grep(/^\Q$cintdom\E$/,@intdoms))) {
  286:                     $cdom = $params->{'custom_coursedomain'};
  287:                 }
  288:             }
  289:         }
  290:     }
  291: 
  292:     my ($tail) = ($requri =~ m{^/adm/lti(|/.*)$});
  293:     my $urlcnum;
  294:     if ($tail ne '') {
  295:         my $urlcdom;
  296:         if ($tail =~ m{^/uploaded/($match_domain)/($match_courseid)/(?:default|supplemental)(?:|_\d+)\.(?:sequence|page)(|___\d+___.+)$}) {
  297:             ($urlcdom,$urlcnum,my $rest) = ($1,$2,$3);
  298:             if (($cdom ne '') && ($cdom ne $urlcdom)) {
  299:                 &invalid_request($r,11);
  300:                 return OK;
  301:             }
  302:             if ($rest eq '') {
  303:                 $mapurl = $tail;
  304:             } else {
  305:                 $symb = $tail;
  306:                 $symb =~ s{^/}{};
  307:             }
  308:         } elsif ($tail =~ m{^/res/(?:$match_domain)/(?:$match_username)/.+\.(?:sequence|page)(|___\d+___.+)$}) {
  309:             if ($1 eq '') {
  310:                 $mapurl = $tail;
  311:             } else {
  312:                 $symb = $tail;
  313:                 $symb =~ s{^/res/}{};
  314:             }
  315:         } elsif ($tail =~ m{^/($match_domain)/($match_courseid)$}) {
  316:             ($urlcdom,$urlcnum) = ($1,$2);
  317:             if (($cdom ne '') && ($cdom ne $urlcdom)) {
  318:                 &invalid_request($r,12);
  319:                 return OK;
  320:             }
  321:         } elsif ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
  322:             ($urlcdom,$urlcnum) = &course_from_tinyurl($tail);
  323:             if (($urlcdom eq '') || ($urlcnum eq '')) {
  324:                 &invalid_request($r,13);
  325:                 return OK;
  326:             }
  327:         }
  328:         if (($cdom eq '') && ($urlcdom ne '')) { 
  329:             my $cprimary_id = &Apache::lonnet::domain($urlcdom,'primary');
  330:             if ($cprimary_id ne '') {
  331:                 my $cintdom = &Apache::lonnet::internet_dom($cprimary_id);
  332:                 if (($cintdom ne '') && (grep(/^\Q$cintdom\E$/,@intdoms))) {
  333:                     $cdom = $urlcdom;
  334:                 }
  335:             } else {
  336:                 $urlcnum = '';
  337:             }
  338:         }
  339:     }
  340:     if ($cdom eq '') {
  341:         if ($udom ne '') {
  342:             $cdom = $udom;
  343:         } else {
  344:             $cdom = $defdom;
  345:         }
  346:     }
  347: 
  348: #
  349: # Retrieve information for LTI Consumers in course's domain
  350: # defined in domain configuration for LTI.
  351: #
  352: # Verify the signed request using the secret for those
  353: # Consumers for which the key in the POSTed data matches
  354: # keys in the course configuration or the domain configuration
  355: # for LTI.
  356: #
  357: 
  358:     my %lti;
  359:     my $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom);
  360:     if ($itemid) {
  361:         %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
  362:     }
  363: 
  364: #
  365: # Request is invalid if the signed request could not be verified
  366: # for the Consumer key and Consumer secret from the domain
  367: # configuration in LON-CAPA for that LTI Consumer.
  368: #
  369:     unless (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {
  370:         &invalid_request($r,14);
  371:         return OK;
  372:     }
  373: 
  374: #
  375: # Determine if nonce in POSTed data has expired.
  376: # If unexpired, confirm it has not already been used.
  377: #
  378:     unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
  379:                                             $lti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
  380:         &invalid_request($r,15);
  381:         return OK;
  382:     }
  383: 
  384: #
  385: # Determine if a username is required from the domain
  386: # configuration for the specific LTI Consumer
  387: #
  388: 
  389:     if (!$lti{$itemid}{'requser'}) {
  390:         if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
  391:             my $ltitype = 'd';
  392:             foreach my $key (%{$params}) {
  393:                 delete($env{'form.'.$key});
  394:             }
  395:             my $ltoken = &Apache::lonnet::tmpput({'linkprot' => $itemid.$ltitype.':'.$tail},
  396:                                                    $lonhost);
  397:             if ($ltoken) {
  398:                 $r->internal_redirect($tail.'?ltoken='.$ltoken);
  399:                 $r->set_handlers('PerlHandler'=> undef);
  400:             } else {
  401:                 &invalid_request($r,16);
  402:             }
  403:         } else {
  404:             &invalid_request($r,17);
  405:         }
  406:         return OK;
  407:     }
  408: 
  409: #
  410: # Determine if source of username matches requirement from the 
  411: # domain configuration for the specific LTI Consumer.
  412: # 
  413: 
  414:     if ($lti{$itemid}{'mapuser'} eq $possmapuser) {
  415:         $uname = $possuname;
  416:     } elsif ($lti{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
  417:         if ($params->{'lis_person_sourcedid'} =~ /^$match_username$/) {
  418:             $uname = $possuname;
  419:         }
  420:     } elsif ($lti{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
  421:         if ($params->{'lis_person_contact_email_primary'} =~ /^$match_username$/) {
  422:             $uname = $params->{'lis_person_contact_email_primary'};
  423:         }
  424:     } elsif (exists($params->{$lti{$itemid}{'mapuser'}})) {
  425:         if ($params->{$lti{$itemid}{'mapuser'}} =~ /^$match_username$/) {
  426:             $uname = $params->{$lti{$itemid}{'mapuser'}};
  427:         }
  428:     }
  429: 
  430: #
  431: # Determine the courseID of the LON-CAPA course to which the
  432: # launch of LON-CAPA should provide access.
  433: #
  434: # Order is:
  435: #
  436: # (a) from course mapping (if the link between Consumer "course" and 
  437: # Provider "course" has been established previously).
  438: # (b) from tail of requested URL (after /adm/lti/) if it has format of a symb
  439: # (c) from tail of requested URL (after /adm/lti) if it has format of a map
  440: # (d) from tail of requested URL (after /adm/lti) if it has format /domain/courseID
  441: # (e) from tail of requested URL (after /adm/lti) if it has format /tiny/domain/\w+
  442: #     i.e., a shortened URL (see bug #6400).
  443: #
  444: # If Consumer course included in POSTed data points as a target course which
  445: # has a format which matches a LON-CAPA courseID, but the course does not
  446: # exist, the request is invalid.
  447: # 
  448: 
  449:     my ($sourcecrs,%consumers);
  450:     if ($lti{$itemid}{'mapcrs'} eq 'course_offering_sourcedid') {
  451:         $sourcecrs = $params->{'course_offering_sourcedid'};
  452:     } elsif ($lti{$itemid}{'mapcrs'} eq 'context_id') {
  453:         $sourcecrs = $params->{'context_id'};
  454:     } elsif ($lti{$itemid}{'mapcrs'} ne '') {
  455:         $sourcecrs = $params->{$lti{$itemid}{'mapcrs'}};
  456:     }
  457: 
  458:     my $posscnum;
  459:     if ($sourcecrs ne '') {
  460:         %consumers = &Apache::lonnet::get_dom('lticonsumers',[$sourcecrs],$cdom);
  461:         if (exists($consumers{$sourcecrs})) {
  462:             if ($consumers{$sourcecrs} =~ /^\Q$itemid:\E($match_courseid)$/) {
  463:                 my $storedcnum = $1;
  464:                 my $crshome = &Apache::lonnet::homeserver($storedcnum,$cdom);
  465:                 if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
  466:                     &invalid_request($r,18);
  467:                     return OK;
  468:                 } else {
  469:                     $posscnum = $storedcnum;
  470:                 }
  471:             }
  472:         }
  473:     }
  474: 
  475:     if ($urlcnum ne '') {
  476:         if ($posscnum ne '') {
  477:             if ($posscnum ne $urlcnum) {
  478:                 &invalid_request($r,19);
  479:                 return OK;
  480:             } else {
  481:                 $cnum = $posscnum;
  482:             }
  483:         } else {
  484:             my $crshome = &Apache::lonnet::homeserver($urlcnum,$cdom);
  485:             if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
  486:                 &invalid_request($r,20);
  487:                 return OK;
  488:             } else {
  489:                 $cnum = $urlcnum;
  490:             }
  491:         }
  492:     } elsif ($posscnum ne '') {
  493:         $cnum = $posscnum;
  494:     }
  495: 
  496: #
  497: # Get LON-CAPA role(s) to use from role-mapping of Consumer roles
  498: # defined in domain configuration for the appropriate LTI
  499: # Consumer.
  500: #
  501: # If multiple LON-CAPA roles are indicated for the current user,
  502: # ordering (from first to last) is: cc/co, in, ta, ep, st.
  503: #
  504: 
  505:     my (@ltiroles,@lcroles);
  506:     my @lcroleorder = ('cc','in','ta','ep','st');
  507:     my ($lcrolesref,$ltirolesref) = 
  508:         &LONCAPA::ltiutils::get_lc_roles($params->{'roles'},
  509:                                          \@lcroleorder,
  510:                                          $lti{$itemid}{maproles});
  511:     if (ref($lcrolesref) eq 'ARRAY') {
  512:         @lcroles = @{$lcrolesref};
  513:     }
  514:     if (ref($ltirolesref) eq 'ARRAY') {
  515:         @ltiroles = @{$ltirolesref};
  516:     }
  517: 
  518: #
  519: # If no LON-CAPA username  -- is user allowed to create one?
  520: #
  521: 
  522:     my $selfcreate;
  523:     if (($uname ne '') && ($udom ne '')) {
  524:         $uhome = &Apache::lonnet::homeserver($uname,$udom);
  525:         if ($uhome =~ /(con_lost|no_host|no_such_host)/) {
  526:             &Apache::lonnet::logthis(" LTI authorized unknown user $uname:$udom ");
  527:             if (ref($lti{$itemid}{'makeuser'}) eq 'ARRAY') {
  528:                 if (@{$lti{$itemid}{'makeuser'}} > 0) {
  529:                     foreach my $ltirole (@ltiroles) {
  530:                         if (grep(/^\Q$ltirole\E$/,@{$lti{$itemid}{'makeuser'}})) {
  531:                             $selfcreate = 1;
  532:                             last;
  533:                         }
  534:                     }
  535:                 }
  536:             }
  537:             if ($selfcreate) {
  538:                 my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
  539:                 my $domdesc = &Apache::lonnet::domain($udom,'description');
  540:                 my %data = (
  541:                     'permanentemail' => $env{'form.lis_person_contact_email_primary'},
  542:                     'firstname'      => $env{'form.lis_person_name_given'},
  543:                     'lastname'       => $env{'form.lis_person_name_family'},
  544:                     'fullname'       => $env{'form.lis_person_name_full'},
  545:                 );
  546:                 my $result =
  547:                     &LONCAPA::ltiutils::create_user($lti{$itemid},$uname,$udom,
  548:                                                     $domdesc,\%data,\%alerts,\%rulematch,
  549:                                                     \%inst_results,\%curr_rules,%got_rules);
  550:                 if ($result eq 'notallowed') {
  551:                     &invalid_request($r,21);
  552:                 } elsif ($result eq 'ok') {
  553:                     if (($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'mapcrs'}) &&
  554:                         ($lti{$itemid}{'makecrs'})) {
  555:                         unless (&Apache::lonnet::usertools_access($uname,$udom,'lti','reload','requestcourses')) {
  556:                             &Apache::lonnet::put('environment',{ 'requestcourses.lti' => 'autolimit=', },$udom,$uname);
  557:                         }
  558:                     }
  559:                 } else {
  560:                     &invalid_request($r,22);
  561:                     return OK;
  562:                 }
  563:             } else {
  564:                 &invalid_request($r,23);
  565:                 return OK;
  566:             }
  567:         }
  568:     } else {
  569:         &invalid_request($r,24);
  570:         return OK;
  571:     }
  572: 
  573: #
  574: # If no LON-CAPA course available, check if domain's configuration
  575: # for the specific LTI Consumer allows a new course to be created 
  576: # (requires role in Consumer to be: Instructor and Instructor to map to CC)
  577: #
  578: 
  579:     my $reqcrs;
  580:     if ($cnum eq '') {
  581:         if ($lti{$itemid}{'crsinc'}) {
  582:             if ((@ltiroles) && ($lti{$itemid}{'mapcrs'}) &&
  583:                 ($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'makecrs'})) {
  584:                 my (%can_request,%request_domains);
  585:                 &Apache::lonnet::check_can_request($cdom,\%can_request,\%request_domains,$uname,$udom);
  586:                 if ($can_request{'lti'}) {
  587:                     $reqcrs = 1;
  588:                     &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,
  589:                                  $symb,$cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,
  590:                                  $reqcrs,$sourcecrs);
  591:                 } else {
  592:                     &invalid_request($r,25);
  593:                 }
  594:             } else {
  595:                 &invalid_request($r,26);
  596:             }
  597:         } else {
  598:             &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,
  599:                          $symb,$cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,
  600:                          $reqcrs,$sourcecrs);
  601:         }
  602:         return OK;
  603:     }
  604: 
  605: #
  606: # If LON-CAPA course is a Community, and LON-CAPA role
  607: # indicated is cc, change role indicated to co.
  608: #
  609: 
  610:     my %crsenv;
  611:     if ($lcroles[0] eq 'cc') {
  612:         if (($cdom ne '') && ($cnum ne '')) {
  613:             %crsenv = &Apache::lonnet::coursedescription($cdom.'_'.$cnum,{ 'one_time' => 1,});
  614:             if ($crsenv{'type'} eq 'Community') {
  615:                 $lcroles[0] = 'co';
  616:             }
  617:         }
  618:     }
  619: 
  620: #
  621: # Determine if user has a LON-CAPA role in the mapped LON-CAPA course.
  622: # If multiple LON-CAPA roles are available for the user's assigned LTI roles,
  623: # choose the first available LON-CAPA role in the order: cc/co, in, ta, ep, st
  624: #
  625: 
  626:     my ($role,$usec,$withsec);
  627:     unless ((($lcroles[0] eq 'cc') || ($lcroles[0] eq 'co')) && (@lcroles == 1)) {
  628:         if ($lti{$itemid}{'section'} ne '') {
  629:             if ($lti{$itemid}{'section'} eq 'course_section_sourcedid') {
  630:                 if ($env{'form.course_section_sourcedid'} !~ /\W/) {
  631:                     $usec = $env{'form.course_section_sourcedid'};
  632:                 }
  633:             } elsif ($env{'form.'.$lti{$itemid}{'section'}} !~ /\W/) {
  634:                 $usec = $env{'form.'.$lti{$itemid}{'section'}};
  635:             }
  636:         }
  637:         if ($usec ne '') {
  638:             $withsec = 1;
  639:         }
  640:     }
  641: 
  642:     if (@lcroles) {
  643:         my %crsroles = &Apache::lonnet::get_my_roles($uname,$udom,'userroles',undef,\@lcroles,
  644:                                                      [$cdom],$withsec);
  645:         foreach my $reqrole (@lcroles) {
  646:             if ($withsec) {
  647:                 my $incsec;
  648:                 if (($reqrole eq 'cc') || ($reqrole eq 'co')) {
  649:                     $incsec = '';
  650:                 } else {
  651:                     $incsec = $usec;
  652:                 }
  653:                 if (exists($crsroles{$cnum.':'.$cdom.':'.$reqrole.':'.$incsec})) {
  654:                     $role = $reqrole.'./'.$cdom.'/'.$cnum;
  655:                     if ($incsec ne '') {
  656:                         $role .= '/'.$usec;
  657:                     }
  658:                     last;
  659:                 }
  660:             } else {
  661:                 if (exists($crsroles{$cnum.':'.$cdom.':'.$reqrole})) {
  662:                     $role = $reqrole.'./'.$cdom.'/'.$cnum;
  663:                     last;
  664:                 }
  665:             }
  666:         }
  667:     }
  668: 
  669: #
  670: # Determine if user can selfenroll
  671: #
  672: 
  673:     my ($reqrole,$selfenrollrole);
  674:     if ($role eq '') {
  675:         if ((@ltiroles) && (ref($lti{$itemid}{'selfenroll'}) eq 'ARRAY')) {
  676:             foreach my $ltirole (@ltiroles) {
  677:                 if (grep(/^\Q$ltirole\E$/,@{$lti{$itemid}{'selfenroll'}})) {
  678:                     if (ref($lti{$itemid}{maproles}) eq 'HASH') {
  679:                         $reqrole = $lti{$itemid}{maproles}{$ltirole};
  680:                         last;
  681:                     }
  682:                 }
  683:             }
  684:         }
  685:         if ($reqrole eq '') {
  686:             &invalid_request($r,27);
  687:             return OK;
  688:         } else {
  689:             unless (%crsenv) {
  690:                 %crsenv = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
  691:             }
  692:             my $default_enrollment_start_date = $crsenv{'default_enrollment_start_date'};
  693:             my $default_enrollment_end_date   = $crsenv{'default_enrollment_end_date'};
  694:             my $now = time;
  695:             if ($default_enrollment_end_date && $default_enrollment_end_date <= $now) {
  696:                 &invalid_request($r,28);
  697:                 return OK;
  698:             } elsif ($default_enrollment_start_date && $default_enrollment_start_date >$now) {
  699:                 &invalid_request($r,29);
  700:                 return OK;
  701:             } else {
  702:                 $selfenrollrole = $reqrole.'./'.$cdom.'/'.$cnum;
  703:                 if (($withsec) && ($reqrole ne 'cc') && ($reqrole ne 'co')) {
  704:                     if ($usec ne '') {
  705:                         $selfenrollrole .= '/'.$usec;
  706:                     }
  707:                 }
  708:             }
  709:         }
  710:     }
  711: 
  712: #
  713: # Retrieve course type of LON-CAPA course to check if mapping from a Consumer
  714: # course identifier permitted for this type of course (one of: official,
  715: # unofficial, community, textbook, placement or lti.
  716: #
  717: 
  718:     unless (%crsenv) {
  719:         %crsenv = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
  720:     }
  721:     my $crstype = lc($crsenv{'type'});
  722:     if ($crstype eq '') {
  723:         $crstype = 'course';
  724:     }
  725:     if ($crstype eq 'course') {
  726:         if ($crsenv{'internal.coursecode'}) {
  727:             $crstype = 'official';
  728:         } elsif ($crsenv{'internal.textbook'}) {
  729:             $crstype = 'textbook';
  730:         } elsif ($crsenv{'internal.lti'}) {
  731:             $crstype = 'lti';
  732:         } else {
  733:             $crstype = 'unofficial';
  734:         }
  735:     }
  736: 
  737: #
  738: # Store consumer-to-LON-CAPA course mapping if permitted
  739: #
  740: 
  741:     if (($lti{$itemid}{'storecrs'}) && ($sourcecrs ne '') && 
  742:         ($consumers{$sourcecrs} eq '') && ($cnum ne '')) {
  743:         if (ref($lti{$itemid}{'mapcrstype'}) eq 'ARRAY') {
  744:             if (grep(/^$crstype$/,@{$lti{$itemid}{'mapcrstype'}})) {
  745:                 &Apache::lonnet::put_dom('lticonsumers',{ $sourcecrs => $itemid.':'.$cnum },$cdom);
  746:             }
  747:         }
  748:     }
  749: 
  750: #
  751: # Start user session
  752: #
  753: 
  754:     &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,$role,$mapurl,$tail,$symb,
  755:                  $cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,undef,$sourcecrs,
  756:                  $selfenrollrole);
  757:     return OK;
  758: }
  759: 
  760: sub get_lti_itemid {
  761:     my ($requri,$hostname,$params,$cdom,$cnum,$context) = @_;
  762:     return unless (ref($params) eq 'HASH');
  763:     my $protocol = 'http';
  764:     if ($ENV{'SERVER_PORT'} == 443) {
  765:         $protocol = 'https';
  766:     }
  767:     my $url = $protocol.'://'.$hostname.$requri;
  768:     my $method = $env{'request.method'};
  769:     if ($cnum ne '') {
  770:         return &Apache::lonnet::courselti_itemid($cnum,$cdom,$url,$method,$params,$context);
  771:     } else {
  772:         return &Apache::lonnet::domainlti_itemid($cdom,$url,$method,$params,$context);
  773:     }
  774: }
  775: 
  776: sub lti_enroll {
  777:     my ($uname,$udom,$selfenrollrole) = @_;
  778:     my $enrollresult;
  779:     my ($role,$cdom,$cnum,$sec) =
  780:            ($selfenrollrole =~ m{^(\w+)\./($match_domain)/($match_courseid)(?:|/(\w*))$});
  781:     if (($cnum ne '') && ($cdom ne '')) {
  782:         my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
  783:         if ($chome ne 'no_host') {
  784:             my %coursehash = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
  785:             my $start = $coursehash{'default_enrollment_start_date'};
  786:             my $end = $coursehash{'default_enrollment_end_date'};
  787:             $enrollresult = &LONCAPA::ltiutils::enrolluser($udom,$uname,$role,$cdom,$cnum,$sec,
  788:                                                            $start,$end,1);
  789:         }
  790:     }
  791:     return $enrollresult;
  792: }
  793: 
  794: sub lti_reqcrs {
  795:     my ($r,$cdom,$form,$uname,$udom) = @_;
  796:     my (%can_request,%request_domains);
  797:     &Apache::lonnet::check_can_request($cdom,\%can_request,\%request_domains,$uname,$udom);
  798:     if ($can_request{'lti'}) {
  799:         my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$cdom);
  800:         my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
  801:         &Apache::lonrequestcourse::print_textbook_form($r,$cdom,[$cdom],\%domdefs,
  802:                                                        $domconfig{'requestcourses'},
  803:                                                        \%can_request,'lti',$form);
  804:     } else {
  805:         $r->print(
  806:               &Apache::loncommon::start_page('Invalid LTI call',undef,{'only_body' => 1}).
  807:               &mt('Invalid LTI call').
  808:               &Apache::loncommon::end_page()
  809:         );
  810:     }
  811: }
  812: 
  813: sub lti_session {
  814:     my ($r,$itemid,$uname,$udom,$uhome,$lonhost,$role,$mapurl,$tail,$symb,$cdom,$cnum,
  815:         $params,$ltiroles,$ltihash,$lcroles,$reqcrs,$sourcecrs,$selfenrollrole) = @_;
  816:     return unless ((ref($params) eq 'HASH') && (ref($ltiroles) eq 'ARRAY') &&
  817:                    (ref($ltihash) eq 'HASH') && (ref($lcroles) eq 'ARRAY'));
  818: #
  819: # Check if user should be hosted here or switched to another server.
  820: #
  821:     $r->user($uname);
  822:     if ($cnum) {
  823:         if ($role) {
  824:             &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, role: $role, course: $cdom\_$cnum");
  825:         } elsif ($selfenrollrole =~ m{^(\w+)\./$cdom/$cnum}) {
  826:             &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, desired role: $1 course: $cdom\_$cnum");
  827:         }
  828:     } else {
  829:         &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, course dom: $cdom");
  830:     }
  831:     my ($is_balancer,$otherserver,$hosthere);
  832:     ($is_balancer,$otherserver) =
  833:         &Apache::lonnet::check_loadbalancing($uname,$udom,'login');
  834:     if ($is_balancer) {
  835:         if ($otherserver eq '') {
  836:             my $lowest_load;
  837:             ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($udom);
  838:             if ($lowest_load > 100) {
  839:                 $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$udom);
  840:             }
  841:         }
  842:         if ($otherserver ne '') {
  843:             my @hosts = &Apache::lonnet::current_machine_ids();
  844:             if (grep(/^\Q$otherserver\E$/,@hosts)) {
  845:                 $hosthere = $otherserver;
  846:             }
  847:         }
  848:     }
  849:     my $protocol = 'http';
  850:     if ($ENV{'SERVER_PORT'} == 443) {
  851:         $protocol = 'https';
  852:     }
  853:     if (($is_balancer) && (!$hosthere)) {
  854:         # login but immediately go to switch server.
  855:         &Apache::lonauth::success($r,$uname,$udom,$uhome,'noredirect');
  856:         if (($ltihash->{'callback'}) && ($params->{$ltihash->{'callback'}})) {
  857:             &LONCAPA::ltiutils::setup_logout_callback($uname,$udom,$otherserver,
  858:                                                       $ltihash->{'key'},
  859:                                                       $ltihash->{'secret'},
  860:                                                       $params->{$ltihash->{'callback'}},
  861:                                                       $r->dir_config('ltiIDsDir'),
  862:                                                       $protocol,$r->hostname);
  863:         }
  864:         if ($symb) {
  865:             $env{'form.symb'} = $symb;
  866:             $env{'request.lti.uri'} = $tail;
  867:         } else {
  868:             if ($mapurl) {
  869:                 $env{'form.origurl'} = $mapurl;
  870:                 $env{'request.lti.uri'} = $mapurl;
  871:             } elsif ($tail =~ m{^\Q/tiny/$cdom/\E\w+$}) {
  872:                 $env{'form.origurl'} = $tail;
  873:                 $env{'request.lti.uri'} = $tail;
  874:             } elsif ($tail eq "/$cdom/$cnum") {
  875:                 $env{'form.origurl'} = '/adm/navmaps';
  876:                 $env{'request.lti.uri'} = $tail;
  877:             } else {
  878:                 unless ($tail eq '/adm/roles') {
  879:                     if ($cnum) {
  880:                         $env{'form.origurl'} = '/adm/navmaps';
  881:                     }
  882:                 }
  883:             }
  884:         }
  885:         if ($role) {
  886:             $env{'form.role'} = $role;
  887:         }
  888:         if (($lcroles->[0] eq 'cc') && ($reqcrs)) {
  889:             $env{'request.lti.reqcrs'} = 1;
  890:             $env{'request.lti.reqrole'} = 'cc';
  891:             $env{'request.lti.sourcecrs'} = $sourcecrs;
  892:         }
  893:         if ($selfenrollrole) {
  894:             $env{'request.lti.selfenrollrole'} = $selfenrollrole;
  895:             $env{'request.lti.sourcecrs'} = $sourcecrs;
  896:         }
  897:         if ($ltihash->{'passback'}) {
  898:             if ($params->{'lis_result_sourcedid'}) {
  899:                 $env{'request.lti.passbackid'} = $params->{'lis_result_sourcedid'};
  900:             }
  901:             if ($params->{'lis_outcome_service_url'}) {
  902:                 $env{'request.lti.passbackurl'} = $params->{'lis_outcome_service_url'};
  903:             }
  904:         }
  905:         if (($ltihash->{'roster'}) && (grep(/^Instructor$/,@{$ltiroles}))) {
  906:             if ($params->{'ext_ims_lis_memberships_id'}) {
  907:                 $env{'request.lti.rosterid'} = $params->{'ext_ims_lis_memberships_id'};
  908:             }
  909:             if ($params->{'ext_ims_lis_memberships_url'}) {
  910:                 $env{'request.lti.rosterurl'} = $params->{'ext_ims_lis_memberships_url'};
  911:             }
  912:         }
  913:         $env{'request.lti.login'} = $itemid;
  914:         if ($params->{'launch_presentation_document_target'}) {
  915:             $env{'request.lti.target'} = $params->{'launch_presentation_document_target'};
  916:         }
  917:         foreach my $key (keys(%{$params})) {
  918:             delete($env{'form.'.$key});
  919:         }
  920:         my $redirecturl = '/adm/switchserver';
  921:         if ($otherserver ne '') {
  922:             $redirecturl .= '?otherserver='.$otherserver;
  923:         }
  924:         $r->internal_redirect($redirecturl);
  925:         $r->set_handlers('PerlHandler'=> undef);
  926:     } else {
  927:         # need to login them in, so generate the need data that
  928:         # migrate expects to do login
  929:         foreach my $key (keys(%{$params})) {
  930:             delete($env{'form.'.$key});
  931:         }
  932:         if (($ltihash->{'callback'}) && ($params->{$ltihash->{'callback'}})) {
  933:             &LONCAPA::ltiutils::setup_logout_callback($uname,$udom,$lonhost,
  934:                                                       $ltihash->{'key'},
  935:                                                       $ltihash->{'secret'},
  936:                                                       $params->{$ltihash->{'callback'}},
  937:                                                       $r->dir_config('ltiIDsDir'),
  938:                                                       $protocol,$r->hostname);
  939:         }
  940:         my $ip = $r->get_remote_host();
  941:         my %info=('ip'        => $ip,
  942:                   'domain'    => $udom,
  943:                   'username'  => $uname,
  944:                   'server'    => $lonhost,
  945:                   'lti.login' => $itemid,
  946:                   'lti.uri'   => $tail,
  947:                  );
  948:         if ($role) {
  949:             $info{'role'} = $role;
  950:         }
  951:         if ($symb) {
  952:             $info{'symb'} = $symb;
  953:         }
  954:         if (($lcroles->[0] eq 'cc') && ($reqcrs)) {
  955:             $info{'lti.reqcrs'} = 1;
  956:             $info{'lti.reqrole'} = 'cc';
  957:             $info{'lti.sourcecrs'} = $sourcecrs;
  958:         }
  959:         if ($selfenrollrole) {
  960:             $info{'lti.selfenrollrole'} = $selfenrollrole;
  961:         }
  962:         if ($ltihash->{'passback'}) {
  963:             if ($params->{'lis_result_sourcedid'}) {
  964:                 $info{'lti.passbackid'} = $params->{'lis_result_sourcedid'}
  965:             }
  966:             if ($params->{'lis_outcome_service_url'}) {
  967:                 $info{'lti.passbackurl'} = $params->{'lis_outcome_service_url'}
  968:             }
  969:         }
  970:         if (($ltihash->{'roster'}) && (grep(/^Instructor$/,@{$ltiroles}))) {
  971:             if ($params->{'ext_ims_lis_memberships_id'}) {
  972:                 $info{'lti.rosterid'} = $params->{'ext_ims_lis_memberships_id'};
  973:             }
  974:             if ($params->{'ext_ims_lis_memberships_url'}) {
  975:                 $info{'lti.rosterurl'} = $params->{'ext_ims_lis_memberships_url'};
  976:             }
  977:         }
  978:         if ($params->{'launch_presentation_document_target'}) {
  979:             $info{'lti.target'} = $params->{'launch_presentation_document_target'};
  980:         }
  981: 
  982:         unless ($info{'symb'}) {
  983:             if ($mapurl) {
  984:                 $info{'origurl'} = $mapurl;
  985:             } elsif ($tail =~ m{^\Q/tiny/$cdom/\E\w+$}) {
  986:                 $info{'origurl'} = $tail;
  987:             } else {
  988:                 unless ($tail eq '/adm/roles') {
  989:                     if ($cnum) {
  990:                         $info{'origurl'} = '/adm/navmaps';
  991:                     }
  992:                 }
  993:             }
  994:         }
  995:         if (($is_balancer) && ($hosthere)) {
  996:             $info{'noloadbalance'} = $hosthere;
  997:         }
  998:         my $token = &Apache::lonnet::tmpput(\%info,$lonhost);
  999:         $env{'form.token'} = $token;
 1000:         $r->internal_redirect('/adm/migrateuser');
 1001:         $r->set_handlers('PerlHandler'=> undef);
 1002:     }
 1003:     return;
 1004: }
 1005: 
 1006: sub invalid_request {
 1007:     my ($r,$num) = @_;
 1008:     &Apache::loncommon::content_type($r,'text/html');
 1009:     $r->send_http_header;
 1010:     if ($r->header_only) {
 1011:         return;
 1012:     }
 1013:     &Apache::lonlocal::get_language_handle($r);
 1014:     $r->print(
 1015:         &Apache::loncommon::start_page('Invalid LTI call','',{ 'only_body' => 1,}).
 1016:         &mt('Invalid LTI call [_1]',$num).
 1017:         &Apache::loncommon::end_page());
 1018:     return;
 1019: }
 1020: 
 1021: sub course_from_tinyurl {
 1022:     my ($tail) = @_;
 1023:     my ($urlcdom,$urlcnum);
 1024:     if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
 1025:         ($urlcdom,my $key) = ($1,$2);
 1026:         my $tinyurl;
 1027:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$urlcdom."\0".$key);
 1028:         if (defined($cached)) {
 1029:             $tinyurl = $result;
 1030:         } else {
 1031:             my $configuname = &Apache::lonnet::get_domainconfiguser($urlcdom);
 1032:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$urlcdom,$configuname);
 1033:             if ($currtiny{$key} ne '') {
 1034:                 $tinyurl = $currtiny{$key};
 1035:                 &Apache::lonnet::do_cache_new('tiny',$urlcdom."\0".$key,$currtiny{$key},600);
 1036:             }
 1037:         }
 1038:         if ($tinyurl ne '') {
 1039:             $urlcnum = (split(/\&/,$tinyurl))[0];
 1040:         }
 1041:     }
 1042:     return ($urlcdom,$urlcnum);
 1043: }
 1044: 
 1045: 1;

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