File:  [LON-CAPA] / loncom / lti / ltipassback.pm
Revision 1.8: download - view: text, annotated - select for diffs
Fri Jun 2 00:28:03 2023 UTC (12 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, version_2_11_4_msu, HEAD
- Remove trailing white space.

    1: # The LearningOnline Network with CAPA
    2: # LTI Consumer Module to receive grades passed back by Provider 
    3: #
    4: # $Id: ltipassback.pm,v 1.8 2023/06/02 00:28:03 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::ltipassback;
   30: 
   31: use strict;
   32: use URI::Escape;
   33: use Apache::Constants qw(:common :http);
   34: use Apache::lonnet;
   35: use Apache::loncommon;
   36: use Apache::lonacc;
   37: use LONCAPA::ltiutils;
   38: 
   39: sub handler {
   40:     my $r = shift;
   41:     my %errors;
   42:     my $params = {};
   43:     my ($oauthtype,$authheader,$xmlbody);
   44: #
   45: # Retrieve content type from headers
   46: #
   47:     my $content_type = $r->headers_in->get('Content-Type');
   48:     if ($content_type eq 'application/xml') {
   49:         $oauthtype = 'consumer';
   50: #
   51: # Retrieve OAuth data from Authorization header sent by LTI Provider
   52: #
   53:         $authheader = $r->headers_in->get('Authorization');
   54:         my ($authtype,$valuestr) = ($authheader =~ /^(OAuth)\s+(.+)$/i);
   55:         if (lc($authtype) eq 'oauth') {
   56:             foreach my $pair (split(/\s*,\s*/,$valuestr)) {
   57:                 my ($key,$value) = split(/=/,$pair);
   58:                 $value =~ s /(^"|"$)//g;
   59:                 $params->{$key} = URI::Escape::uri_unescape($value);
   60:             }
   61:         }
   62: #
   63: # Retrieve message body
   64: #
   65:         my $length = $r->headers_in->get('Content-length');
   66:         if ($length) {
   67:             $r->read($xmlbody,$length,0);
   68:             if ($xmlbody ne '') {
   69:                 my %grades = &LONCAPA::ltiutils::parse_grade_xml($xmlbody);
   70:                 foreach my $num (sort { $a <=> $b } (keys(%grades))) {
   71:                     if (ref($grades{$num}) eq 'HASH') {
   72:                         if (($grades{$num}{'sourcedid'} ne '') && ($grades{$num}{'score'} ne '')) {
   73:                             $params->{'sourcedid'} = $grades{$num}{'sourcedid'};
   74:                             $params->{'result_resultscore_textstring'} = $grades{$num}{'score'};
   75:                             $params->{'result_resultscore_language'} = $grades{$num}{'language'};
   76:                             $params->{'result_resultvaluesourcedid'} = 'decimal'; 
   77:                         }
   78:                     } 
   79:                 }
   80:             }
   81:         }
   82:     } else {
   83:         $oauthtype = 'request token';
   84: #
   85: # Retrieve data POSTed by LTI Provider
   86: #
   87:         &Apache::lonacc::get_posted_cgi($r);
   88:         foreach my $key (sort(keys(%env))) {
   89:             if ($key =~ /^form\.(.+)$/) {
   90:                 $params->{$1} = $env{$key};
   91:             }
   92:         }
   93:     }
   94: 
   95:     unless (keys(%{$params})) {
   96:         $errors{1} = 1; 
   97:         &invalid_request($r,$params,\%errors);
   98:         return OK;
   99:     }
  100: 
  101:     unless ($params->{'oauth_consumer_key'} &&
  102:             $params->{'oauth_nonce'} &&
  103:             $params->{'oauth_timestamp'} &&
  104:             $params->{'oauth_version'} &&
  105:             $params->{'oauth_signature'} &&
  106:             $params->{'oauth_signature_method'}) {
  107:         $errors{2} = 1; 
  108:         &invalid_request($r,$params,\%errors);
  109:         return OK;
  110:     }
  111: 
  112: #
  113: # Retrieve the signature, digested symb, digested user, and LON-CAPA 
  114: # courseID from the sourcedid in the POSTed data
  115: #
  116:     unless ($params->{'sourcedid'}) {
  117:         $errors{3} = 1; 
  118:         &invalid_request($r,$params,\%errors);
  119:         return OK;
  120:     }
  121: 
  122:     my ($resultsig,$digsymb,$diguser,$cid) = split(/\Q:::\E/,$params->{'sourcedid'});
  123:     unless ($resultsig && $digsymb && $diguser && $cid) {
  124:         $errors{4} = 1; 
  125:         &invalid_request($r,$params,\%errors);
  126:         return OK;
  127:     }
  128: 
  129:     my ($cdom,$cnum,$marker,$symb,$uname,$udom);
  130: 
  131: #
  132: # Determine the domain and the courseID of the LON-CAPA course to which the
  133: # launch of LON-CAPA should provide access.
  134: #
  135:     ($cdom,$cnum) = &LONCAPA::ltiutils::get_loncapa_course($r->dir_config('lonHostID'),
  136:                                                            $cid,\%errors);  
  137:     unless ($cdom && $cnum) {
  138:         &invalid_request($r,$params,\%errors);
  139:         return OK;
  140:     }
  141: 
  142: #
  143: # Use the digested symb to lookup the real symb in exttools.db
  144: #
  145: 
  146:     ($marker,$symb,$uname,$udom) = 
  147:         &LONCAPA::ltiutils::get_tool_instance($cdom,$cnum,$digsymb,$diguser,\%errors);
  148: 
  149:     unless ($marker) {
  150:         &invalid_request($r,$params,\%errors);
  151:         return OK;
  152:     }
  153: 
  154: #
  155: # Retrieve the Consumer key and Consumer secret from the domain configuration
  156: # for the Tool Provider ID stored in the exttool_$marker.db
  157: #
  158: 
  159:     my (%toolsettings,%ltitools);
  160:     my ($consumer_secret,$nonce_lifetime) =
  161:         &LONCAPA::ltiutils::get_tool_secret($params->{'oauth_consumer_key'},
  162:                                             $marker,$symb,$cdom,$cnum,
  163:                                             \%toolsettings,\%ltitools,\%errors);
  164: 
  165:     if (keys(%errors) > 0) {
  166:         &invalid_request($r,$params,\%errors);
  167:         return OK;
  168:     }
  169: 
  170: #
  171: # Verify the signed request using the consumer_key and 
  172: # secret for the specific LTI Provider.
  173: #
  174: 
  175:     my $protocol = 'http';
  176:     if ($ENV{'SERVER_PORT'} == 443) {
  177:         $protocol = 'https';
  178:     }
  179: 
  180:     unless (LONCAPA::ltiutils::verify_request($oauthtype,$protocol,$r->hostname,$r->uri,
  181:                                               $r->method,$consumer_secret,$params,
  182:                                               $authheader,\%errors)) {
  183:         &invalid_request($r,$params,\%errors);
  184:         return OK;
  185:     }
  186: 
  187: #
  188: # Verify XML in request body has not been tampered with
  189: #
  190: 
  191:     if ($content_type eq 'application/xml') {
  192:         my $bodyhash = Digest::SHA::sha1_base64($xmlbody);
  193:         while (length($bodyhash) % 4) {
  194:             $bodyhash .= '=';
  195:         }
  196:         unless ($bodyhash eq $params->{oauth_body_hash}) {
  197:             $errors{16} = 1;
  198:             &invalid_request($r,$params,\%errors);
  199:             return OK;
  200:         }
  201:     }
  202: 
  203: #
  204: # Determine if nonce in POSTed data has expired.
  205: # If unexpired, confirm it has not already been used.
  206: #
  207: 
  208:     unless (&LONCAPA::ltiutils::check_nonce($params->{'oauth_nonce'},$params->{'oauth_timestamp'},
  209:                                             $ltitools{'lifetime'},$cdom,$r->dir_config('lonLTIDir'))) {
  210:         $errors{17} = 1;
  211:         &invalid_request($r,$params,\%errors);
  212:         return OK;
  213:     }
  214: 
  215: #
  216: # Verify that the sourcedid has not been tampered with,
  217: # and the gradesecret used to create it is still valid. 
  218: # 
  219: 
  220:     unless (&LONCAPA::ltiutils::verify_lis_item($resultsig,'grade',$digsymb,$diguser,$cdom,
  221:                                                 $cnum,\%toolsettings,\%ltitools,\%errors)) {
  222:         &invalid_request($r,$params,\%errors);
  223:         return OK;
  224:     }
  225: 
  226: #
  227: # Does the user have an active role in the course which maps to one of
  228: # the supported LTI roles
  229: #
  230: 
  231:     if (($uname ne '') && ($udom ne '')) {
  232:         my %maproles;
  233:         if (ref($ltitools{'roles'}) eq 'HASH') {
  234:             %maproles = %{$ltitools{'roles'}};
  235:         }
  236:         unless (keys(%maproles)) {
  237:             $errors{22} = 1;
  238:             &invalid_request($r,$params,\%errors);
  239:             return OK;
  240:         }
  241:         my ($crstype,$hasrole);
  242:         my @allroles = &Apache::lonuserutils::roles_by_context('course',0,$crstype);
  243:         my (%availableroles,$coursepersonnel,$includestudents,%users);
  244:         foreach my $role (@allroles) {
  245:             if (exists($maproles{$role})) {
  246:                 $availableroles{$role} = 1;
  247:                 if ($role eq 'st') {
  248:                     $includestudents = 1;
  249:                 } else {
  250:                     $coursepersonnel = 1;
  251:                 }
  252:             }
  253:         }
  254:         if (keys(%availableroles)) {
  255:             my $courseurl = "/$cdom/$cnum";
  256:             my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,$courseurl);
  257:             if (keys(%roleshash)) {
  258:                 my $now = time;
  259:                 foreach my $key (keys(%roleshash)) {
  260:                     if ($key =~ m{^\Q$courseurl\E(|/\w+)_(\w+)$}) {
  261:                         my ($secgroup,$rolecode) = ($1,$2);
  262:                         next if ($rolecode eq 'gr');
  263:                         next unless ($availableroles{$rolecode});
  264:                         my ($dummy,$end,$start)=split(/\_/,$roleshash{$key});
  265:                         next if (defined($end) && $end && ($now > $end));
  266:                         next if (defined($start) && $start && ($now < $start));
  267:                         $hasrole = 1;
  268:                         last;
  269:                     }
  270:                 }
  271:             }
  272:         }
  273:         unless ($hasrole) {
  274:             $errors{23} = 1;
  275:             &invalid_request($r,$params,\%errors);
  276:             return OK;
  277:         }
  278:     } else {
  279:         $errors{24} = 1;
  280:         &invalid_request($r,$params,\%errors);
  281:         return OK;
  282:     }
  283: 
  284: #
  285: # Store result if one was sent in a valid format. 
  286: #
  287: 
  288:     my ($result,$resulttype,$lang,$pcf);
  289:     if (exists($params->{'result_resultvaluesourcedid'})) {
  290:         $resulttype = $params->{'result_resultvaluesourcedid'};
  291:         $resulttype =~ s/(^\s+|\s+)$//g;
  292:     } else {
  293:         $resulttype = 'decimal';
  294:     }
  295:     $result = $params->{'result_resultscore_textstring'};
  296:     $result =~ s/(^\s+|\s+)$//g;
  297:     my $posslang = $params->{'result_resultscore_language'};
  298:     $posslang =~ s/(^\s+|\s+)$//g;
  299:     if ($posslang =~ /^\w+(|\-\w+(|\-w+))$/) {
  300:         $lang = $posslang;
  301:     }
  302:     if (($resulttype eq 'ratio') || ($resulttype eq 'decimal') || ($resulttype eq 'percentage')) {
  303:         if ($resulttype eq 'ratio') {
  304:             my ($numerator,$denominator) = split(/\s*\/\s*/,$result,2);
  305:             $numerator =~ s/(^\s+|\s+)$//g;
  306:             $denominator =~ s/(^\s+|\s+)$//g;
  307:             if (($numerator =~ /^\d+$/) && ($denominator =~ /^\d+$/) && ($denominator !=0)) {
  308:                 eval {
  309:                          $pcf = $numerator/$denominator;
  310:                      };
  311:             }
  312:             if ($@) {
  313:                 $errors{24} = 1;
  314:                 &invalid_request($r,$params,\%errors);
  315:                 return OK;
  316:             }
  317:         } elsif ($resulttype eq 'decimal') {
  318:             if (($result ne '') && ($result =~ /^\d*\.?\d*$/)) {
  319:                 if ($result eq '.') {
  320:                     $result = 0;
  321:                 }
  322:                 if (($result >= 0) && ($result <= 1)) {
  323:                     $pcf = $result;
  324:                 }
  325:             }
  326:         } elsif ($resulttype eq 'percentage') {
  327:             if ($result =~ /^(\d+)\s*\%?$/) {
  328:                 my $percent = $1;
  329:                 if (($percent >= 0) && ($percent <= 100)) {
  330:                     $pcf = $percent/100.0;
  331:                 }
  332:             }
  333:         }
  334:         if ($pcf ne '') {
  335:             my %newrecord=();
  336:             my $reckey = 'resource.0.solved'; 
  337:             my %record = &Apache::lonnet::restore($symb,$cdom.'_'.$cnum,$udom,$uname);
  338:             my $tries = 0;
  339:             if ($record{'resource.0.tries'} =~ /^\d$/) {
  340:                 $tries = $record{'resource.0.tries'};
  341:             }
  342:             if ($record{'resource.0.awarded'} ne $pcf) {
  343:                 $newrecord{'resource.0.awarded'}  = $pcf;
  344:             }
  345:             if ($pcf == 0) {
  346:                 if ($record{$reckey} ne 'incorrect_by_passback') {
  347:                     $newrecord{$reckey} = 'incorrect_by_passback';
  348:                 }
  349:             } else {
  350:                 if ($record{$reckey} ne 'correct_by_passback') {
  351:                     $newrecord{$reckey} = 'correct_by_passback';
  352:                 }
  353:             }
  354:             if (%newrecord) {
  355:                 $newrecord{'resource.0.tries'} = 1 + $tries;
  356:                 $env{'request.course.id'} = $cdom.'_'.$cnum;
  357:                 my $result = &Apache::lonnet::cstore(\%newrecord,$symb,$cdom.'_'.$cnum,
  358:                                                      $udom,$uname);
  359:                 delete($env{'request.course.id'});
  360:                 if (($result eq 'ok') || ($result eq 'con_delayed')) {
  361:                     &success($r,$params->{'sourcedid'},$resulttype,$result,$lang);
  362:                 } else {
  363:                     $errors{25} = 1;
  364:                     &invalid_request($r,$params,\%errors);
  365:                 }
  366:             } else {
  367:                 &success($r,$params->{'sourcedid'},$resulttype,$result,$lang);
  368:             }
  369:         } else {
  370:             $errors{26} = 1;
  371:             &invalid_request($r,$params,\%errors);
  372:         }
  373:     } else {
  374:         $errors{27} = 1;
  375:         &invalid_request($r,$params,\%errors);
  376:     }
  377:     return OK;
  378: }
  379: 
  380: sub success {
  381:     my ($r,$sourcedid,$scoretype,$score,$lang) = @_;
  382:     my $date = &Apache::loncommon::utc_string(time); 
  383:     &Apache::loncommon::content_type($r,'text/xml');
  384:     $r->send_http_header;
  385:     if ($r->header_only) {
  386:         return;
  387:     }
  388:     $r->print(<<"END");
  389: <?xml version="1.0" encoding="UTF-8" ?>
  390: <message_response>
  391:   <lti_message_type>basic-lis-updateresult</lti_message_type>
  392:   <statusinfo>
  393:     <codemajor>Success</codemajor>
  394:     <severity>Status</severity>
  395:     <codeminor>fullsuccess</codeminor>
  396:     <description>Grade updated</description>
  397:   </statusinfo>
  398:   <result>
  399:     <sourcedid>$sourcedid</sourcedid>
  400:     <date>$date</date>
  401:     <resultscore>
  402:       <resultvaluesourcedid>$scoretype</resultvaluesourcedid>
  403:       <textstring>$score</textstring>
  404:       <language>$lang</language>
  405:     </resultscore>
  406:   </result>
  407: </message_response>
  408: END
  409:     return;
  410: }
  411: 
  412: sub invalid_request {
  413:     my ($r,$params,$errors) = @_;
  414:     my $date = &Apache::loncommon::utc_string(time);
  415:     my ($scoretype,$score,$lang);
  416:     if (ref($params) eq 'HASH') {
  417:         if ($params->{'result_resultvaluesourcedid'} =~ /^\s*(decimal|percentage|ratio)\s*$/) {
  418:             $scoretype = $1;
  419:         }
  420:         if ($scoretype eq 'decimal') {
  421:             if ($params->{'result_resultscore_textstring'} =~ /^\s*(\d*\.?\d*)\s*$/) {
  422:                 $score = $1;
  423:             }
  424:         } elsif ($scoretype eq 'ratio') {
  425:             if ($params->{'result_resultscore_textstring'} =~ m{^\s*(\d+)\s*/\s*(\d+)\s*$}) {
  426:                 $score = $1.'/'.$2;
  427:             }
  428:         } elsif ($scoretype eq 'percentage') {
  429:             if ($params->{'result_resultscore_textstring'} =~ /^\s*(\d+)\s*(\%?)\s*$/) {
  430:                 $score = $1.$2;
  431:             }
  432:         }
  433:         my $posslang = $params->{'result_resultscore_language'};
  434:         $posslang =~ s/(^\s+|\s+)$//g; 
  435:         if ($posslang =~ /^\w+(|\-\w+(|\-w+))$/) {
  436:             $lang = $posslang;
  437:         }
  438:     } 
  439:     my $errormsg;
  440:     if (ref($errors) eq 'HASH') {
  441:         $errormsg = join(',',keys(%{$errors}));
  442:     }
  443:     &Apache::loncommon::content_type($r,'text/xml');
  444:     $r->send_http_header;
  445:     if ($r->header_only) {
  446:         return;
  447:     }
  448:     $r->print(<<"END");
  449: <message_response>
  450:   <lti_message_type>basic-lis-updateresult</lti_message_type>
  451:   <statusinfo>
  452:      <codemajor>Failure</codemajor>
  453:      <severity>Error</severity>
  454:      <codeminor>$errormsg</codeminor>
  455:   </statusinfo>
  456:   <result>
  457:     <sourcedid>$params->{'sourcedid'}</sourcedid>
  458:     <statusofresult>interim</statusofresult>
  459:     <date>$date</date>
  460:     <resultscore>
  461:       <resultvaluesourcedid>$scoretype</resultvaluesourcedid>
  462:       <textstring>$score</textstring>
  463:       <language>$lang</language>
  464:     </resultscore>
  465:   </result>
  466: </message_response>
  467: END
  468:     return;
  469: }
  470: 
  471: 1;
  472: 

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