Annotation of loncom/lti/ltiutils.pm, revision 1.13

1.1       raeburn     1: # The LearningOnline Network with CAPA
                      2: # Utility functions for managing LON-CAPA LTI interactions 
                      3: #
1.13    ! raeburn     4: # $Id: ltiutils.pm,v 1.12 2018/05/30 17:22:30 raeburn Exp $
1.1       raeburn     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 LONCAPA::ltiutils;
                     30: 
                     31: use strict;
                     32: use Net::OAuth;
                     33: use Digest::SHA;
                     34: use UUID::Tiny ':std';
                     35: use Apache::lonnet;
                     36: use Apache::loncommon;
1.11      raeburn    37: use Apache::loncoursedata;
                     38: use Apache::lonuserutils;
                     39: use Apache::lonenc();
                     40: use Apache::longroup();
1.12      raeburn    41: use Apache::lonlocal;
1.10      raeburn    42: use Math::Round();
1.1       raeburn    43: use LONCAPA qw(:DEFAULT :match);
                     44: 
                     45: #
                     46: # LON-CAPA as LTI Consumer or LTI Provider
                     47: #
                     48: # Determine if a nonce in POSTed data has expired.
                     49: # If unexpired, confirm it has not already been used.
                     50: #
                     51: # When LON-CAPA is operating as a Consumer, nonce checking
                     52: # occurs when a Tool Provider launched from an instance of
                     53: # an external tool in a LON-CAPA course makes a request to
                     54: # (a) /adm/service/roster or (b) /adm/service/passback to, 
                     55: # respectively, retrieve a roster or store the grade for 
                     56: # the original launch by a specific user.
                     57: #
                     58: # When LON-CAPA is operating as a Provider, nonce checking 
                     59: # occurs when a user in course context in another LMS (the 
1.4       raeburn    60: # Consumer) launches an external tool to access a LON-CAPA URL: 
1.1       raeburn    61: # /adm/lti/ with LON-CAPA symb, map, or deep-link ID appended.
                     62: #
                     63: 
                     64: sub check_nonce {
                     65:     my ($nonce,$timestamp,$lifetime,$domain,$ltidir) = @_;
                     66:     if (($ltidir eq '') || ($timestamp eq '') || ($timestamp =~ /^\D/) ||
                     67:         ($lifetime eq '') || ($lifetime =~ /\D/) || ($domain eq '')) {
                     68:         return;
                     69:     }
                     70:     my $now = time;
                     71:     if (($timestamp) && ($timestamp < ($now - $lifetime))) {
                     72:         return;
                     73:     }
                     74:     if ($nonce eq '') {
                     75:         return;
                     76:     }
                     77:     if (-e "$ltidir/$domain/$nonce") {
                     78:         return;
                     79:     } else  {
                     80:         unless (-e "$ltidir/$domain") {
                     81:             unless (mkdir("$ltidir/$domain",0755)) {
                     82:                 return;
                     83:             }
                     84:         }
                     85:         if (open(my $fh,'>',"$ltidir/$domain/$nonce")) {
                     86:             print $fh $now;
                     87:             close($fh);
                     88:             return 1;
                     89:         }
                     90:     }
                     91:     return;
                     92: }
                     93: 
                     94: #
                     95: # LON-CAPA as LTI Consumer
                     96: #
                     97: # Determine the domain and the courseID of the LON-CAPA course
                     98: # for which access is needed by a Tool Provider -- either to 
                     99: # retrieve a roster or store the grade for an instance of an 
                    100: # external tool in the course.
                    101: #
                    102: 
                    103: sub get_loncapa_course {
                    104:     my ($lonhost,$cid,$errors) = @_;
                    105:     return unless (ref($errors) eq 'HASH');
                    106:     my ($cdom,$cnum);
                    107:     if ($cid =~ /^($match_domain)_($match_courseid)$/) {
                    108:         my ($posscdom,$posscnum) = ($1,$2);
                    109:         my $cprimary_id = &Apache::lonnet::domain($posscdom,'primary');
                    110:         if ($cprimary_id eq '') {
                    111:             $errors->{5} = 1;
                    112:             return;
                    113:         } else {
                    114:             my @intdoms;
                    115:             my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                    116:             if (ref($internet_names) eq 'ARRAY') {
                    117:                 @intdoms = @{$internet_names};
                    118:             }
                    119:             my $cintdom = &Apache::lonnet::internet_dom($cprimary_id);
                    120:             if  (($cintdom ne '') && (grep(/^\Q$cintdom\E$/,@intdoms))) {
                    121:                 $cdom = $posscdom;
                    122:             } else {
                    123:                 $errors->{6} = 1;
                    124:                 return;
                    125:             }
                    126:         }
                    127:         my $chome = &Apache::lonnet::homeserver($posscnum,$posscdom);
                    128:         if ($chome =~ /(con_lost|no_host|no_such_host)/) {
                    129:             $errors->{7} = 1;
                    130:             return;
                    131:         } else {
                    132:             $cnum = $posscnum;
                    133:         }
                    134:     } else {
                    135:         $errors->{8} = 1;
                    136:         return;
                    137:     }
                    138:     return ($cdom,$cnum);
                    139: }
                    140: 
                    141: #
                    142: # LON-CAPA as LTI Consumer
                    143: #
                    144: # Determine the symb and (optionally) LON-CAPA user for an 
                    145: # instance of an external tool in a course -- either to 
                    146: # to retrieve a roster or store a grade.
                    147: #
                    148: # Use the digested symb to lookup the real symb in exttools.db
                    149: # and the digested userID to lookup the real userID (if needed).
                    150: # and extract the exttool instance and symb.
                    151: #
                    152: 
                    153: sub get_tool_instance {
                    154:     my ($cdom,$cnum,$digsymb,$diguser,$errors) = @_;
                    155:     return unless (ref($errors) eq 'HASH');
                    156:     my ($marker,$symb,$uname,$udom);
                    157:     my @keys = ($digsymb); 
                    158:     if ($diguser) {
                    159:         push(@keys,$diguser);
                    160:     }
                    161:     my %digesthash = &Apache::lonnet::get('exttools',\@keys,$cdom,$cnum);
                    162:     if ($digsymb) {
                    163:         $symb = $digesthash{$digsymb};
                    164:         if ($symb) {
                    165:             my ($map,$id,$url) = split(/___/,$symb);
                    166:             $marker = (split(m{/},$url))[3];
                    167:             $marker=~s/\D//g;
                    168:         } else {
                    169:             $errors->{9} = 1;
                    170:         }
                    171:     }
                    172:     if ($diguser) {
                    173:         if ($digesthash{$diguser} =~ /^($match_username):($match_domain)$/) {
                    174:             ($uname,$udom) = ($1,$2);
                    175:         } else {
                    176:             $errors->{10} = 1;
                    177:         }
                    178:         return ($marker,$symb,$uname,$udom);
                    179:     } else {
                    180:         return ($marker,$symb);
                    181:     }
                    182: }
                    183: 
                    184: #
                    185: # LON-CAPA as LTI Consumer
                    186: #
                    187: # Retrieve data needed to validate a request from a Tool Provider
                    188: # for a roster or to store a grade for an instance of an external 
                    189: # tool in a LON-CAPA course.
                    190: #
                    191: # Retrieve the Consumer key and Consumer secret from the domain 
                    192: # configuration or the Tool Provider ID stored in the
                    193: # exttool_$marker db file and compare the Consumer key with the
                    194: # one in the POSTed data.
                    195: #
                    196: # Side effect is to populate the $toolsettings hashref with the 
                    197: # contents of the .db file (instance of tool in course) and the
                    198: # $ltitools hashref with the configuration for the tool (at
                    199: # domain level).
                    200: #
                    201: 
                    202: sub get_tool_secret {
                    203:     my ($key,$marker,$symb,$cdom,$cnum,$toolsettings,$ltitools,$errors) = @_;
                    204:     return unless ((ref($toolsettings) eq 'HASH') && (ref($ltitools) eq 'HASH') &&
                    205:                    (ref($errors) eq 'HASH'));
                    206:     my ($consumer_secret,$nonce_lifetime);
                    207:     if ($marker) {
                    208:         %{$toolsettings}=&Apache::lonnet::dump('exttool_'.$marker,$cdom,$cnum);
                    209:         if ($toolsettings->{'id'}) {
                    210:             my $idx = $toolsettings->{'id'};
                    211:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'consumer');
                    212:             if (ref($lti{$idx}) eq 'HASH') {
                    213:                 %{$ltitools} = %{$lti{$idx}};
                    214:                 if ($ltitools->{'key'} eq $key) {
                    215:                     $consumer_secret = $ltitools->{'secret'};
                    216:                     $nonce_lifetime = $ltitools->{'lifetime'};
                    217:                 } else {
                    218:                     $errors->{11} = 1;
                    219:                     return;
                    220:                 }
                    221:             } else {
                    222:                 $errors->{12} = 1;
                    223:                 return;
                    224:             }
                    225:         } else {
                    226:             $errors->{13} = 1;
                    227:             return;
                    228:         }
                    229:     } else {
                    230:         $errors->{14};
                    231:         return;
                    232:     }
                    233:     return ($consumer_secret,$nonce_lifetime);
                    234: }
                    235: 
                    236: #
                    237: # LON-CAPA as LTI Consumer
                    238: #
                    239: # Verify a signed request using the consumer_key and
                    240: # secret for the specific LTI Provider.
                    241: #
                    242: 
                    243: sub verify_request {
                    244:     my ($params,$protocol,$hostname,$requri,$reqmethod,$consumer_secret,$errors) = @_;
                    245:     return unless (ref($errors) eq 'HASH');
                    246:     my $request = Net::OAuth->request('request token')->from_hash($params,
                    247:                                        request_url => $protocol.'://'.$hostname.$requri,
                    248:                                        request_method => $reqmethod,
                    249:                                        consumer_secret => $consumer_secret,);
                    250:     unless ($request->verify()) {
                    251:         $errors->{15} = 1;
                    252:         return;
                    253:     }
                    254: }
                    255: 
                    256: #
                    257: # LON-CAPA as LTI Consumer
                    258: #
                    259: # Verify that an item identifier (either roster request:
                    260: # ext_ims_lis_memberships_id, or grade store:
                    261: # lis_result_sourcedid) has not been tampered with, and
                    262: # the secret used to create the unique identifier has not
                    263: # expired.
                    264: #
                    265: # Prepending the current secret (if still valid),
                    266: # or the previous secret (if current one is no longer valid),
                    267: # to a string composed of the :::-separated components
                    268: # must generate the result signature in the lis item ID
                    269: # sent by the Tool Provider.
                    270: #
                    271: 
                    272: sub verify_lis_item {
                    273:     my ($sigrec,$context,$digsymb,$diguser,$cdom,$cnum,$toolsettings,$ltitools,$errors) = @_;
                    274:     return unless ((ref($toolsettings) eq 'HASH') && (ref($ltitools) eq 'HASH') && 
                    275:                    (ref($errors) eq 'HASH'));
                    276:     my ($has_action, $valid_for);
                    277:     if ($context eq 'grade') {
                    278:         $has_action = $ltitools->{'passback'};
                    279:         $valid_for = $ltitools->{'passbackvalid'}
                    280:     } elsif ($context eq 'roster') {
                    281:         $has_action = $ltitools->{'roster'};
                    282:         $valid_for = $ltitools->{'rostervalid'};
                    283:     }
                    284:     if ($has_action) {
                    285:         my $secret;
                    286:         if (($toolsettings->{$context.'secretdate'} + $valid_for) > time) {
                    287:             $secret = $toolsettings->{$context.'secret'};
                    288:         } else {
                    289:             $secret = $toolsettings->{'old'.$context.'secret'};
                    290:         }
                    291:         if ($secret) {
                    292:             my $expected_sig;
                    293:             if ($context eq 'grade') {
                    294:                 my $uniqid = $digsymb.':::'.$diguser.':::'.$cdom.'_'.$cnum;
1.5       raeburn   295:                 $expected_sig = (split(/:::/,&get_service_id($secret,$uniqid)))[0]; 
1.1       raeburn   296:                 if ($expected_sig eq $sigrec) {
                    297:                     return 1;
                    298:                 } else {
1.2       raeburn   299:                     $errors->{17} = 1;
1.1       raeburn   300:                 }
                    301:             } elsif ($context eq 'roster') {
                    302:                 my $uniqid = $digsymb.':::'.$cdom.'_'.$cnum;
1.5       raeburn   303:                 $expected_sig = (split(/:::/,&get_service_id($secret,$uniqid)))[0]; 
1.1       raeburn   304:                 if ($expected_sig eq $sigrec) {
                    305:                     return 1;
                    306:                 } else {
1.2       raeburn   307:                     $errors->{18} = 1;
1.1       raeburn   308:                 }
                    309:             }
                    310:         } else {
1.2       raeburn   311:             $errors->{19} = 1;
1.1       raeburn   312:         }
                    313:     } else {
1.2       raeburn   314:         $errors->{20} = 1;
1.1       raeburn   315:     }
                    316:     return;
                    317: }
                    318: 
                    319: #
                    320: # LON-CAPA as LTI Consumer
                    321: #
                    322: # Sign a request used to launch an instance of an external
1.4       raeburn   323: # tool in a LON-CAPA course, using the key and secret supplied 
1.1       raeburn   324: # by the Tool Provider.
                    325: # 
                    326: 
                    327: sub sign_params {
1.3       raeburn   328:     my ($url,$key,$secret,$sigmethod,$paramsref) = @_;
1.1       raeburn   329:     return unless (ref($paramsref) eq 'HASH');
1.3       raeburn   330:     if ($sigmethod eq '') {
                    331:         $sigmethod = 'HMAC-SHA1';
                    332:     }
1.9       raeburn   333:     srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
1.1       raeburn   334:     my $nonce = Digest::SHA::sha1_hex(sprintf("%06x%06x",rand(0xfffff0),rand(0xfffff0)));
                    335:     my $request = Net::OAuth->request("request token")->new(
                    336:             consumer_key => $key,
                    337:             consumer_secret => $secret,
                    338:             request_url => $url,
                    339:             request_method => 'POST',
1.3       raeburn   340:             signature_method => $sigmethod,
1.1       raeburn   341:             timestamp => time,
                    342:             nonce => $nonce,
                    343:             callback => 'about:blank',
                    344:             extra_params => $paramsref,
                    345:             version      => '1.0',
                    346:             );
                    347:     $request->sign;
                    348:     return $request->to_hash();
                    349: }
                    350: 
                    351: #
                    352: # LON-CAPA as LTI Consumer
                    353: #
                    354: # Generate a signature for a unique identifier (roster request:
                    355: # ext_ims_lis_memberships_id, or grade store: lis_result_sourcedid)
                    356: #
                    357: 
                    358: sub get_service_id {
                    359:     my ($secret,$id) = @_;
                    360:     my $sig = Digest::SHA::sha1_hex($secret.':::'.$id);
                    361:     return $sig.':::'.$id;
                    362: }
                    363: 
                    364: #
                    365: # LON-CAPA as LTI Consumer
                    366: #
                    367: # Generate and store the time-limited secret used to create the
                    368: # signature in a service request identifier (roster request or
                    369: # grade store). An existing secret past its expiration date
                    370: # will be stored as old<service name>secret, and a new secret
                    371: # <service name>secret will be stored.
                    372: # 
                    373: # Secrets are specific to service name and to the tool instance 
                    374: # (and are stored in the exttool_$marker db file).
                    375: # The time period a secret remains valid is determined by the 
                    376: # domain configuration for the specific tool and the service.
                    377: # 
                    378: 
                    379: sub set_service_secret {
                    380:     my ($cdom,$cnum,$marker,$name,$now,$toolsettings,$ltitools) = @_;
                    381:     return unless ((ref($toolsettings) eq 'HASH') && (ref($ltitools) eq 'HASH'));
                    382:     my $warning;
                    383:     my ($needsnew,$oldsecret,$lifetime);
                    384:     if ($name eq 'grade') {
                    385:         $lifetime = $ltitools->{'passbackvalid'}
                    386:     } elsif ($name eq 'roster') {
                    387:         $lifetime = $ltitools->{'rostervalid'};
                    388:     }
                    389:     if ($toolsettings->{$name} eq '') {
                    390:         $needsnew = 1;
                    391:     } elsif (($toolsettings->{$name.'date'} + $lifetime) < $now) {
                    392:         $oldsecret = $toolsettings->{$name.'secret'};
                    393:         $needsnew = 1;
                    394:     }
                    395:     if ($needsnew) {
                    396:         if (&get_tool_lock($cdom,$cnum,$marker,$name,$now) eq 'ok') {
                    397:             my $secret = UUID::Tiny::create_uuid_as_string(UUID_V4);
                    398:             $toolsettings->{$name.'secret'} = $secret;
                    399:             my %secrethash = (
                    400:                            $name.'secret' => $secret,
                    401:                            $name.'secretdate' => $now,
                    402:                           );
                    403:             if ($oldsecret ne '') {
                    404:                 $secrethash{'old'.$name.'secret'} = $oldsecret;
                    405:             }
                    406:             my $putres = &Apache::lonnet::put('exttool_'.$marker,
                    407:                                               \%secrethash,$cdom,$cnum);
                    408:             my $delresult = &release_tool_lock($cdom,$cnum,$marker,$name);
                    409:             if ($delresult ne 'ok') {
                    410:                 $warning = $delresult ;
                    411:             }
                    412:             if ($putres eq 'ok') {
                    413:                 return 'ok';
                    414:             }
                    415:         } else {
                    416:             $warning = 'Could not obtain exclusive lock';
                    417:         }
                    418:     } else {
                    419:         return 'ok';
                    420:     }
                    421:     return;
                    422: }
                    423: 
                    424: #
                    425: # LON-CAPA as LTI Consumer
                    426: #
                    427: # Add a lock key to exttools.db for the instance of an external tool 
                    428: # when generating and storing a service secret.
                    429: #
                    430: 
                    431: sub get_tool_lock {
                    432:     my ($cdom,$cnum,$marker,$name,$now) = @_;
                    433:     # get lock for tool for which secret is being set
                    434:     my $lockhash = {
                    435:                      $name."\0".$marker."\0".'lock' => $now.':'.$env{'user.name'}.
                    436:                                                        ':'.$env{'user.domain'},
                    437:                    };
                    438:     my $tries = 0;
                    439:     my $gotlock = &Apache::lonnet::newput('exttools',$lockhash,$cdom,$cnum);
                    440: 
                    441:     while (($gotlock ne 'ok') && $tries <3) {
                    442:         $tries ++;
                    443:         sleep(1);
                    444:         $gotlock = &Apache::lonnet::newput('exttools',$lockhash,$cdom,$cnum);
                    445:     }
                    446:     return $gotlock;
                    447: }
                    448: 
                    449: #
                    450: # LON-CAPA as LTI Consumer
                    451: #
                    452: # Remove a lock key from exttools.db for the instance of an external
                    453: # tool created when generating and storing a service secret.
                    454: #
                    455: 
                    456: sub release_tool_lock {
1.3       raeburn   457:     my ($cdom,$cnum,$marker,$name) = @_;
1.1       raeburn   458:     #  remove lock
                    459:     my @del_lock = ($name."\0".$marker."\0".'lock');
                    460:     my $dellockoutcome=&Apache::lonnet::del('exttools',\@del_lock,$cdom,$cnum);
                    461:     if ($dellockoutcome ne 'ok') {
                    462:         return 'Warning: failed to release lock for exttool';
                    463:     } else {
                    464:         return 'ok';
                    465:     }
                    466: }
                    467: 
1.6       raeburn   468: #
                    469: # LON-CAPA as LTI Provider
                    470: #
                    471: # Use the part of the launch URL after /adm/lti to determine
                    472: # the scope for the current session (i.e., restricted to a
                    473: # single resource, to a single folder/map, or to an entire
                    474: # course).
                    475: #
                    476: # Returns an array containing scope: resource, map, or course
                    477: # and the LON-CAPA URL that is displayed post-launch, including
                    478: # accommodation of URL encryption, and translation of a tiny URL
                    479: # to the actual URL
                    480: #
                    481: 
                    482: sub lti_provider_scope {
1.10      raeburn   483:     my ($tail,$cdom,$cnum,$getunenc) = @_;
                    484:     my ($scope,$realuri,$passkey,$unencsymb);
                    485:     if ($tail =~ m{^/?uploaded/$cdom/$cnum/(?:default|supplemental)(?:|_\d+)\.(?:sequence|page)(|___\d+___.+)$}) {
1.6       raeburn   486:         my $rest = $1;
                    487:         if ($rest eq '') {
                    488:             $scope = 'map';
                    489:             $realuri = $tail;
                    490:         } else {
1.13    ! raeburn   491:             my $symb = $tail;
        !           492:             $symb =~ s{^/}{};
        !           493:             my ($map,$resid,$url) = &Apache::lonnet::decode_symb($symb);
1.6       raeburn   494:             $realuri = &Apache::lonnet::clutter($url);
1.7       raeburn   495:             if ($url =~ /\.sequence$/) {
                    496:                 $scope = 'map';
1.6       raeburn   497:             } else {
1.7       raeburn   498:                 $scope = 'resource';
1.13    ! raeburn   499:                 $realuri .= '?symb='.$symb;
        !           500:                 $passkey = $symb;
1.10      raeburn   501:                 if ($getunenc) {
1.13    ! raeburn   502:                     $unencsymb = $symb;
1.10      raeburn   503:                 }
1.6       raeburn   504:             }
                    505:         }
1.10      raeburn   506:     } elsif ($tail =~ m{^/?res/$match_domain/$match_username/.+\.(?:sequence|page)(|___\d+___.+)$}) {
1.8       raeburn   507:         my $rest = $1;
                    508:         if ($rest eq '') {
                    509:             $scope = 'map';
                    510:             $realuri = $tail;
                    511:         } else {
1.13    ! raeburn   512:             my $symb = $tail;
        !           513:             $symb =~ s{^/?res/}{};
        !           514:             my ($map,$resid,$url) = &Apache::lonnet::decode_symb($symb);
1.8       raeburn   515:             $realuri = &Apache::lonnet::clutter($url);
                    516:             if ($url =~ /\.sequence$/) {
                    517:                 $scope = 'map';
                    518:             } else {
                    519:                 $scope = 'resource';
1.13    ! raeburn   520:                 $realuri .= '?symb='.$symb;
        !           521:                 $passkey = $symb;
1.10      raeburn   522:                 if ($getunenc) {
1.13    ! raeburn   523:                     $unencsymb = $symb;
1.10      raeburn   524:                 }
1.8       raeburn   525:             }
                    526:         }
1.6       raeburn   527:     } elsif ($tail =~ m{^/tiny/$cdom/(\w+)$}) {
                    528:         my $key = $1;
                    529:         my $tinyurl;
                    530:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                    531:         if (defined($cached)) {
                    532:             $tinyurl = $result;
                    533:         } else {
                    534:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                    535:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                    536:             if ($currtiny{$key} ne '') {
                    537:                 $tinyurl = $currtiny{$key};
                    538:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                    539:             }
                    540:         }
                    541:         if ($tinyurl ne '') {
                    542:             my ($cnum,$symb) = split(/\&/,$tinyurl,2);
                    543:             my ($map,$resid,$url) = &Apache::lonnet::decode_symb($symb);
                    544:             if ($url =~ /\.(page|sequence)$/) {
                    545:                 $scope = 'map';
                    546:             } else {
                    547:                 $scope = 'resource';
                    548:             }
1.10      raeburn   549:             $passkey = $symb;
1.6       raeburn   550:             if ((&Apache::lonnet::EXT('resource.0.encrypturl',$symb) =~ /^yes$/i) &&
                    551:                 (!$env{'request.role.adv'})) {
                    552:                 $realuri = &Apache::lonenc::encrypted(&Apache::lonnet::clutter($url));
1.7       raeburn   553:                 if ($scope eq 'resource') {
1.6       raeburn   554:                     $realuri .= '?symb='.&Apache::lonenc::encrypted($symb);
                    555:                 }
                    556:             } else {
                    557:                 $realuri = &Apache::lonnet::clutter($url);
1.7       raeburn   558:                 if ($scope eq 'resource') {
1.6       raeburn   559:                     $realuri .= '?symb='.$symb;
                    560:                 }
                    561:             }
1.10      raeburn   562:             if ($getunenc) {
                    563:                 $unencsymb = $symb;
                    564:             }
1.6       raeburn   565:         }
1.10      raeburn   566:     } elsif (($tail =~ m{^/$cdom/$cnum$}) || ($tail eq '')) {
1.6       raeburn   567:         $scope = 'course';
                    568:         $realuri = '/adm/navmaps';
1.13    ! raeburn   569:         $passkey = '';
1.10      raeburn   570:     }
                    571:     if ($scope eq 'map') {
                    572:         $passkey = $realuri;
                    573:     }
                    574:     if (wantarray) {
                    575:         return ($scope,$realuri,$unencsymb);
                    576:     } else {
                    577:         return $passkey;
                    578:     }
                    579: }
                    580: 
1.12      raeburn   581: #
                    582: # LON-CAPA as LTI Provider
                    583: #
                    584: # Obtain a list of course personnel and students from
                    585: # the LTI Consumer which launched this instance.
                    586: #
                    587: 
1.11      raeburn   588: sub get_roster {
                    589:     my ($id,$url,$ckey,$secret) = @_;
                    590:     my %ltiparams = (
                    591:         lti_version                => 'LTI-1p0',
                    592:         lti_message_type           => 'basic-lis-readmembershipsforcontext',
                    593:         ext_ims_lis_memberships_id => $id,
                    594:     );
1.13    ! raeburn   595:     my $hashref = &sign_params($url,$ckey,$secret,'',\%ltiparams);
1.11      raeburn   596:     if (ref($hashref) eq 'HASH') {
                    597:         my $request=new HTTP::Request('POST',$url);
                    598:         $request->content(join('&',map {
                    599:                           my $name = escape($_);
                    600:                           "$name=" . ( ref($hashref->{$_}) eq 'ARRAY'
                    601:                           ? join("&$name=", map {escape($_) } @{$hashref->{$_}})
                    602:                           : &escape($hashref->{$_}) );
                    603:         } keys(%{$hashref})));
                    604:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10);
                    605:         my $message=$response->status_line;
                    606:         if (($response->is_success) && ($response->content ne '')) {
                    607:             my %data = ();
                    608:             my $count = 0;
                    609:             my @state = ();
                    610:             my @items = ('user_id','roles','person_sourcedid','person_name_given','person_name_family',
                    611:                          'person_contact_email_primary','person_name_full','lis_result_sourcedid');
                    612:             my $p = HTML::Parser->new
                    613:             (
                    614:              xml_mode => 1,
                    615:              start_h =>
                    616:                  [sub {
                    617:                      my ($tagname, $attr) = @_;
                    618:                      push(@state,$tagname);
                    619:                      if ("@state" eq "message_response memberships member") {
                    620:                          $count ++;
                    621:                      }
                    622:                  }, "tagname, attr"],
                    623:              text_h =>
                    624:                 [sub {
                    625:                      my ($text) = @_;
                    626:                      foreach my $item (@items) {
                    627:                          if ("@state" eq "message_response memberships member $item") {
                    628:                              $data{$count}{$item} = $text;
                    629:                          }
                    630:                      }
                    631:                    }, "dtext"],
                    632:              end_h =>
                    633:                  [sub {
                    634:                      my ($tagname) = @_;
                    635:                      pop @state;
                    636:                     }, "tagname"],
                    637:             );
                    638:             $p->parse($response->content);
                    639:             $p->eof;
                    640:             return %data;
                    641:         }
                    642:     }
                    643:     return;
                    644: }
                    645: 
1.12      raeburn   646: #
                    647: # LON-CAPA as LTI Provider
                    648: #
                    649: # Passback a grade for a user to the LTI Consumer which originally
                    650: # provided the lis_result_sourcedid
                    651: #
                    652: 
1.10      raeburn   653: sub send_grade {
                    654:     my ($id,$url,$ckey,$secret,$scoretype,$total,$possible) = @_;
                    655:     my $score;
                    656:     if ($possible > 0) {
                    657:         if ($scoretype eq 'ratio') {
                    658:             $score = Math::Round::round($total).'/'.Math::Round::round($possible);
                    659:         } elsif ($scoretype eq 'percentage') {
                    660:             $score = (100.0*$total)/$possible;
                    661:             $score = Math::Round::round($score);
                    662:         } else {
                    663:             $score = $total/$possible;
                    664:             $score = sprintf("%.2f",$score);
                    665:         }
                    666:     }
                    667:     my $date = &Apache::loncommon::utc_string(time);
                    668:     my %ltiparams = (
                    669:         lti_version                   => 'LTI-1p0',
                    670:         lti_message_type              => 'basic-lis-updateresult',
                    671:         sourcedid                     => $id,
                    672:         result_resultscore_textstring => $score,
                    673:         result_resultscore_language   => 'en-US',
                    674:         result_resultvaluesourcedid   => $scoretype,
                    675:         result_statusofresult         => 'final',
                    676:         result_date                   => $date,
                    677:     );
1.13    ! raeburn   678:     my $hashref = &sign_params($url,$ckey,$secret,'',\%ltiparams);
1.10      raeburn   679:     if (ref($hashref) eq 'HASH') {
                    680:         my $request=new HTTP::Request('POST',$url);
                    681:         $request->content(join('&',map {
                    682:                           my $name = escape($_);
                    683:                           "$name=" . ( ref($hashref->{$_}) eq 'ARRAY'
                    684:                           ? join("&$name=", map {escape($_) } @{$hashref->{$_}})
                    685:                           : &escape($hashref->{$_}) );
                    686:         } keys(%{$hashref})));
                    687:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10);
                    688:         my $message=$response->status_line;
                    689: #FIXME Handle case where pass back of score to LTI Consumer failed.
1.6       raeburn   690:     }
                    691: }
                    692: 
1.12      raeburn   693: #
                    694: # LON-CAPA as LTI Provider
                    695: #
                    696: # Create a new user in LON-CAPA. If the domain's configuration 
                    697: # includes rules for format of "official" usernames, those rules
                    698: # will apply when determining if a user is to be created.  In
                    699: # additional if institutional user information is available that
                    700: # will be used when creating a new user account.
                    701: #
                    702: 
1.11      raeburn   703: sub create_user {
                    704:     my ($ltiref,$uname,$udom,$domdesc,$data,$alerts,$rulematch,$inst_results,
                    705:         $curr_rules,$got_rules) = @_;
                    706:     return unless (ref($ltiref) eq 'HASH');
                    707:     my $checkhash = { "$uname:$udom" => { 'newuser' => 1, }, };
                    708:     my $checks = { 'username' => 1, };
                    709:     my ($lcauth,$lcauthparm);
                    710:     &Apache::loncommon::user_rule_check($checkhash,$checks,$alerts,$rulematch,
                    711:                                         $inst_results,$curr_rules,$got_rules);
                    712:     my ($userchkmsg,$lcauth,$lcauthparm);
                    713:     my $allowed = 1;
                    714:     if (ref($alerts->{'username'}) eq 'HASH') {
                    715:          if (ref($alerts->{'username'}{$udom}) eq 'HASH') {
                    716:              if ($alerts->{'username'}{$udom}{$uname}) {
                    717:                  if (ref($curr_rules->{$udom}) eq 'HASH') {
                    718:                      $userchkmsg =
                    719:                          &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1).
                    720:                          &Apache::loncommon::user_rule_formats($udom,$domdesc,
                    721:                                                                $curr_rules->{$udom}{'username'},
                    722:                                                                'username');
                    723:                  }
                    724:                  $allowed = 0;
                    725:              }
                    726:          }
                    727:     }
                    728:     if ($allowed) {
                    729:         if (ref($rulematch->{$uname.':'.$udom}) eq 'HASH') {
                    730:             my $matchedrule = $rulematch->{$uname.':'.$udom}{'username'};
                    731:             my ($rules,$ruleorder) =
                    732:                 &Apache::lonnet::inst_userrules($udom,'username');
                    733:             if (ref($rules) eq 'HASH') {
                    734:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
                    735:                     $lcauth = $rules->{$matchedrule}{'authtype'};
                    736:                     $lcauthparm = $rules->{$matchedrule}{'authparm'};
                    737:                 }
                    738:             }
                    739:         }
                    740:         if ($lcauth eq '') {
                    741:             $lcauth = $ltiref->{'lcauth'};
                    742:             if ($lcauth eq 'internal') {
                    743:                 $lcauthparm = &create_passwd();
                    744:             } else {
                    745:                 $lcauthparm = $ltiref->{'lcauthparm'};
                    746:             }
                    747:         }
                    748:     } else {
                    749:         return 'notallowed';
                    750:     }
                    751:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
                    752:     my (%useinstdata,%info);
                    753:     if (ref($ltiref->{'instdata'}) eq 'ARRAY') {
                    754:         map { $useinstdata{$_} = 1; } @{$ltiref->{'instdata'}};
                    755:     }
                    756:     foreach my $item (@userinfo) {
                    757:         if (($useinstdata{$item}) && (ref($inst_results->{$uname.':'.$udom}) eq 'HASH') &&
                    758:             ($inst_results->{$uname.':'.$udom}{$item} ne '')) {
                    759:             $info{$item} = $inst_results->{$uname.':'.$udom}{$item};
                    760:         } else {
                    761:             if ($item eq 'permanentemail') {
                    762:                 if ($data->{'permanentemail'} =~/^[^\@]+\@[^@]+$/) {
                    763:                     $info{$item} = $data->{'permanentemail'};
                    764:                 }
                    765:             } elsif (($item eq 'firstname') || ($item eq 'lastname')) {
                    766:                 $info{$item} = $data->{$item};
                    767:             }
                    768:         }
                    769:     }
                    770:     if (($info{'middlename'} eq '') && ($data->{'fullname'} ne '')) {
                    771:         unless ($useinstdata{'middlename'}) {
                    772:             my $fullname = $data->{'fullname'};
                    773:             if ($info{'firstname'}) {
                    774:                 $fullname =~ s/^\s*\Q$info{'firstname'}\E\s*//i;
                    775:             }
                    776:             if ($info{'lastname'}) {
                    777:                 $fullname =~ s/\s*\Q$info{'lastname'}\E\s*$//i;
                    778:             }
                    779:             if ($fullname ne '') {
                    780:                 $fullname =~ s/^\s+|\s+$//g;
                    781:                 if ($fullname ne '') {
                    782:                     $info{'middlename'} = $fullname;
                    783:                 }
                    784:             }
                    785:         }
                    786:     }
                    787:     if (ref($inst_results->{$uname.':'.$udom}{'inststatus'}) eq 'ARRAY') {
                    788:         my @inststatuses = @{$inst_results->{$uname.':'.$udom}{'inststatus'}};
                    789:         $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
                    790:     }
                    791:     my $result =
                    792:         &Apache::lonnet::modifyuser($udom,$uname,$info{'id'},
                    793:                                     $lcauth,$lcauthparm,$info{'firstname'},
                    794:                                     $info{'middlename'},$info{'lastname'},
                    795:                                     $info{'generation'},undef,undef,
                    796:                                     $info{'permanentemail'},$info{'inststatus'});
                    797:     return $result;
                    798: }
                    799: 
1.12      raeburn   800: #
                    801: # LON-CAPA as LTI Provider
                    802: #
                    803: # Create a password for a new user if the authentication
                    804: # type to assign to new users created following LTI launch is
                    805: # to be LON-CAPA "internal".
                    806: #
                    807: 
1.11      raeburn   808: sub create_passwd {
                    809:     my $passwd = '';
1.12      raeburn   810:     srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
1.11      raeburn   811:     my @letts = ("a".."z");
                    812:     for (my $i=0; $i<8; $i++) {
                    813:         my $lettnum = int(rand(2));
                    814:         my $item = '';
                    815:         if ($lettnum) {
                    816:             $item = $letts[int(rand(26))];
                    817:             my $uppercase = int(rand(2));
                    818:             if ($uppercase) {
                    819:                 $item =~ tr/a-z/A-Z/;
                    820:             }
                    821:         } else {
                    822:             $item = int(rand(10));
                    823:         }
                    824:         $passwd .= $item;
                    825:     }
                    826:     return ($passwd);
                    827: }
                    828: 
1.12      raeburn   829: #
                    830: # LON-CAPA as LTI Provider
                    831: #
                    832: # Enroll a user in a LON-CAPA course, with the specified role and (optional)
                    833: # section.  If this is a self-enroll case, i.e., a user launched the LTI tool
                    834: # in the Consumer, user privs will be added to the user's environment for
                    835: # the new role.
                    836: #
                    837: # If this is a self-enroll case, a Course Coordinator role will only be assigned 
                    838: # if the current user is also the course owner.
                    839: #
                    840: 
1.11      raeburn   841: sub enrolluser {
1.12      raeburn   842:     my ($udom,$uname,$role,$cdom,$cnum,$sec,$start,$end,$selfenroll) = @_;
1.11      raeburn   843:     my $enrollresult;
                    844:     my $area = "/$cdom/$cnum";
                    845:     if (($role ne 'cc') && ($role ne 'co') && ($sec ne '')) {
                    846:         $area .= '/'.$sec;
                    847:     }
                    848:     my $spec = $role.'.'.$area;
                    849:     my $instcid;
                    850:     if ($role eq 'st') {
                    851:         $enrollresult =
                    852:             &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,
                    853:                                                        undef,undef,$sec,$end,$start,
1.12      raeburn   854:                                                        'ltienroll',undef,$cdom.'_'.$cnum,
                    855:                                                        $selfenroll,'ltienroll','',$instcid);
1.11      raeburn   856:     } elsif ($role =~ /^(cc|in|ta|ep)$/) {
                    857:         $enrollresult =
                    858:             &Apache::lonnet::assignrole($udom,$uname,$area,$role,$end,$start,
1.12      raeburn   859:                                         undef,$selfenroll,'ltienroll');
                    860:     }
                    861:     if ($enrollresult eq 'ok') {
                    862:         if ($selfenroll) {
                    863:             my (%userroles,%newrole,%newgroups);
                    864:             &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,
                    865:                                                 $area);
                    866:             &Apache::lonnet::set_userprivs(\%userroles,\%newrole,\%newgroups);
                    867:             $userroles{'user.role.'.$spec} = $start.'.'.$end;
                    868:             &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
                    869:         }
1.11      raeburn   870:     }
                    871:     return $enrollresult;
                    872: }
                    873: 
1.12      raeburn   874: #
                    875: # LON-CAPA as LTI Provider
                    876: #
                    877: # Batch addition of users following LTI launch by a user
                    878: # with LTI Instructor status.
                    879: #
                    880: # A list of users is obtained by a call to get_roster()
                    881: # if the calling Consumer support the LTI extension: 
                    882: # Context Memberships Service. 
                    883: #
                    884: # If a user included in the retrieved list does not currently
                    885: # have a user account in LON-CAPA, an account will be created.
                    886: #
                    887: # If a user already has an account, and the same role and
                    888: # section assigned (currently active), then no change will
                    889: # be made for that user.
                    890: #
                    891: # Information available for new users (besides username and)
                    892: # role) may include: first name, last name, full name (from
                    893: # which middle name will be extracted), permanent e-mail address,
                    894: # and lis_result_sourcedid (for passback of grades).
                    895: #
                    896: # If grades are to be passed back, the passback url will be
                    897: # the same as for the current user's session.
                    898: #
                    899: # The roles which may be assigned will be determined from the
                    900: # LTI roles included in the retrieved roster, and the mapping
                    901: # of LTI roles to LON-CAPA roles configured for this LTI Consumer
                    902: # in the domain configuration.
                    903: #
                    904: # Course Coordinator roles will only be assigned if the current
                    905: # user is also the course owner.
                    906: #
                    907: # The domain configuration for the corresponding Consumer can include
                    908: # a section to assign to LTI users. If the roster includes students
                    909: # any existing student roles with a different section will be expired,
                    910: # and a role in the LTI section will be assigned.
                    911: #
                    912: # For non-student rules (excluding Course Coordinator) a role will be
                    913: # assigned with the LTI section )or no section, if one is not rquired.
                    914: #
                    915: 
1.11      raeburn   916: sub batchaddroster {
                    917:     my ($item) = @_;
                    918:     return unless(ref($item) eq 'HASH');
                    919:     return unless (ref($item->{'ltiref'}) eq 'HASH');
                    920:     my ($cdom,$cnum) = split(/_/,$item->{'cid'});
                    921:     my $udom = $cdom;
                    922:     my $id = $item->{'id'};
                    923:     my $url = $item->{'url'};
                    924:     my @intdoms;
                    925:     my $intdomsref = $item->{'intdoms'};
                    926:     if (ref($intdomsref) eq 'ARRAY') {
                    927:         @intdoms = @{$intdomsref};
                    928:     }
                    929:     my $uriscope = $item->{'uriscope'};
                    930:     my $ckey = $item->{'ltiref'}->{'key'};
                    931:     my $secret = $item->{'ltiref'}->{'secret'};
                    932:     my $section = $item->{'ltiref'}->{'section'};
                    933:     $section =~ s/\W//g;
                    934:     if ($section eq 'none') {
                    935:         undef($section);
                    936:     } elsif ($section ne '') {
                    937:         my %curr_groups =
                    938:             &Apache::longroup::coursegroups($cdom,$cnum);
                    939:         if (exists($curr_groups{$section})) {
                    940:             undef($section);
                    941:         }
                    942:     }
                    943:     my (%maproles,@possroles);
                    944:     if (ref($item->{'ltiref'}->{'maproles'}) eq 'HASH') {
                    945:         %maproles = %{$item->{'ltiref'}->{'maproles'}};
                    946:     }
                    947:     if (ref($item->{'possroles'}) eq 'ARRAY') {
                    948:         @possroles = @{$item->{'possroles'}};
                    949:     }
                    950:     if (($ckey ne '') && ($secret ne '') && ($id ne '') && ($url ne '')) {
                    951:         my %data = &get_roster($id,$url,$ckey,$secret);
                    952:         if (keys(%data) > 0) {
                    953:             my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
                    954:             my %coursehash = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                    955:             my $start = $coursehash{'default_enrollment_start_date'};
                    956:             my $end = $coursehash{'default_enrollment_end_date'};
                    957:             my $domdesc = &Apache::lonnet::domain($udom,'description');
                    958:             my $roster = &Apache::loncoursedata::get_classlist($cdom,$cnum);
                    959:             my $status = &Apache::loncoursedata::CL_STATUS;
                    960:             my $cend = &Apache::loncoursedata::CL_END;
                    961:             my $cstart = &Apache::loncoursedata::CL_START;
                    962:             my $lockedtype=&Apache::loncoursedata::CL_LOCKEDTYPE;
                    963:             my $sec=&Apache::loncoursedata::CL_SECTION;
                    964:             my (@activestudents,@futurestudents,@excludedstudents,@localstudents,%currlist,%advroles);
                    965:             if (grep(/^st$/,@possroles)) {
                    966:                 foreach my $user (keys(%{$roster})) {
                    967:                     if ($user =~ m/^(.+):$cdom$/) {
                    968:                         my $stuname = $1;
                    969:                         if ($roster->{$user}[$status] eq "Active") {
                    970:                             push(@activestudents,$stuname);
                    971:                             @{$currlist{$stuname}} = @{$roster->{$user}};
                    972:                             push(@localstudents,$stuname);
                    973:                         } elsif (($roster->{$user}[$cstart] > time)  && ($roster->{$user}[$cend] > time ||
                    974:                                   $roster->{$user}[$cend] == 0 || $roster->{$user}[$cend] eq '')) {
                    975:                             push(@futurestudents,$stuname);
                    976:                             @{$currlist{$stuname}} = @{$roster->{$user}};
                    977:                             push(@localstudents,$stuname);
                    978:                         } elsif ($roster->{$user}[$lockedtype] == 1) {
                    979:                             push(@excludedstudents,$stuname);
                    980:                         }
                    981:                     }
                    982:                 }
                    983:             }
                    984:             if ((@possroles > 1) || ((@possroles == 1) && (!grep(/^st$/,@possroles)))) {
                    985:                 my %personnel = &Apache::lonnet::get_course_adv_roles($item->{'cid'},1);
                    986:                 foreach my $item (keys(%personnel)) {
                    987:                     my ($role,$currsec) = split(/:/,$item);
                    988:                     if ($currsec eq '') {
                    989:                         $currsec = 'none';
                    990:                     }
                    991:                     foreach my $user (split(/,/,$personnel{$item})) {
                    992:                         push(@{$advroles{$user}{$role}},$currsec);
                    993:                     }
                    994:                 }
                    995:             }
                    996:             if (($end == 0) || ($end > time) || (@localstudents > 0)) {
                    997:                 my (%passback,$pbnum,$numadv);
                    998:                 $numadv = 0;
                    999:                 foreach my $i (sort { $a <=> $b } keys(%data)) {
                   1000:                     if (ref($data{$i}) eq 'HASH') {
                   1001:                         my $entry = $data{$i};
                   1002:                         my $user = $entry->{'person_sourcedid'};
                   1003:                         my $uname;
                   1004:                         if ($user =~ /^($match_username):($match_domain)$/) {
                   1005:                             $uname = $1;
                   1006:                             my $possudom = $2;
                   1007:                             if ($possudom ne $udom) {
                   1008:                                 my $uintdom = &Apache::lonnet::domain($possudom,'primary');
                   1009:                                 if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) {
                   1010:                                     $udom = $possudom;
                   1011:                                 }
                   1012:                             }
                   1013:                         } elsif ($uname =~ /^match_username$/) {
                   1014:                             $uname = $user;
                   1015:                         } else {
                   1016:                             next;
                   1017:                         }
                   1018:                         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   1019:                         if ($uhome eq 'no_host') {
                   1020:                             my %data;
                   1021:                             $data{'permanentemail'} = $entry->{'person_contact_email_primary'};
                   1022:                             $data{'lastname'} = $entry->{'person_name_family'};
                   1023:                             $data{'firstname'} = $entry->{'person_name_given'};
                   1024:                             $data{'fullname'} = $entry->{'person_name_full'};
                   1025:                             my $addresult =
                   1026:                                 &create_user($item->{'ltiref'},$uname,$udom,
                   1027:                                              $domdesc,\%data,\%alerts,\%rulematch,
                   1028:                                              \%inst_results,\%curr_rules,\%got_rules);
                   1029:                             next unless ($addresult eq 'ok');
                   1030:                         }
                   1031:                         if ($env{'request.lti.passbackurl'}) {
                   1032:                             if ($entry->{'lis_result_sourcedid'} ne '') {
                   1033:                                 unless ($pbnum) {
                   1034:                                     ($pbnum,my $error) = &store_passbackurl($env{'request.lti.login'},
                   1035:                                                                             $env{'request.lti.passbackurl'},
                   1036:                                                                             $cdom,$cnum);
                   1037:                                     if ($pbnum eq '') {
                   1038:                                         $pbnum = $env{'request.lti.passbackurl'};
                   1039:                                     }
                   1040:                                 }
                   1041:                                 $passback{$uname."\0".$uriscope."\0".$env{'request.lti.sourcecrs'}."\0".$env{'request.lti.login'}} =
                   1042:                                           $pbnum."\0".$entry->{'lis_result_sourcedid'};
                   1043:                             }
                   1044:                         }
                   1045:                         my $rolestr = $entry->{'roles'};
                   1046:                         my ($lcrolesref) = &get_lc_roles($rolestr,\@possroles,\%maproles);
                   1047:                         my @lcroles = @{$lcrolesref};
                   1048:                         if (@lcroles) {
                   1049:                             if (grep(/^st$/,@lcroles)) {
                   1050:                                 my $addstu;
                   1051:                                 if (!grep(/^\Q$uname\E$/,@excludedstudents)) {
                   1052:                                     if (grep(/^\Q$uname\E$/,@localstudents)) {
                   1053: # Check for section changes
                   1054:                                         if ($currlist{$uname}[$sec] ne $section) {
                   1055:                                             $addstu = 1;
                   1056:                                             &Apache::lonuserutils::modifystudent($udom,$uname,$cdom.'_'.$cnum,
                   1057:                                                                                  undef,undef,'course');
                   1058:                                         } elsif (grep(/^\Q$uname\E$/,@futurestudents)) {
                   1059: # Check for access date changes for students with access starting in the future.
                   1060:                                             my $datechange = &datechange_check($currlist{$uname}[$cstart],
                   1061:                                                                                $currlist{$uname}[$cend],
                   1062:                                                                                $start,$end);
                   1063:                                             if ($datechange) {
                   1064:                                                 $addstu = 1;
                   1065:                                             }
                   1066:                                         }
                   1067:                                     } else {
                   1068:                                         $addstu = 1;
                   1069:                                     }
                   1070:                                 }
                   1071:                                 unless ($addstu) {
                   1072:                                     pop(@lcroles);
                   1073:                                 }
                   1074:                             }
                   1075:                             my @okroles;
                   1076:                             if (@lcroles) {
                   1077:                                 foreach my $role (@lcroles) {
                   1078:                                     unless (($role eq 'st') || (keys(%advroles) == 0)) {
                   1079:                                         if (exists($advroles{$uname.':'.$udom})) {
                   1080:                                             if ((ref($advroles{$uname.':'.$udom}) eq 'HASH') &&
                   1081:                                                 (ref($advroles{$uname.':'.$udom}{$role}) eq 'ARRAY')) {
                   1082:                                                 if (($section eq '') || ($role eq 'cc') || ($role eq 'co')) {
                   1083:                                                     next if (grep(/^none$/,@{$advroles{$uname.':'.$udom}{$role}}));
                   1084:                                                 } else {
                   1085:                                                     next if (grep(/^\Q$sec\E$/,@{$advroles{$uname.':'.$udom}{$role}}));
                   1086:                                                 }
                   1087:                                             }
                   1088:                                         }
                   1089:                                     }
                   1090:                                     push(@okroles,$role);
                   1091:                                 }
                   1092:                             }
                   1093:                             if (@okroles) {
                   1094:                                 my $permanentemail = $entry->{'person_contact_email_primary'};
                   1095:                                 my $lastname = $entry->{'person_name_family'};
                   1096:                                 my $firstname = $entry->{'person_name_given'};
                   1097:                                 foreach my $role (@okroles) {
                   1098:                                     my $enrollresult = &enrolluser($udom,$uname,$role,$cdom,$cnum,
                   1099:                                                                    $section,$start,$end);
                   1100:                                     if (($enrollresult eq 'ok') && ($role ne 'st')) {
                   1101:                                         $numadv ++;
                   1102:                                     }
                   1103:                                 }
                   1104:                             }
                   1105:                         }
                   1106:                     }
                   1107:                 }
                   1108:                 if (keys(%passback)) {
                   1109:                     &Apache::lonnet::put('nohist_lti_passback',\%passback,$cdom,$cnum);
                   1110:                 }
                   1111:                 if ($numadv) {
                   1112:                     &Apache::lonnet::flushcourselogs();
                   1113:                 }
                   1114:             }
                   1115:         }
                   1116:     }
                   1117:     return;
                   1118: }
                   1119: 
1.12      raeburn  1120: #
                   1121: # LON-CAPA as LTI Provider
                   1122: #
                   1123: # Gather a list of available LON-CAPA roles derived
                   1124: # from a comma separated list of LTI roles.
                   1125: #
                   1126: # Which LON-CAPA roles are assignable by the current user
                   1127: # and how LTI roles map to LON-CAPA roles (as defined in
                   1128: # the domain configuration for the specific Consumer) are 
                   1129: # factored in when compiling the list of available roles.
                   1130: #
                   1131: # Inputs: 3
                   1132: #  $rolestr - comma separated list of LTI roles.
                   1133: #  $allowedroles - reference to array of assignable LC roles
                   1134: #  $maproles - ref to HASH of mapping of LTI roles to LC roles
                   1135: #
                   1136: # Outputs: 2
                   1137: # (a) reference to array of available LC roles.
                   1138: # (b) reference to array of LTI roles.
                   1139: #
                   1140: 
1.11      raeburn  1141: sub get_lc_roles {
                   1142:     my ($rolestr,$allowedroles,$maproles) = @_;
                   1143:     my (@ltiroles,@lcroles);
                   1144:     my @ltiroleorder = ('Instructor','TeachingAssistant','Mentor','Learner');
                   1145:     if ($rolestr =~ /,/) {
                   1146:         my @possltiroles = split(/\s*,\s*/,$rolestr);
                   1147:         foreach my $ltirole (@ltiroleorder) {
                   1148:             if (grep(/^\Q$ltirole\E$/,@possltiroles)) {
                   1149:                 push(@ltiroles,$ltirole);
                   1150:             }
                   1151:         }
                   1152:     } else {
                   1153:         my $singlerole = $rolestr;
                   1154:         $singlerole =~ s/^\s|\s+$//g;
                   1155:         if ($singlerole ne '') {
                   1156:             if (grep(/^\Q$singlerole\E$/,@ltiroleorder)) {
                   1157:                 @ltiroles = ($singlerole);
                   1158:             }
                   1159:         }
                   1160:     }
                   1161:     if (@ltiroles) {
                   1162:         my %possroles;
                   1163:         map { $possroles{$maproles->{$_}} = 1; } @ltiroles;
                   1164:         if (keys(%possroles) > 0) {
                   1165:             if (ref($allowedroles) eq 'ARRAY') {
                   1166:                 foreach my $item (@{$allowedroles}) {
                   1167:                     if (($item eq 'co') || ($item eq 'cc')) {
                   1168:                         if ($possroles{'cc'}) {
                   1169:                             push(@lcroles,$item);
                   1170:                         }
                   1171:                     } elsif ($possroles{$item}) {
                   1172:                         push(@lcroles,$item);
                   1173:                     }
                   1174:                 }
                   1175:             }
                   1176:         }
                   1177:     }
                   1178:     return (\@lcroles,\@ltiroles);
                   1179: }
                   1180: 
1.12      raeburn  1181: #
                   1182: # LON-CAPA as LTI Provider
                   1183: #
                   1184: # Compares current start and dates for a user's role
                   1185: # with dates to apply for the same user/role to 
                   1186: # determine if there is a change between the current
                   1187: # ones and the updated ones.
                   1188: # 
                   1189: 
1.11      raeburn  1190: sub datechange_check {
                   1191:     my ($oldstart,$oldend,$startdate,$enddate) = @_;
                   1192:     my $datechange = 0;
                   1193:     unless ($oldstart eq $startdate) {
                   1194:         $datechange = 1;
                   1195:     }
                   1196:     if (!$datechange) {
                   1197:         if (!$oldend) {
                   1198:             if ($enddate) {
                   1199:                 $datechange = 1;
                   1200:             }
                   1201:         } elsif ($oldend ne $enddate) {
                   1202:             $datechange = 1;
                   1203:         }
                   1204:     }
                   1205:     return $datechange;
                   1206: }
                   1207: 
1.12      raeburn  1208: #
                   1209: # LON-CAPA as LTI Provider
                   1210: #
                   1211: # Store the URL used by a specific LTI Consumer to process grades passed back
                   1212: # by an LTI Provider.
                   1213: #
                   1214: 
1.11      raeburn  1215: sub store_passbackurl {
                   1216:     my ($ltinum,$pburl,$cdom,$cnum) = @_;
                   1217:     my %history = &Apache::lonnet::restore($ltinum,'passbackurl',$cdom,$cnum);
                   1218:     my ($pbnum,$version,$error);
                   1219:     if ($history{'version'}) {
                   1220:         $version = $history{'version'};
                   1221:         for (my $i=1; $i<=$version; $i++) {
                   1222:             if ($history{$i.':pburl'} eq $pburl) {
                   1223:                 $pbnum = $i;
                   1224:                 last;
                   1225:             }
                   1226:         }
                   1227:     } else {
                   1228:         $version = 0;
                   1229:     }
                   1230:     if ($pbnum eq '') {
                   1231:         # get lock on passbackurl db
                   1232:         my $now = time;
                   1233:         my $lockhash = {
                   1234:             'lock'."\0".$ltinum."\0".$now => $env{'user.name'}.':'.$env{'user.domain'},
                   1235:         };
                   1236:         my $tries = 0;
                   1237:         my $gotlock = &Apache::lonnet::newput('passbackurl',$lockhash,$cdom,$cnum);
                   1238:         while (($gotlock ne 'ok') && ($tries<3)) {
                   1239:             $tries ++;
                   1240:             sleep 1;
                   1241:             $gotlock = &Apache::lonnet::newput('passbackurl',$lockhash,$cdom.$cnum);
                   1242:         }
                   1243:         if ($gotlock eq 'ok') {
                   1244:             if (&Apache::lonnet::store_userdata({pburl => $pburl},
                   1245:                                                  $ltinum,'passbackurl',$cdom,$cnum) eq 'ok') {
                   1246:                 $pbnum = 1+$version;
                   1247:             }
                   1248:             my $dellock = &Apache::lonnet::del('passbackurl',['lock'."\0".$ltinum."\0".$now],$cdom,$cnum);
                   1249:             unless ($dellock eq 'ok') {
                   1250:                 $error = &mt('error: could not release lockfile');
                   1251:             }
                   1252:         } else {
                   1253:             $error = &mt('error: could not obtain lockfile');
                   1254:         }
                   1255:     }
                   1256:     return ($pbnum,$error);
                   1257: }
                   1258: 
1.1       raeburn  1259: 1;

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