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

1.1       raeburn     1: # The LearningOnline Network with CAPA
                      2: # Utility functions for managing LON-CAPA LTI interactions 
                      3: #
1.12    ! raeburn     4: # $Id: ltiutils.pm,v 1.11 2018/05/28 23:26:04 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 {
                    491:             my ($map,$resid,$url) = &Apache::lonnet::decode_symb($tail);
                    492:             $realuri = &Apache::lonnet::clutter($url);
1.7       raeburn   493:             if ($url =~ /\.sequence$/) {
                    494:                 $scope = 'map';
1.6       raeburn   495:             } else {
1.7       raeburn   496:                 $scope = 'resource';
1.6       raeburn   497:                 $realuri .= '?symb='.$tail;
1.10      raeburn   498:                 $passkey = $tail;
                    499:                 if ($getunenc) {
                    500:                     $unencsymb = $tail;
                    501:                 }
1.6       raeburn   502:             }
                    503:         }
1.10      raeburn   504:     } elsif ($tail =~ m{^/?res/$match_domain/$match_username/.+\.(?:sequence|page)(|___\d+___.+)$}) {
1.8       raeburn   505:         my $rest = $1;
                    506:         if ($rest eq '') {
                    507:             $scope = 'map';
                    508:             $realuri = $tail;
                    509:         } else {
                    510:             my ($map,$resid,$url) = &Apache::lonnet::decode_symb($tail);
                    511:             $realuri = &Apache::lonnet::clutter($url);
                    512:             if ($url =~ /\.sequence$/) {
                    513:                 $scope = 'map';
                    514:             } else {
                    515:                 $scope = 'resource';
                    516:                 $realuri .= '?symb='.$tail;
1.10      raeburn   517:                 $passkey = $tail;
                    518:                 if ($getunenc) {
                    519:                     $unencsymb = $tail;
                    520:                 }
1.8       raeburn   521:             }
                    522:         }
1.6       raeburn   523:     } elsif ($tail =~ m{^/tiny/$cdom/(\w+)$}) {
                    524:         my $key = $1;
                    525:         my $tinyurl;
                    526:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                    527:         if (defined($cached)) {
                    528:             $tinyurl = $result;
                    529:         } else {
                    530:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                    531:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                    532:             if ($currtiny{$key} ne '') {
                    533:                 $tinyurl = $currtiny{$key};
                    534:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                    535:             }
                    536:         }
                    537:         if ($tinyurl ne '') {
                    538:             my ($cnum,$symb) = split(/\&/,$tinyurl,2);
                    539:             my ($map,$resid,$url) = &Apache::lonnet::decode_symb($symb);
                    540:             if ($url =~ /\.(page|sequence)$/) {
                    541:                 $scope = 'map';
                    542:             } else {
                    543:                 $scope = 'resource';
                    544:             }
1.10      raeburn   545:             $passkey = $symb;
1.6       raeburn   546:             if ((&Apache::lonnet::EXT('resource.0.encrypturl',$symb) =~ /^yes$/i) &&
                    547:                 (!$env{'request.role.adv'})) {
                    548:                 $realuri = &Apache::lonenc::encrypted(&Apache::lonnet::clutter($url));
1.7       raeburn   549:                 if ($scope eq 'resource') {
1.6       raeburn   550:                     $realuri .= '?symb='.&Apache::lonenc::encrypted($symb);
                    551:                 }
                    552:             } else {
                    553:                 $realuri = &Apache::lonnet::clutter($url);
1.7       raeburn   554:                 if ($scope eq 'resource') {
1.6       raeburn   555:                     $realuri .= '?symb='.$symb;
                    556:                 }
                    557:             }
1.10      raeburn   558:             if ($getunenc) {
                    559:                 $unencsymb = $symb;
                    560:             }
1.6       raeburn   561:         }
1.10      raeburn   562:     } elsif (($tail =~ m{^/$cdom/$cnum$}) || ($tail eq '')) {
1.6       raeburn   563:         $scope = 'course';
                    564:         $realuri = '/adm/navmaps';
1.10      raeburn   565:         $passkey = $tail;
                    566:     }
                    567:     if ($scope eq 'map') {
                    568:         $passkey = $realuri;
                    569:     }
                    570:     if (wantarray) {
                    571:         return ($scope,$realuri,$unencsymb);
                    572:     } else {
                    573:         return $passkey;
                    574:     }
                    575: }
                    576: 
1.12    ! raeburn   577: #
        !           578: # LON-CAPA as LTI Provider
        !           579: #
        !           580: # Obtain a list of course personnel and students from
        !           581: # the LTI Consumer which launched this instance.
        !           582: #
        !           583: 
1.11      raeburn   584: sub get_roster {
                    585:     my ($id,$url,$ckey,$secret) = @_;
                    586:     my %ltiparams = (
                    587:         lti_version                => 'LTI-1p0',
                    588:         lti_message_type           => 'basic-lis-readmembershipsforcontext',
                    589:         ext_ims_lis_memberships_id => $id,
                    590:     );
                    591:     my $hashref = &sign_params($url,$ckey,$secret,\%ltiparams);
                    592:     if (ref($hashref) eq 'HASH') {
                    593:         my $request=new HTTP::Request('POST',$url);
                    594:         $request->content(join('&',map {
                    595:                           my $name = escape($_);
                    596:                           "$name=" . ( ref($hashref->{$_}) eq 'ARRAY'
                    597:                           ? join("&$name=", map {escape($_) } @{$hashref->{$_}})
                    598:                           : &escape($hashref->{$_}) );
                    599:         } keys(%{$hashref})));
                    600:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10);
                    601:         my $message=$response->status_line;
                    602:         if (($response->is_success) && ($response->content ne '')) {
                    603:             my %data = ();
                    604:             my $count = 0;
                    605:             my @state = ();
                    606:             my @items = ('user_id','roles','person_sourcedid','person_name_given','person_name_family',
                    607:                          'person_contact_email_primary','person_name_full','lis_result_sourcedid');
                    608:             my $p = HTML::Parser->new
                    609:             (
                    610:              xml_mode => 1,
                    611:              start_h =>
                    612:                  [sub {
                    613:                      my ($tagname, $attr) = @_;
                    614:                      push(@state,$tagname);
                    615:                      if ("@state" eq "message_response memberships member") {
                    616:                          $count ++;
                    617:                      }
                    618:                  }, "tagname, attr"],
                    619:              text_h =>
                    620:                 [sub {
                    621:                      my ($text) = @_;
                    622:                      foreach my $item (@items) {
                    623:                          if ("@state" eq "message_response memberships member $item") {
                    624:                              $data{$count}{$item} = $text;
                    625:                          }
                    626:                      }
                    627:                    }, "dtext"],
                    628:              end_h =>
                    629:                  [sub {
                    630:                      my ($tagname) = @_;
                    631:                      pop @state;
                    632:                     }, "tagname"],
                    633:             );
                    634:             $p->parse($response->content);
                    635:             $p->eof;
                    636:             return %data;
                    637:         }
                    638:     }
                    639:     return;
                    640: }
                    641: 
1.12    ! raeburn   642: #
        !           643: # LON-CAPA as LTI Provider
        !           644: #
        !           645: # Passback a grade for a user to the LTI Consumer which originally
        !           646: # provided the lis_result_sourcedid
        !           647: #
        !           648: 
1.10      raeburn   649: sub send_grade {
                    650:     my ($id,$url,$ckey,$secret,$scoretype,$total,$possible) = @_;
                    651:     my $score;
                    652:     if ($possible > 0) {
                    653:         if ($scoretype eq 'ratio') {
                    654:             $score = Math::Round::round($total).'/'.Math::Round::round($possible);
                    655:         } elsif ($scoretype eq 'percentage') {
                    656:             $score = (100.0*$total)/$possible;
                    657:             $score = Math::Round::round($score);
                    658:         } else {
                    659:             $score = $total/$possible;
                    660:             $score = sprintf("%.2f",$score);
                    661:         }
                    662:     }
                    663:     my $date = &Apache::loncommon::utc_string(time);
                    664:     my %ltiparams = (
                    665:         lti_version                   => 'LTI-1p0',
                    666:         lti_message_type              => 'basic-lis-updateresult',
                    667:         sourcedid                     => $id,
                    668:         result_resultscore_textstring => $score,
                    669:         result_resultscore_language   => 'en-US',
                    670:         result_resultvaluesourcedid   => $scoretype,
                    671:         result_statusofresult         => 'final',
                    672:         result_date                   => $date,
                    673:     );
                    674:     my $hashref = &sign_params($url,$ckey,$secret,\%ltiparams);
                    675:     if (ref($hashref) eq 'HASH') {
                    676:         my $request=new HTTP::Request('POST',$url);
                    677:         $request->content(join('&',map {
                    678:                           my $name = escape($_);
                    679:                           "$name=" . ( ref($hashref->{$_}) eq 'ARRAY'
                    680:                           ? join("&$name=", map {escape($_) } @{$hashref->{$_}})
                    681:                           : &escape($hashref->{$_}) );
                    682:         } keys(%{$hashref})));
                    683:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10);
                    684:         my $message=$response->status_line;
                    685: #FIXME Handle case where pass back of score to LTI Consumer failed.
1.6       raeburn   686:     }
                    687: }
                    688: 
1.12    ! raeburn   689: #
        !           690: # LON-CAPA as LTI Provider
        !           691: #
        !           692: # Create a new user in LON-CAPA. If the domain's configuration 
        !           693: # includes rules for format of "official" usernames, those rules
        !           694: # will apply when determining if a user is to be created.  In
        !           695: # additional if institutional user information is available that
        !           696: # will be used when creating a new user account.
        !           697: #
        !           698: 
1.11      raeburn   699: sub create_user {
                    700:     my ($ltiref,$uname,$udom,$domdesc,$data,$alerts,$rulematch,$inst_results,
                    701:         $curr_rules,$got_rules) = @_;
                    702:     return unless (ref($ltiref) eq 'HASH');
                    703:     my $checkhash = { "$uname:$udom" => { 'newuser' => 1, }, };
                    704:     my $checks = { 'username' => 1, };
                    705:     my ($lcauth,$lcauthparm);
                    706:     &Apache::loncommon::user_rule_check($checkhash,$checks,$alerts,$rulematch,
                    707:                                         $inst_results,$curr_rules,$got_rules);
                    708:     my ($userchkmsg,$lcauth,$lcauthparm);
                    709:     my $allowed = 1;
                    710:     if (ref($alerts->{'username'}) eq 'HASH') {
                    711:          if (ref($alerts->{'username'}{$udom}) eq 'HASH') {
                    712:              if ($alerts->{'username'}{$udom}{$uname}) {
                    713:                  if (ref($curr_rules->{$udom}) eq 'HASH') {
                    714:                      $userchkmsg =
                    715:                          &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1).
                    716:                          &Apache::loncommon::user_rule_formats($udom,$domdesc,
                    717:                                                                $curr_rules->{$udom}{'username'},
                    718:                                                                'username');
                    719:                  }
                    720:                  $allowed = 0;
                    721:              }
                    722:          }
                    723:     }
                    724:     if ($allowed) {
                    725:         if (ref($rulematch->{$uname.':'.$udom}) eq 'HASH') {
                    726:             my $matchedrule = $rulematch->{$uname.':'.$udom}{'username'};
                    727:             my ($rules,$ruleorder) =
                    728:                 &Apache::lonnet::inst_userrules($udom,'username');
                    729:             if (ref($rules) eq 'HASH') {
                    730:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
                    731:                     $lcauth = $rules->{$matchedrule}{'authtype'};
                    732:                     $lcauthparm = $rules->{$matchedrule}{'authparm'};
                    733:                 }
                    734:             }
                    735:         }
                    736:         if ($lcauth eq '') {
                    737:             $lcauth = $ltiref->{'lcauth'};
                    738:             if ($lcauth eq 'internal') {
                    739:                 $lcauthparm = &create_passwd();
                    740:             } else {
                    741:                 $lcauthparm = $ltiref->{'lcauthparm'};
                    742:             }
                    743:         }
                    744:     } else {
                    745:         return 'notallowed';
                    746:     }
                    747:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
                    748:     my (%useinstdata,%info);
                    749:     if (ref($ltiref->{'instdata'}) eq 'ARRAY') {
                    750:         map { $useinstdata{$_} = 1; } @{$ltiref->{'instdata'}};
                    751:     }
                    752:     foreach my $item (@userinfo) {
                    753:         if (($useinstdata{$item}) && (ref($inst_results->{$uname.':'.$udom}) eq 'HASH') &&
                    754:             ($inst_results->{$uname.':'.$udom}{$item} ne '')) {
                    755:             $info{$item} = $inst_results->{$uname.':'.$udom}{$item};
                    756:         } else {
                    757:             if ($item eq 'permanentemail') {
                    758:                 if ($data->{'permanentemail'} =~/^[^\@]+\@[^@]+$/) {
                    759:                     $info{$item} = $data->{'permanentemail'};
                    760:                 }
                    761:             } elsif (($item eq 'firstname') || ($item eq 'lastname')) {
                    762:                 $info{$item} = $data->{$item};
                    763:             }
                    764:         }
                    765:     }
                    766:     if (($info{'middlename'} eq '') && ($data->{'fullname'} ne '')) {
                    767:         unless ($useinstdata{'middlename'}) {
                    768:             my $fullname = $data->{'fullname'};
                    769:             if ($info{'firstname'}) {
                    770:                 $fullname =~ s/^\s*\Q$info{'firstname'}\E\s*//i;
                    771:             }
                    772:             if ($info{'lastname'}) {
                    773:                 $fullname =~ s/\s*\Q$info{'lastname'}\E\s*$//i;
                    774:             }
                    775:             if ($fullname ne '') {
                    776:                 $fullname =~ s/^\s+|\s+$//g;
                    777:                 if ($fullname ne '') {
                    778:                     $info{'middlename'} = $fullname;
                    779:                 }
                    780:             }
                    781:         }
                    782:     }
                    783:     if (ref($inst_results->{$uname.':'.$udom}{'inststatus'}) eq 'ARRAY') {
                    784:         my @inststatuses = @{$inst_results->{$uname.':'.$udom}{'inststatus'}};
                    785:         $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
                    786:     }
                    787:     my $result =
                    788:         &Apache::lonnet::modifyuser($udom,$uname,$info{'id'},
                    789:                                     $lcauth,$lcauthparm,$info{'firstname'},
                    790:                                     $info{'middlename'},$info{'lastname'},
                    791:                                     $info{'generation'},undef,undef,
                    792:                                     $info{'permanentemail'},$info{'inststatus'});
                    793:     return $result;
                    794: }
                    795: 
1.12    ! raeburn   796: #
        !           797: # LON-CAPA as LTI Provider
        !           798: #
        !           799: # Create a password for a new user if the authentication
        !           800: # type to assign to new users created following LTI launch is
        !           801: # to be LON-CAPA "internal".
        !           802: #
        !           803: 
1.11      raeburn   804: sub create_passwd {
                    805:     my $passwd = '';
1.12    ! raeburn   806:     srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
1.11      raeburn   807:     my @letts = ("a".."z");
                    808:     for (my $i=0; $i<8; $i++) {
                    809:         my $lettnum = int(rand(2));
                    810:         my $item = '';
                    811:         if ($lettnum) {
                    812:             $item = $letts[int(rand(26))];
                    813:             my $uppercase = int(rand(2));
                    814:             if ($uppercase) {
                    815:                 $item =~ tr/a-z/A-Z/;
                    816:             }
                    817:         } else {
                    818:             $item = int(rand(10));
                    819:         }
                    820:         $passwd .= $item;
                    821:     }
                    822:     return ($passwd);
                    823: }
                    824: 
1.12    ! raeburn   825: #
        !           826: # LON-CAPA as LTI Provider
        !           827: #
        !           828: # Enroll a user in a LON-CAPA course, with the specified role and (optional)
        !           829: # section.  If this is a self-enroll case, i.e., a user launched the LTI tool
        !           830: # in the Consumer, user privs will be added to the user's environment for
        !           831: # the new role.
        !           832: #
        !           833: # If this is a self-enroll case, a Course Coordinator role will only be assigned 
        !           834: # if the current user is also the course owner.
        !           835: #
        !           836: 
1.11      raeburn   837: sub enrolluser {
1.12    ! raeburn   838:     my ($udom,$uname,$role,$cdom,$cnum,$sec,$start,$end,$selfenroll) = @_;
1.11      raeburn   839:     my $enrollresult;
                    840:     my $area = "/$cdom/$cnum";
                    841:     if (($role ne 'cc') && ($role ne 'co') && ($sec ne '')) {
                    842:         $area .= '/'.$sec;
                    843:     }
                    844:     my $spec = $role.'.'.$area;
                    845:     my $instcid;
                    846:     if ($role eq 'st') {
                    847:         $enrollresult =
                    848:             &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,
                    849:                                                        undef,undef,$sec,$end,$start,
1.12    ! raeburn   850:                                                        'ltienroll',undef,$cdom.'_'.$cnum,
        !           851:                                                        $selfenroll,'ltienroll','',$instcid);
1.11      raeburn   852:     } elsif ($role =~ /^(cc|in|ta|ep)$/) {
                    853:         $enrollresult =
                    854:             &Apache::lonnet::assignrole($udom,$uname,$area,$role,$end,$start,
1.12    ! raeburn   855:                                         undef,$selfenroll,'ltienroll');
        !           856:     }
        !           857:     if ($enrollresult eq 'ok') {
        !           858:         if ($selfenroll) {
        !           859:             my (%userroles,%newrole,%newgroups);
        !           860:             &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,
        !           861:                                                 $area);
        !           862:             &Apache::lonnet::set_userprivs(\%userroles,\%newrole,\%newgroups);
        !           863:             $userroles{'user.role.'.$spec} = $start.'.'.$end;
        !           864:             &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
        !           865:         }
1.11      raeburn   866:     }
                    867:     return $enrollresult;
                    868: }
                    869: 
1.12    ! raeburn   870: #
        !           871: # LON-CAPA as LTI Provider
        !           872: #
        !           873: # Batch addition of users following LTI launch by a user
        !           874: # with LTI Instructor status.
        !           875: #
        !           876: # A list of users is obtained by a call to get_roster()
        !           877: # if the calling Consumer support the LTI extension: 
        !           878: # Context Memberships Service. 
        !           879: #
        !           880: # If a user included in the retrieved list does not currently
        !           881: # have a user account in LON-CAPA, an account will be created.
        !           882: #
        !           883: # If a user already has an account, and the same role and
        !           884: # section assigned (currently active), then no change will
        !           885: # be made for that user.
        !           886: #
        !           887: # Information available for new users (besides username and)
        !           888: # role) may include: first name, last name, full name (from
        !           889: # which middle name will be extracted), permanent e-mail address,
        !           890: # and lis_result_sourcedid (for passback of grades).
        !           891: #
        !           892: # If grades are to be passed back, the passback url will be
        !           893: # the same as for the current user's session.
        !           894: #
        !           895: # The roles which may be assigned will be determined from the
        !           896: # LTI roles included in the retrieved roster, and the mapping
        !           897: # of LTI roles to LON-CAPA roles configured for this LTI Consumer
        !           898: # in the domain configuration.
        !           899: #
        !           900: # Course Coordinator roles will only be assigned if the current
        !           901: # user is also the course owner.
        !           902: #
        !           903: # The domain configuration for the corresponding Consumer can include
        !           904: # a section to assign to LTI users. If the roster includes students
        !           905: # any existing student roles with a different section will be expired,
        !           906: # and a role in the LTI section will be assigned.
        !           907: #
        !           908: # For non-student rules (excluding Course Coordinator) a role will be
        !           909: # assigned with the LTI section )or no section, if one is not rquired.
        !           910: #
        !           911: 
1.11      raeburn   912: sub batchaddroster {
                    913:     my ($item) = @_;
                    914:     return unless(ref($item) eq 'HASH');
                    915:     return unless (ref($item->{'ltiref'}) eq 'HASH');
                    916:     my ($cdom,$cnum) = split(/_/,$item->{'cid'});
                    917:     my $udom = $cdom;
                    918:     my $id = $item->{'id'};
                    919:     my $url = $item->{'url'};
                    920:     my @intdoms;
                    921:     my $intdomsref = $item->{'intdoms'};
                    922:     if (ref($intdomsref) eq 'ARRAY') {
                    923:         @intdoms = @{$intdomsref};
                    924:     }
                    925:     my $uriscope = $item->{'uriscope'};
                    926:     my $ckey = $item->{'ltiref'}->{'key'};
                    927:     my $secret = $item->{'ltiref'}->{'secret'};
                    928:     my $section = $item->{'ltiref'}->{'section'};
                    929:     $section =~ s/\W//g;
                    930:     if ($section eq 'none') {
                    931:         undef($section);
                    932:     } elsif ($section ne '') {
                    933:         my %curr_groups =
                    934:             &Apache::longroup::coursegroups($cdom,$cnum);
                    935:         if (exists($curr_groups{$section})) {
                    936:             undef($section);
                    937:         }
                    938:     }
                    939:     my (%maproles,@possroles);
                    940:     if (ref($item->{'ltiref'}->{'maproles'}) eq 'HASH') {
                    941:         %maproles = %{$item->{'ltiref'}->{'maproles'}};
                    942:     }
                    943:     if (ref($item->{'possroles'}) eq 'ARRAY') {
                    944:         @possroles = @{$item->{'possroles'}};
                    945:     }
                    946:     if (($ckey ne '') && ($secret ne '') && ($id ne '') && ($url ne '')) {
                    947:         my %data = &get_roster($id,$url,$ckey,$secret);
                    948:         if (keys(%data) > 0) {
                    949:             my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
                    950:             my %coursehash = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                    951:             my $start = $coursehash{'default_enrollment_start_date'};
                    952:             my $end = $coursehash{'default_enrollment_end_date'};
                    953:             my $domdesc = &Apache::lonnet::domain($udom,'description');
                    954:             my $roster = &Apache::loncoursedata::get_classlist($cdom,$cnum);
                    955:             my $status = &Apache::loncoursedata::CL_STATUS;
                    956:             my $cend = &Apache::loncoursedata::CL_END;
                    957:             my $cstart = &Apache::loncoursedata::CL_START;
                    958:             my $lockedtype=&Apache::loncoursedata::CL_LOCKEDTYPE;
                    959:             my $sec=&Apache::loncoursedata::CL_SECTION;
                    960:             my (@activestudents,@futurestudents,@excludedstudents,@localstudents,%currlist,%advroles);
                    961:             if (grep(/^st$/,@possroles)) {
                    962:                 foreach my $user (keys(%{$roster})) {
                    963:                     if ($user =~ m/^(.+):$cdom$/) {
                    964:                         my $stuname = $1;
                    965:                         if ($roster->{$user}[$status] eq "Active") {
                    966:                             push(@activestudents,$stuname);
                    967:                             @{$currlist{$stuname}} = @{$roster->{$user}};
                    968:                             push(@localstudents,$stuname);
                    969:                         } elsif (($roster->{$user}[$cstart] > time)  && ($roster->{$user}[$cend] > time ||
                    970:                                   $roster->{$user}[$cend] == 0 || $roster->{$user}[$cend] eq '')) {
                    971:                             push(@futurestudents,$stuname);
                    972:                             @{$currlist{$stuname}} = @{$roster->{$user}};
                    973:                             push(@localstudents,$stuname);
                    974:                         } elsif ($roster->{$user}[$lockedtype] == 1) {
                    975:                             push(@excludedstudents,$stuname);
                    976:                         }
                    977:                     }
                    978:                 }
                    979:             }
                    980:             if ((@possroles > 1) || ((@possroles == 1) && (!grep(/^st$/,@possroles)))) {
                    981:                 my %personnel = &Apache::lonnet::get_course_adv_roles($item->{'cid'},1);
                    982:                 foreach my $item (keys(%personnel)) {
                    983:                     my ($role,$currsec) = split(/:/,$item);
                    984:                     if ($currsec eq '') {
                    985:                         $currsec = 'none';
                    986:                     }
                    987:                     foreach my $user (split(/,/,$personnel{$item})) {
                    988:                         push(@{$advroles{$user}{$role}},$currsec);
                    989:                     }
                    990:                 }
                    991:             }
                    992:             if (($end == 0) || ($end > time) || (@localstudents > 0)) {
                    993:                 my (%passback,$pbnum,$numadv);
                    994:                 $numadv = 0;
                    995:                 foreach my $i (sort { $a <=> $b } keys(%data)) {
                    996:                     if (ref($data{$i}) eq 'HASH') {
                    997:                         my $entry = $data{$i};
                    998:                         my $user = $entry->{'person_sourcedid'};
                    999:                         my $uname;
                   1000:                         if ($user =~ /^($match_username):($match_domain)$/) {
                   1001:                             $uname = $1;
                   1002:                             my $possudom = $2;
                   1003:                             if ($possudom ne $udom) {
                   1004:                                 my $uintdom = &Apache::lonnet::domain($possudom,'primary');
                   1005:                                 if (($uintdom ne '') && (grep(/^\Q$uintdom\E$/,@intdoms))) {
                   1006:                                     $udom = $possudom;
                   1007:                                 }
                   1008:                             }
                   1009:                         } elsif ($uname =~ /^match_username$/) {
                   1010:                             $uname = $user;
                   1011:                         } else {
                   1012:                             next;
                   1013:                         }
                   1014:                         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   1015:                         if ($uhome eq 'no_host') {
                   1016:                             my %data;
                   1017:                             $data{'permanentemail'} = $entry->{'person_contact_email_primary'};
                   1018:                             $data{'lastname'} = $entry->{'person_name_family'};
                   1019:                             $data{'firstname'} = $entry->{'person_name_given'};
                   1020:                             $data{'fullname'} = $entry->{'person_name_full'};
                   1021:                             my $addresult =
                   1022:                                 &create_user($item->{'ltiref'},$uname,$udom,
                   1023:                                              $domdesc,\%data,\%alerts,\%rulematch,
                   1024:                                              \%inst_results,\%curr_rules,\%got_rules);
                   1025:                             next unless ($addresult eq 'ok');
                   1026:                         }
                   1027:                         if ($env{'request.lti.passbackurl'}) {
                   1028:                             if ($entry->{'lis_result_sourcedid'} ne '') {
                   1029:                                 unless ($pbnum) {
                   1030:                                     ($pbnum,my $error) = &store_passbackurl($env{'request.lti.login'},
                   1031:                                                                             $env{'request.lti.passbackurl'},
                   1032:                                                                             $cdom,$cnum);
                   1033:                                     if ($pbnum eq '') {
                   1034:                                         $pbnum = $env{'request.lti.passbackurl'};
                   1035:                                     }
                   1036:                                 }
                   1037:                                 $passback{$uname."\0".$uriscope."\0".$env{'request.lti.sourcecrs'}."\0".$env{'request.lti.login'}} =
                   1038:                                           $pbnum."\0".$entry->{'lis_result_sourcedid'};
                   1039:                             }
                   1040:                         }
                   1041:                         my $rolestr = $entry->{'roles'};
                   1042:                         my ($lcrolesref) = &get_lc_roles($rolestr,\@possroles,\%maproles);
                   1043:                         my @lcroles = @{$lcrolesref};
                   1044:                         if (@lcroles) {
                   1045:                             if (grep(/^st$/,@lcroles)) {
                   1046:                                 my $addstu;
                   1047:                                 if (!grep(/^\Q$uname\E$/,@excludedstudents)) {
                   1048:                                     if (grep(/^\Q$uname\E$/,@localstudents)) {
                   1049: # Check for section changes
                   1050:                                         if ($currlist{$uname}[$sec] ne $section) {
                   1051:                                             $addstu = 1;
                   1052:                                             &Apache::lonuserutils::modifystudent($udom,$uname,$cdom.'_'.$cnum,
                   1053:                                                                                  undef,undef,'course');
                   1054:                                         } elsif (grep(/^\Q$uname\E$/,@futurestudents)) {
                   1055: # Check for access date changes for students with access starting in the future.
                   1056:                                             my $datechange = &datechange_check($currlist{$uname}[$cstart],
                   1057:                                                                                $currlist{$uname}[$cend],
                   1058:                                                                                $start,$end);
                   1059:                                             if ($datechange) {
                   1060:                                                 $addstu = 1;
                   1061:                                             }
                   1062:                                         }
                   1063:                                     } else {
                   1064:                                         $addstu = 1;
                   1065:                                     }
                   1066:                                 }
                   1067:                                 unless ($addstu) {
                   1068:                                     pop(@lcroles);
                   1069:                                 }
                   1070:                             }
                   1071:                             my @okroles;
                   1072:                             if (@lcroles) {
                   1073:                                 foreach my $role (@lcroles) {
                   1074:                                     unless (($role eq 'st') || (keys(%advroles) == 0)) {
                   1075:                                         if (exists($advroles{$uname.':'.$udom})) {
                   1076:                                             if ((ref($advroles{$uname.':'.$udom}) eq 'HASH') &&
                   1077:                                                 (ref($advroles{$uname.':'.$udom}{$role}) eq 'ARRAY')) {
                   1078:                                                 if (($section eq '') || ($role eq 'cc') || ($role eq 'co')) {
                   1079:                                                     next if (grep(/^none$/,@{$advroles{$uname.':'.$udom}{$role}}));
                   1080:                                                 } else {
                   1081:                                                     next if (grep(/^\Q$sec\E$/,@{$advroles{$uname.':'.$udom}{$role}}));
                   1082:                                                 }
                   1083:                                             }
                   1084:                                         }
                   1085:                                     }
                   1086:                                     push(@okroles,$role);
                   1087:                                 }
                   1088:                             }
                   1089:                             if (@okroles) {
                   1090:                                 my $permanentemail = $entry->{'person_contact_email_primary'};
                   1091:                                 my $lastname = $entry->{'person_name_family'};
                   1092:                                 my $firstname = $entry->{'person_name_given'};
                   1093:                                 foreach my $role (@okroles) {
                   1094:                                     my $enrollresult = &enrolluser($udom,$uname,$role,$cdom,$cnum,
                   1095:                                                                    $section,$start,$end);
                   1096:                                     if (($enrollresult eq 'ok') && ($role ne 'st')) {
                   1097:                                         $numadv ++;
                   1098:                                     }
                   1099:                                 }
                   1100:                             }
                   1101:                         }
                   1102:                     }
                   1103:                 }
                   1104:                 if (keys(%passback)) {
                   1105:                     &Apache::lonnet::put('nohist_lti_passback',\%passback,$cdom,$cnum);
                   1106:                 }
                   1107:                 if ($numadv) {
                   1108:                     &Apache::lonnet::flushcourselogs();
                   1109:                 }
                   1110:             }
                   1111:         }
                   1112:     }
                   1113:     return;
                   1114: }
                   1115: 
1.12    ! raeburn  1116: #
        !          1117: # LON-CAPA as LTI Provider
        !          1118: #
        !          1119: # Gather a list of available LON-CAPA roles derived
        !          1120: # from a comma separated list of LTI roles.
        !          1121: #
        !          1122: # Which LON-CAPA roles are assignable by the current user
        !          1123: # and how LTI roles map to LON-CAPA roles (as defined in
        !          1124: # the domain configuration for the specific Consumer) are 
        !          1125: # factored in when compiling the list of available roles.
        !          1126: #
        !          1127: # Inputs: 3
        !          1128: #  $rolestr - comma separated list of LTI roles.
        !          1129: #  $allowedroles - reference to array of assignable LC roles
        !          1130: #  $maproles - ref to HASH of mapping of LTI roles to LC roles
        !          1131: #
        !          1132: # Outputs: 2
        !          1133: # (a) reference to array of available LC roles.
        !          1134: # (b) reference to array of LTI roles.
        !          1135: #
        !          1136: 
1.11      raeburn  1137: sub get_lc_roles {
                   1138:     my ($rolestr,$allowedroles,$maproles) = @_;
                   1139:     my (@ltiroles,@lcroles);
                   1140:     my @ltiroleorder = ('Instructor','TeachingAssistant','Mentor','Learner');
                   1141:     if ($rolestr =~ /,/) {
                   1142:         my @possltiroles = split(/\s*,\s*/,$rolestr);
                   1143:         foreach my $ltirole (@ltiroleorder) {
                   1144:             if (grep(/^\Q$ltirole\E$/,@possltiroles)) {
                   1145:                 push(@ltiroles,$ltirole);
                   1146:             }
                   1147:         }
                   1148:     } else {
                   1149:         my $singlerole = $rolestr;
                   1150:         $singlerole =~ s/^\s|\s+$//g;
                   1151:         if ($singlerole ne '') {
                   1152:             if (grep(/^\Q$singlerole\E$/,@ltiroleorder)) {
                   1153:                 @ltiroles = ($singlerole);
                   1154:             }
                   1155:         }
                   1156:     }
                   1157:     if (@ltiroles) {
                   1158:         my %possroles;
                   1159:         map { $possroles{$maproles->{$_}} = 1; } @ltiroles;
                   1160:         if (keys(%possroles) > 0) {
                   1161:             if (ref($allowedroles) eq 'ARRAY') {
                   1162:                 foreach my $item (@{$allowedroles}) {
                   1163:                     if (($item eq 'co') || ($item eq 'cc')) {
                   1164:                         if ($possroles{'cc'}) {
                   1165:                             push(@lcroles,$item);
                   1166:                         }
                   1167:                     } elsif ($possroles{$item}) {
                   1168:                         push(@lcroles,$item);
                   1169:                     }
                   1170:                 }
                   1171:             }
                   1172:         }
                   1173:     }
                   1174:     return (\@lcroles,\@ltiroles);
                   1175: }
                   1176: 
1.12    ! raeburn  1177: #
        !          1178: # LON-CAPA as LTI Provider
        !          1179: #
        !          1180: # Compares current start and dates for a user's role
        !          1181: # with dates to apply for the same user/role to 
        !          1182: # determine if there is a change between the current
        !          1183: # ones and the updated ones.
        !          1184: # 
        !          1185: 
1.11      raeburn  1186: sub datechange_check {
                   1187:     my ($oldstart,$oldend,$startdate,$enddate) = @_;
                   1188:     my $datechange = 0;
                   1189:     unless ($oldstart eq $startdate) {
                   1190:         $datechange = 1;
                   1191:     }
                   1192:     if (!$datechange) {
                   1193:         if (!$oldend) {
                   1194:             if ($enddate) {
                   1195:                 $datechange = 1;
                   1196:             }
                   1197:         } elsif ($oldend ne $enddate) {
                   1198:             $datechange = 1;
                   1199:         }
                   1200:     }
                   1201:     return $datechange;
                   1202: }
                   1203: 
1.12    ! raeburn  1204: #
        !          1205: # LON-CAPA as LTI Provider
        !          1206: #
        !          1207: # Store the URL used by a specific LTI Consumer to process grades passed back
        !          1208: # by an LTI Provider.
        !          1209: #
        !          1210: 
1.11      raeburn  1211: sub store_passbackurl {
                   1212:     my ($ltinum,$pburl,$cdom,$cnum) = @_;
                   1213:     my %history = &Apache::lonnet::restore($ltinum,'passbackurl',$cdom,$cnum);
                   1214:     my ($pbnum,$version,$error);
                   1215:     if ($history{'version'}) {
                   1216:         $version = $history{'version'};
                   1217:         for (my $i=1; $i<=$version; $i++) {
                   1218:             if ($history{$i.':pburl'} eq $pburl) {
                   1219:                 $pbnum = $i;
                   1220:                 last;
                   1221:             }
                   1222:         }
                   1223:     } else {
                   1224:         $version = 0;
                   1225:     }
                   1226:     if ($pbnum eq '') {
                   1227:         # get lock on passbackurl db
                   1228:         my $now = time;
                   1229:         my $lockhash = {
                   1230:             'lock'."\0".$ltinum."\0".$now => $env{'user.name'}.':'.$env{'user.domain'},
                   1231:         };
                   1232:         my $tries = 0;
                   1233:         my $gotlock = &Apache::lonnet::newput('passbackurl',$lockhash,$cdom,$cnum);
                   1234:         while (($gotlock ne 'ok') && ($tries<3)) {
                   1235:             $tries ++;
                   1236:             sleep 1;
                   1237:             $gotlock = &Apache::lonnet::newput('passbackurl',$lockhash,$cdom.$cnum);
                   1238:         }
                   1239:         if ($gotlock eq 'ok') {
                   1240:             if (&Apache::lonnet::store_userdata({pburl => $pburl},
                   1241:                                                  $ltinum,'passbackurl',$cdom,$cnum) eq 'ok') {
                   1242:                 $pbnum = 1+$version;
                   1243:             }
                   1244:             my $dellock = &Apache::lonnet::del('passbackurl',['lock'."\0".$ltinum."\0".$now],$cdom,$cnum);
                   1245:             unless ($dellock eq 'ok') {
                   1246:                 $error = &mt('error: could not release lockfile');
                   1247:             }
                   1248:         } else {
                   1249:             $error = &mt('error: could not obtain lockfile');
                   1250:         }
                   1251:     }
                   1252:     return ($pbnum,$error);
                   1253: }
                   1254: 
1.1       raeburn  1255: 1;

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