Diff for /loncom/lti/ltiauth.pm between versions 1.18 and 1.38

version 1.18, 2019/06/13 17:45:26 version 1.38, 2022/06/26 04:03:48
Line 30  package Apache::ltiauth; Line 30  package Apache::ltiauth;
   
 use strict;  use strict;
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
 use Apache::Constants qw(:common :http);  use Encode;
 use Net::OAuth;  use Apache::Constants qw(:common :http :remotehost);
 use Apache::lonlocal;  use Apache::lonlocal;
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::loncommon;  use Apache::loncommon;
Line 42  use LONCAPA::ltiutils; Line 42  use LONCAPA::ltiutils;
 sub handler {  sub handler {
     my $r = shift;      my $r = shift;
     my $requri = $r->uri;      my $requri = $r->uri;
       my $hostname = $r->hostname;
 #  #
 # Check for existing session, and temporarily delete any form items  # Check for existing session, and temporarily delete any form items
 # in %env, if session exists  # in %env, if session exists
Line 57  sub handler { Line 58  sub handler {
         }          }
     }      }
 #  #
 # Retrieve data POSTed by LTI Consumer on launch  # Retrieve data POSTed by LTI launch
 #  #
     &Apache::lonacc::get_posted_cgi($r);      &Apache::lonacc::get_posted_cgi($r);
     my $params = {};      my $params = {};
     foreach my $key (sort(keys(%env))) {      foreach my $key (sort(keys(%env))) {
         if ($key =~ /^form\.(.+)$/) {          if ($key =~ /^form\.(.+)$/) {
             $params->{$1} = $env{$key};              $params->{$1} = &Encode::decode('UTF-8',$env{$key});
         }          }
     }      }
 #  #
 # Check for existing session, and restored temporarily  # Check for existing session, and restore temporarily
 # deleted form items to %env, if session exists.  # deleted form items to %env, if session exists.
 #  #
     if ($handle ne '') {      if ($handle ne '') {
Line 79  sub handler { Line 80  sub handler {
     }      }
   
     unless (keys(%{$params})) {      unless (keys(%{$params})) {
         &invalid_request($r,1);          &invalid_request($r,'No parameters included in launch request');
         return OK;          return OK;
     }      }
   
Line 89  sub handler { Line 90  sub handler {
             $params->{'oauth_version'} &&              $params->{'oauth_version'} &&
             $params->{'oauth_signature'} &&              $params->{'oauth_signature'} &&
             $params->{'oauth_signature_method'}) {              $params->{'oauth_signature_method'}) {
         &invalid_request($r,2);          &invalid_request($r,'One or more required parameters missing from launch request');
         return OK;          return OK;
     }      }
   
Line 97  sub handler { Line 98  sub handler {
 # Retrieve "internet domains" for all this institution's LON-CAPA  # Retrieve "internet domains" for all this institution's LON-CAPA
 # nodes.  # nodes.
 #  #
     my ($udom,$uname,$uhome,$cdom,$cnum,$symb,$mapurl,@intdoms);      my @intdoms;
     my $lonhost = $r->dir_config('lonHostID');      my $lonhost = $r->dir_config('lonHostID');
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);      my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
     if (ref($internet_names) eq 'ARRAY') {      if (ref($internet_names) eq 'ARRAY') {
         @intdoms = @{$internet_names};          @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);
                           }
                           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;
                                   }
                               }
                           }
                           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);
                                                   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;
                               }
                               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   # For user who launched LTI in Consumer, determine user's domain in 
Line 198  sub handler { Line 371  sub handler {
         if ($tail =~ m{^/uploaded/($match_domain)/($match_courseid)/(?:default|supplemental)(?:|_\d+)\.(?:sequence|page)(|___\d+___.+)$}) {          if ($tail =~ m{^/uploaded/($match_domain)/($match_courseid)/(?:default|supplemental)(?:|_\d+)\.(?:sequence|page)(|___\d+___.+)$}) {
             ($urlcdom,$urlcnum,my $rest) = ($1,$2,$3);              ($urlcdom,$urlcnum,my $rest) = ($1,$2,$3);
             if (($cdom ne '') && ($cdom ne $urlcdom)) {              if (($cdom ne '') && ($cdom ne $urlcdom)) {
                 &invalid_request($r,3);                  &invalid_request($r,'Incorrect domain in requested URL');
                 return OK;                  return OK;
             }              }
             if ($rest eq '') {              if ($rest eq '') {
Line 217  sub handler { Line 390  sub handler {
         } elsif ($tail =~ m{^/($match_domain)/($match_courseid)$}) {          } elsif ($tail =~ m{^/($match_domain)/($match_courseid)$}) {
             ($urlcdom,$urlcnum) = ($1,$2);              ($urlcdom,$urlcnum) = ($1,$2);
             if (($cdom ne '') && ($cdom ne $urlcdom)) {              if (($cdom ne '') && ($cdom ne $urlcdom)) {
                 &invalid_request($r,4);                  &invalid_request($r,'Incorrect domain in requested URL');
                 return OK;                  return OK;
             }              }
         } elsif ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {          } elsif ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
             ($urlcdom,my $key) = ($1,$2);              ($urlcdom,$urlcnum) = &course_from_tinyurl($tail);
             if (($cdom ne '') && ($cdom ne $urlcdom)) {              if (($urlcdom eq '') || ($urlcnum eq '')) {
                 &invalid_request($r,5);                  &invalid_request($r,'Invalid URL shortcut');
                 return OK;                  return OK;
             }              }
             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];  
             }  
         }          }
         if (($cdom eq '') && ($urlcdom ne '')) {           if (($cdom eq '') && ($urlcdom ne '')) { 
             my $cprimary_id = &Apache::lonnet::domain($urlcdom,'primary');              my $cprimary_id = &Apache::lonnet::domain($urlcdom,'primary');
Line 263  sub handler { Line 421  sub handler {
     }      }
   
 #  #
 # Retrieve information for LTI Consumers in course domain  # Retrieve information for LTI Consumers in course's domain
 # and populate hash --  %lti_by_key -- for which keys  # defined in domain configuration for LTI.
 # are those defined in domain configuration for LTI.  
 #  
    
     my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');  
     unless (keys(%lti) > 0) {  
         &invalid_request($r,6);  
         return OK;  
     }  
     my %lti_by_key;  
     if (keys(%lti)) {  
         foreach my $id (keys(%lti)) {  
             if (ref($lti{$id}) eq 'HASH') {  
                 my $key = $lti{$id}{'key'};  
                 push(@{$lti_by_key{$key}},$id);  
             }  
         }  
     }  
   
 #  #
 # Verify the signed request using the secret for those  # Verify the signed request using the secret for those
 # Consumers for which the key in the POSTed data matches   # Consumers for which the key in the POSTed data matches
 # keys in the domain configuration for LTI.  # keys in the course configuration or the domain configuration
   # for LTI.
 #  #
     my $hostname = $r->hostname;  
     my $protocol = 'http';  
     if ($ENV{'SERVER_PORT'} == 443) {  
         $protocol = 'https';  
     }  
   
     if (exists($params->{'oauth_callback'})) {  
         $Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;  
     } else {  
         $Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0;  
     }  
   
     my ($itemid,$consumer_key,$secret);      my %lti;
     $consumer_key = $params->{'oauth_consumer_key'};      my $itemid = &get_lti_itemid($requri,$hostname,$params,$cdom);
     if (ref($lti_by_key{$consumer_key}) eq 'ARRAY') {      if ($itemid) {
         foreach my $id (@{$lti_by_key{$consumer_key}}) {          %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
             if (ref($lti{$id}) eq 'HASH') {  
                 $secret = $lti{$id}{'secret'};  
                 my $request = Net::OAuth->request('request token')->from_hash($params,  
                                                    request_url => $protocol.'://'.$hostname.$requri,  
                                                    request_method => $env{'request.method'},  
                                                    consumer_secret => $secret,);  
                 if ($request->verify()) {  
                     $itemid = $id;  
                     last;  
                 }  
             }  
         }  
     }      }
   
 #  #
Line 324  sub handler { Line 442  sub handler {
 # configuration in LON-CAPA for that LTI Consumer.  # configuration in LON-CAPA for that LTI Consumer.
 #  #
     unless (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {      unless (($itemid) && (ref($lti{$itemid}) eq 'HASH')) {
         &invalid_request($r,7);          &invalid_request($r,'Launch request could not be validated');
         return OK;          return OK;
     }      }
   
Line 334  sub handler { Line 452  sub handler {
 #  #
     unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},      unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
                                             $lti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {                                              $lti{$itemid}{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
         &invalid_request($r,8);          &invalid_request($r,'Time limit exceeded for launch request credentials');
         return OK;          return OK;
     }      }
   
Line 345  sub handler { Line 463  sub handler {
   
     if (!$lti{$itemid}{'requser'}) {      if (!$lti{$itemid}{'requser'}) {
         if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {          if ($tail =~ m{^/tiny/($match_domain)/(\w+)$}) {
               my $ltitype = 'd';
             foreach my $key (%{$params}) {              foreach my $key (%{$params}) {
                 delete($env{'form.'.$key});                  delete($env{'form.'.$key});
             }              }
             my $ltoken = &Apache::lonnet::tmpput({'linkprot' => $itemid.':'.$tail},              my $ltoken = &Apache::lonnet::tmpput({'linkprot' => $itemid.$ltitype.':'.$tail},
                                                    $lonhost);                                                     $lonhost);
             if ($ltoken) {              if ($ltoken) {
                 $r->internal_redirect($tail.'?ltoken='.$ltoken);                  $r->internal_redirect($tail.'?ltoken='.$ltoken);
                 $r->set_handlers('PerlHandler'=> undef);                  $r->set_handlers('PerlHandler'=> undef);
             } else {              } else {
                 &invalid_request($r,9);                      &invalid_request($r,'Failed to store information from launch request');
             }              }
         } else {          } else {
             &invalid_request($r,10);              &invalid_request($r,'Launch URL invalid for matched launch credentials');
         }          }
         return OK;          return OK;
     }      }
Line 415  sub handler { Line 534  sub handler {
     if ($sourcecrs ne '') {      if ($sourcecrs ne '') {
         %consumers = &Apache::lonnet::get_dom('lticonsumers',[$sourcecrs],$cdom);          %consumers = &Apache::lonnet::get_dom('lticonsumers',[$sourcecrs],$cdom);
         if (exists($consumers{$sourcecrs})) {          if (exists($consumers{$sourcecrs})) {
             if ($consumers{$sourcecrs} =~ /^$match_courseid$/) {              if ($consumers{$sourcecrs} =~ /^\Q$itemid:\E($match_courseid)$/) {
                 my $crshome = &Apache::lonnet::homeserver($consumers{$sourcecrs},$cdom);                  my $storedcnum = $1;
                   my $crshome = &Apache::lonnet::homeserver($storedcnum,$cdom);
                 if ($crshome =~ /(con_lost|no_host|no_such_host)/) {                  if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
                     &invalid_request($r,11);                      &invalid_request($r,'Invalid courseID included in launch data');
                     return OK;                      return OK;
                 } else {                  } else {
                     $posscnum = $consumers{$sourcecrs};                      $posscnum = $storedcnum;
                 }                  }
             }              }
         }          }
Line 430  sub handler { Line 550  sub handler {
     if ($urlcnum ne '') {      if ($urlcnum ne '') {
         if ($posscnum ne '') {          if ($posscnum ne '') {
             if ($posscnum ne $urlcnum) {              if ($posscnum ne $urlcnum) {
                 &invalid_request($r,12);                  &invalid_request($r,'Course ID included in launch data incompatible with URL');
                 return OK;                  return OK;
             } else {              } else {
                 $cnum = $posscnum;                  $cnum = $posscnum;
Line 438  sub handler { Line 558  sub handler {
         } else {          } else {
             my $crshome = &Apache::lonnet::homeserver($urlcnum,$cdom);              my $crshome = &Apache::lonnet::homeserver($urlcnum,$cdom);
             if ($crshome =~ /(con_lost|no_host|no_such_host)/) {              if ($crshome =~ /(con_lost|no_host|no_such_host)/) {
                 &invalid_request($r,13);                  &invalid_request($r,'Valid course ID could not be extracted from requested URL');
                 return OK;                  return OK;
             } else {              } else {
                 $cnum = $urlcnum;                  $cnum = $urlcnum;
Line 503  sub handler { Line 623  sub handler {
                                                     $domdesc,\%data,\%alerts,\%rulematch,                                                      $domdesc,\%data,\%alerts,\%rulematch,
                                                     \%inst_results,\%curr_rules,%got_rules);                                                      \%inst_results,\%curr_rules,%got_rules);
                 if ($result eq 'notallowed') {                  if ($result eq 'notallowed') {
                     &invalid_request($r,14);                      &invalid_request($r,'Account creation not permitted for this user');
                 } elsif ($result eq 'ok') {                  } elsif ($result eq 'ok') {
                     if (($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'mapcrs'}) &&                      if (($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'mapcrs'}) &&
                         ($lti{$itemid}{'makecrs'})) {                          ($lti{$itemid}{'makecrs'})) {
Line 512  sub handler { Line 632  sub handler {
                         }                          }
                     }                      }
                 } else {                  } else {
                     &invalid_request($r,15);                      &invalid_request($r,'An error occurred during account creation');
                     return OK;                      return OK;
                 }                  }
             } else {              } else {
                 &invalid_request($r,16);                  &invalid_request($r,'Account creation not permitted');
                 return OK;                  return OK;
             }              }
         }          }
     } else {      } else {
         &invalid_request($r,17);          &invalid_request($r,'Could not determine username and/or domain for user');
         return OK;          return OK;
     }      }
   
Line 533  sub handler { Line 653  sub handler {
   
     my $reqcrs;      my $reqcrs;
     if ($cnum eq '') {      if ($cnum eq '') {
         if ((@ltiroles) && ($lti{$itemid}{'mapcrs'}) &&          if ($lti{$itemid}{'crsinc'}) {
             ($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'makecrs'})) {              if ((@ltiroles) && ($lti{$itemid}{'mapcrs'}) &&
             my (%can_request,%request_domains);                  ($ltiroles[0] eq 'Instructor') && ($lcroles[0] eq 'cc') && ($lti{$itemid}{'makecrs'})) {
             &Apache::lonnet::check_can_request($cdom,\%can_request,\%request_domains,$uname,$udom);                  my (%can_request,%request_domains);
             if ($can_request{'lti'}) {                  &Apache::lonnet::check_can_request($cdom,\%can_request,\%request_domains,$uname,$udom);
                 $reqcrs = 1;                  if ($can_request{'lti'}) {
                 &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,                      $reqcrs = 1;
                              $symb,$cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,                      &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,
                              $reqcrs,$sourcecrs);                                   $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 {              } else {
                 &invalid_request($r,18);                  &invalid_request($r,'No LON-CAPA course available, and creation is not permitted');
             }              }
         } else {          } else {
             &invalid_request($r,19);              &lti_session($r,$itemid,$uname,$udom,$uhome,$lonhost,undef,$mapurl,$tail,
                            $symb,$cdom,$cnum,$params,\@ltiroles,$lti{$itemid},\@lcroles,
                            $reqcrs,$sourcecrs);
         }          }
         return OK;          return OK;
     }      }
Line 554  sub handler { Line 680  sub handler {
 #  #
 # If LON-CAPA course is a Community, and LON-CAPA role  # If LON-CAPA course is a Community, and LON-CAPA role
 # indicated is cc, change role indicated to co.  # indicated is cc, change role indicated to co.
 #   #
   
     my %crsenv;      my %crsenv;
     if ($lcroles[0] eq 'cc') {      if ($lcroles[0] eq 'cc') {
Line 632  sub handler { Line 758  sub handler {
             }              }
         }          }
         if ($reqrole eq '') {          if ($reqrole eq '') {
             &invalid_request($r,20);              &invalid_request($r,'No matching role available in LON-CAPA course, and not permitted to self-enroll');
             return OK;              return OK;
         } else {          } else {
             unless (%crsenv) {              unless (%crsenv) {
Line 642  sub handler { Line 768  sub handler {
             my $default_enrollment_end_date   = $crsenv{'default_enrollment_end_date'};              my $default_enrollment_end_date   = $crsenv{'default_enrollment_end_date'};
             my $now = time;              my $now = time;
             if ($default_enrollment_end_date && $default_enrollment_end_date <= $now) {              if ($default_enrollment_end_date && $default_enrollment_end_date <= $now) {
                 &invalid_request($r,21);                  &invalid_request($r,'No active role available in LON-CAPA course, and past end date for self-enrollment');
                 return OK;                  return OK;
             } elsif ($default_enrollment_start_date && $default_enrollment_start_date >$now) {              } elsif ($default_enrollment_start_date && $default_enrollment_start_date >$now) {
                 &invalid_request($r,22);                  &invalid_request($r,'No active role available in LON-CAPA course, and brefor start date for self-enrollment');
                 return OK;                  return OK;
             } else {              } else {
                 $selfenrollrole = $reqrole.'./'.$cdom.'/'.$cnum;                  $selfenrollrole = $reqrole.'./'.$cdom.'/'.$cnum;
Line 659  sub handler { Line 785  sub handler {
     }      }
   
 #  #
 # Store consumer-to-LON-CAPA course mapping  # 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 (($sourcecrs ne '')  && ($consumers{$sourcecrs} eq '') && ($cnum ne '')) {      if (($lti{$itemid}{'storecrs'}) && ($sourcecrs ne '') && 
         &Apache::lonnet::put_dom('lticonsumers',{ $sourcecrs => $cnum },$cdom);          ($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);
               }
           }
     }      }
   
 #  #
Line 676  sub handler { Line 832  sub handler {
     return OK;      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 {  sub lti_enroll {
     my ($uname,$udom,$selfenrollrole) = @_;      my ($uname,$udom,$selfenrollrole) = @_;
     my $enrollresult;      my $enrollresult;
Line 731  sub lti_session { Line 903  sub lti_session {
     } else {      } else {
         &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, course dom: $cdom");          &Apache::lonnet::logthis(" LTI authorized user ($itemid): $uname:$udom, course dom: $cdom");
     }      }
     my ($is_balancer,$otherserver,$hosthere);      my ($is_balancer,$otherserver,$hosthere) = &check_balancer($r,$uname,$udom);
     ($is_balancer,$otherserver) =      my $protocol = 'http';
         &Apache::lonnet::check_loadbalancing($uname,$udom,'login');      if ($ENV{'SERVER_PORT'} == 443) {
     if ($is_balancer) {          $protocol = 'https';
         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($lowest_load,$lowest_load,1,$udom);  
             }  
         }  
         if ($otherserver ne '') {  
             my @hosts = &Apache::lonnet::current_machine_ids();  
             if (grep(/^\Q$otherserver\E$/,@hosts)) {  
                 $hosthere = $otherserver;  
             }  
         }  
     }      }
     if (($is_balancer) && (!$hosthere)) {      if (($is_balancer) && (!$hosthere)) {
         # login but immediately go to switch server.          # login but immediately go to switch server.
         &Apache::lonauth::success($r,$uname,$udom,$uhome,'noredirect');          &Apache::lonauth::success($r,$uname,$udom,$uhome,'noredirect');
           if (($ltihash->{'callback'}) && ($params->{$ltihash->{'callback'}})) {
               &LONCAPA::ltiutils::setup_logout_callback($uname,$udom,$otherserver,
                                                         $ltihash->{'key'},
                                                         $ltihash->{'secret'},
                                                         $params->{$ltihash->{'callback'}},
                                                         $r->dir_config('ltiIDsDir'),
                                                         $protocol,$r->hostname);
           }
         if ($symb) {          if ($symb) {
             $env{'form.symb'} = $symb;              $env{'form.symb'} = $symb;
             $env{'request.lti.uri'} = $tail;              $env{'request.lti.uri'} = $tail;
Line 767  sub lti_session { Line 934  sub lti_session {
                 $env{'request.lti.uri'} = $tail;                  $env{'request.lti.uri'} = $tail;
             } else {              } else {
                 unless ($tail eq '/adm/roles') {                  unless ($tail eq '/adm/roles') {
                     $env{'form.origurl'} = '/adm/navmaps';                      if ($cnum) {
                           $env{'form.origurl'} = '/adm/navmaps';
                       }
                 }                  }
             }              }
         }          }
Line 803  sub lti_session { Line 972  sub lti_session {
         if ($params->{'launch_presentation_document_target'}) {          if ($params->{'launch_presentation_document_target'}) {
             $env{'request.lti.target'} = $params->{'launch_presentation_document_target'};              $env{'request.lti.target'} = $params->{'launch_presentation_document_target'};
         }          }
         foreach my $key (%{$params}) {          foreach my $key (keys(%{$params})) {
             delete($env{'form.'.$key});              delete($env{'form.'.$key});
         }          }
         my $redirecturl = '/adm/switchserver';          my $redirecturl = '/adm/switchserver';
Line 813  sub lti_session { Line 982  sub lti_session {
         $r->internal_redirect($redirecturl);          $r->internal_redirect($redirecturl);
         $r->set_handlers('PerlHandler'=> undef);          $r->set_handlers('PerlHandler'=> undef);
     } else {      } else {
         # need to login them in, so generate the need data that          # need to login them in, so generate the data migrate expects to do login
         # migrate expects to do login          foreach my $key (keys(%{$params})) {
         foreach my $key (%{$params}) {  
             delete($env{'form.'.$key});              delete($env{'form.'.$key});
         }          }
         my $ip = $r->get_remote_host();          if (($ltihash->{'callback'}) && ($params->{$ltihash->{'callback'}})) {
               &LONCAPA::ltiutils::setup_logout_callback($uname,$udom,$lonhost,
                                                         $ltihash->{'key'},
                                                         $ltihash->{'secret'},
                                                         $params->{$ltihash->{'callback'}},
                                                         $r->dir_config('ltiIDsDir'),
                                                         $protocol,$r->hostname);
           }
           my $ip = &Apache::lonnet::get_requestor_ip($r,REMOTE_NOLOOKUP);
         my %info=('ip'        => $ip,          my %info=('ip'        => $ip,
                   'domain'    => $udom,                    'domain'    => $udom,
                   'username'  => $uname,                    'username'  => $uname,
Line 867  sub lti_session { Line 1043  sub lti_session {
                 $info{'origurl'} = $tail;                  $info{'origurl'} = $tail;
             } else {              } else {
                 unless ($tail eq '/adm/roles') {                  unless ($tail eq '/adm/roles') {
                     $info{'origurl'} = '/adm/navmaps';                      if ($cnum) {
                           $info{'origurl'} = '/adm/navmaps';
                       }
                 }                  }
             }              }
         }          }
Line 882  sub lti_session { Line 1060  sub lti_session {
     return;      return;
 }  }
   
   sub linkprot_session {
       my ($r,$uname,$cnum,$cdom,$uhome,$itemid,$ltitype,$dest,$lonhost) = @_;
       $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;
           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,
                    );
           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) {
           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 {  sub invalid_request {
     my ($r,$num) = @_;      my ($r,$msg) = @_;
     &Apache::loncommon::content_type($r,'text/html');      &Apache::loncommon::content_type($r,'text/html');
     $r->send_http_header;      $r->send_http_header;
     if ($r->header_only) {      if ($r->header_only) {
Line 892  sub invalid_request { Line 1136  sub invalid_request {
     &Apache::lonlocal::get_language_handle($r);      &Apache::lonlocal::get_language_handle($r);
     $r->print(      $r->print(
         &Apache::loncommon::start_page('Invalid LTI call','',{ 'only_body' => 1,}).          &Apache::loncommon::start_page('Invalid LTI call','',{ 'only_body' => 1,}).
         &mt('Invalid LTI call [_1]',$num).          '<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());          &Apache::loncommon::end_page());
     return;      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;  1;

Removed from v.1.18  
changed lines
  Added in v.1.38


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