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