File:
[LON-CAPA] /
loncom /
homework /
lonhomework.pm
Revision
1.376:
download - view:
text,
annotated -
select for diffs
Fri Jun 2 01:20:27 2023 UTC (14 months, 3 weeks ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Bugs 6754 and 6907
- Return of grades to launcher CMS supported for resources or folders
accessed via LTI-mediated deep link.
- Support option: "Encrypt stored consumer secrets defined in domain"
- Signing of LTI payloads for roster retrieval, passback of grades,
and callback to logput launcher CMS session all now occur on
primary library server for course's domain.
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Homework handler
3: #
4: # $Id: lonhomework.pm,v 1.376 2023/06/02 01:20:27 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27:
28:
29: package Apache::lonhomework;
30: use strict;
31: use Apache::style();
32: use Apache::lonxml();
33: use Apache::lonnet;
34: use Apache::lonplot();
35: use Apache::inputtags();
36: use Apache::structuretags();
37: use Apache::randomlabel();
38: use Apache::response();
39: use Apache::hint();
40: use Apache::outputtags();
41: use Apache::caparesponse();
42: use Apache::radiobuttonresponse();
43: use Apache::optionresponse();
44: use Apache::imageresponse();
45: use Apache::essayresponse();
46: use Apache::externalresponse();
47: use Apache::rankresponse();
48: use Apache::matchresponse();
49: use Apache::chemresponse();
50: use Apache::functionplotresponse();
51: use Apache::drawimage();
52: use Apache::loncapamath();
53: use Apache::loncourseuser();
54: use Apache::grades();
55: use Apache::Constants qw(:common);
56: use Apache::loncommon();
57: use Apache::lonparmset();
58: use Apache::lonnavmaps();
59: use Apache::lonlocal;
60: use LONCAPA qw(:DEFAULT :match);
61: use LONCAPA::ltiutils();
62: use Time::HiRes qw( gettimeofday tv_interval );
63: use HTML::Entities();
64: use File::Copy();
65:
66: # FIXME - improve commenting
67:
68: my $registered_cleanup;
69:
70: BEGIN {
71: &Apache::lonxml::register_insert();
72: }
73:
74:
75: =pod
76:
77: =item set_bubble_lines()
78:
79: Called at analysis time to set the bubble lines
80: hash for the problem.. This should be called in the
81: end_problemtype tag in analysis mode.
82:
83: We fetch the hash of part id counters from lonxml
84: and push them into analyze:{part_id.bubble_lines}.
85:
86: =cut
87:
88: sub set_bubble_lines {
89: my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
90:
91: foreach my $key (keys(%bubble_counters)) {
92: $Apache::lonhomework::analyze{"$key.bubble_lines"} =
93: $bubble_counters{"$key"};
94: }
95: }
96:
97: #
98: # Decides what targets to render for.
99: # Implicit inputs:
100: # Various session environment variables:
101: # request.state - published - is a /res/ resource
102: # uploaded - is a /uploaded/ resource
103: # contruct - is a /priv/ resource
104: # form.grade_target - a form parameter requesting a specific target
105: sub get_target {
106: &Apache::lonxml::debug("request.state = $env{'request.state'}");
107: if( defined($env{'form.grade_target'})) {
108: &Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
109: } else {
110: &Apache::lonxml::debug("form.grade_target <undefined>");
111: }
112: if (($env{'request.state'} eq "published") ||
113: ($env{'request.state'} eq "uploaded")) {
114: if ( defined($env{'form.grade_target'} )
115: && ($env{'form.grade_target'} eq 'tex')) {
116: return ($env{'form.grade_target'});
117: } elsif ( defined($env{'form.grade_target'} )
118: && ($Apache::lonhomework::viewgrades eq 'F' )) {
119: return ($env{'form.grade_target'});
120: } elsif ( $env{'form.grade_target'} eq 'webgrade'
121: && ($Apache::lonhomework::queuegrade eq 'F' )) {
122: return ($env{'form.grade_target'});
123: } elsif ($env{'form.grade_target'} eq 'answer') {
124: if ($env{'form.answer_output_mode'} eq 'tex') {
125: return ($env{'form.grade_target'});
126: }
127: }
128: if ($env{'form.webgrade'} &&
129: ($Apache::lonhomework::modifygrades eq 'F'
130: || $Apache::lonhomework::queuegrade eq 'F' )) {
131: return ('grade','webgrade');
132: }
133: if ( defined($env{'form.submitted'}) &&
134: ( !defined($env{'form.newrandomization'}))) {
135: return ('grade', 'web');
136: } else {
137: return ('web');
138: }
139: } elsif ($env{'request.state'} eq "construct") {
140: #
141: # We are in construction space, editing and testing problems
142: #
143: if ( defined($env{'form.grade_target'}) ) {
144: return ($env{'form.grade_target'});
145: }
146: if ( defined($env{'form.preview'})) {
147: if ( defined($env{'form.submitted'})) {
148: #
149: # We are doing a problem preview
150: #
151: return ('grade', 'web');
152: } else {
153: return ('web');
154: }
155: } else {
156: if ($env{'form.problemstate'} eq 'WEB_GRADE') {
157: return ('grade','webgrade','answer');
158: } elsif ($env{'form.problemmode'} eq 'view') {
159: return ('grade','web','answer');
160: } elsif ($env{'form.problemmode'} eq 'saveview') {
161: return ('modified','web','answer');
162: } elsif ($env{'form.problemmode'} eq 'discard') {
163: return ('web','answer');
164: } elsif (($env{'form.problemmode'} eq 'saveedit') ||
165: ($env{'form.problemmode'} eq 'undo')) {
166: return ('modified','no_output_web','edit');
167: } elsif ($env{'form.problemmode'} eq 'edit') {
168: return ('no_output_web','edit');
169: } else {
170: return ('web');
171: }
172: }
173: #
174: # End of Authoring Space
175: #
176: }
177: #
178: # Huh? We are nowhere, so do nothing.
179: #
180: return ();
181: }
182:
183: sub setup_vars {
184: my ($target) = @_;
185: return ';'
186: # return ';$external::target='.$target.';';
187: }
188:
189: sub proctor_checked_in {
190: my ($slot_name,$slot,$type)=@_;
191: my @possible_proctors=split(",",$slot->{'proctor'});
192:
193: return 1 if (!@possible_proctors);
194:
195: my $key;
196: if ($type eq 'Task') {
197: my $version=$Apache::lonhomework::history{'resource.0.version'};
198: $key ="resource.$version.0.checkedin";
199: } elsif (($type eq 'problem') || ($type eq 'tool')) {
200: $key ='resource.0.checkedin';
201: }
202: # backward compatability, used to be username@domain,
203: # now is username:domain
204: my $who = $Apache::lonhomework::history{$key};
205: if ($who !~ /:/) {
206: $who =~ tr/@/:/;
207: }
208: foreach my $possible (@possible_proctors) {
209: if ($who eq $possible
210: && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
211: return 1;
212: }
213: }
214: return 0;
215: }
216:
217: sub check_slot_access {
218: my ($id,$type,$symb,$partlist)=@_;
219:
220: # does it pass normal muster
221: my ($status,$datemsg)=&check_access($id,$symb);
222:
223: my $useslots = &Apache::lonnet::EXT("resource.0.useslots",$symb);
224: if ($useslots ne 'resource' && $useslots ne 'map'
225: && $useslots ne 'map_map') {
226: return ($status,$datemsg);
227: }
228:
229: my $checkin = 'resource.0.checkedin';
230: my $version;
231: if ($type eq 'Task') {
232: $version=$Apache::lonhomework::history{'resource.version'};
233: $checkin = "resource.$version.0.checkedin";
234: }
235: my $checkedin = $Apache::lonhomework::history{$checkin};
236: my ($returned_slot,$slot_name,$checkinslot,$ipused,$blockip,$now,$ip,
237: $consumed_uniq);
238: $now = time;
239: $ip=$ENV{'REMOTE_ADDR'} || $env{'request.host'};
240:
241: if ($checkedin) {
242: $checkinslot = $Apache::lonhomework::history{"$checkin.slot"};
243: my %slot=&Apache::lonnet::get_slot($checkinslot);
244: $consumed_uniq = $slot{'uniqueperiod'};
245: if ($slot{'iptied'}) {
246: $ipused = $Apache::lonhomework::history{"$checkin.ip"};
247: unless (($ip ne '') &&
248: (($ipused eq $ip) || ($ENV{'REMOTE_ADDR'} eq '127.0.0.1'))) {
249: $blockip = $slot{'iptied'};
250: $slot_name = $checkinslot;
251: $returned_slot = \%slot;
252: }
253: }
254: }
255:
256: if ($status eq 'SHOW_ANSWER') {
257: if ($blockip eq 'answer') {
258: return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
259: } else {
260: return ($status,$datemsg);
261: }
262: }
263:
264: if ($status eq 'CLOSED' ||
265: $status eq 'INVALID_ACCESS' ||
266: $status eq 'UNAVAILABLE') {
267: return ($status,$datemsg);
268: }
269: if ($env{'request.state'} eq "construct") {
270: return ($status,$datemsg);
271: }
272:
273: if ($type eq 'Task') {
274: if ($checkedin &&
275: $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
276: if ($blockip eq 'answer') {
277: return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
278: } else {
279: return ('SHOW_ANSWER');
280: }
281: }
282: } elsif (($type eq 'problem') &&
283: ($Apache::lonhomework::browse eq 'F') &&
284: ($ENV{'REMOTE_ADDR'} eq '127.0.0.1') &&
285: ($env{'form.grade_courseid'} eq $env{'request.course.id'}) &&
286: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}))) {
287: return ($status,$datemsg);
288: }
289:
290: my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent",$symb);
291: my $available = &Apache::lonnet::EXT("resource.0.available",$symb);
292: my @slots= (split(':',$availablestudent),split(':',$available));
293:
294: # if (!@slots) {
295: # return ($status,$datemsg);
296: # }
297: undef($returned_slot);
298: undef($slot_name);
299: my $slotstatus='NOT_IN_A_SLOT';
300: my $num_usable_slots = 0;
301: if (!$symb) {
302: ($symb) = &Apache::lonnet::whichuser();
303: }
304: foreach my $slot (@slots) {
305: $slot =~ s/(^\s*|\s*$)//g;
306: &Apache::lonxml::debug("getting $slot");
307: my %slot=&Apache::lonnet::get_slot($slot);
308: &Apache::lonhomework::showhash(%slot);
309: next if ($slot{'endtime'} < $now);
310: $num_usable_slots ++;
311: if ($slot{'starttime'} < $now &&
312: $slot{'endtime'} > $now &&
313: &Apache::loncommon::check_ip_acc($slot{'ip'})) {
314: if ($slot{'iptied'}) {
315: if ($env{'request.course.id'}) {
316: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
317: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
318: if ($slot eq $checkinslot) {
319: if ($ip eq $ipused) {
320: &Apache::lonxml::debug("$slot is good");
321: $slotstatus ='NEEDS_CHECKIN';
322: } else {
323: $slotstatus = 'NEED_DIFFERENT_IP';
324: $slot_name = $slot;
325: $returned_slot = \%slot;
326: last;
327: }
328: } elsif ($ip) {
329: my $uniqkey = "$slot\0$symb\0$ip";
330: my %used_ip = &Apache::lonnet::get('slot_uniqueips',[$uniqkey],$cdom,$cnum);
331: if ($used_ip{$uniqkey}) {
332: $slotstatus = 'NEED_DIFFERENT_IP';
333: } else {
334: &Apache::lonxml::debug("$slot is good");
335: $slotstatus ='NEEDS_CHECKIN';
336: }
337: }
338: }
339: } else {
340: &Apache::lonxml::debug("$slot is good");
341: $slotstatus='NEEDS_CHECKIN';
342: }
343: if ($slotstatus eq 'NEEDS_CHECKIN') {
344: $returned_slot=\%slot;
345: $slot_name=$slot;
346: last;
347: }
348: }
349: }
350: if ($slotstatus eq 'NEEDS_CHECKIN' &&
351: &proctor_checked_in($slot_name,$returned_slot,$type)) {
352: &Apache::lonxml::debug("proctor checked in");
353: $slotstatus=$status;
354: }
355:
356: my ($is_correct,$got_grade);
357: if ($type eq 'Task') {
358: my $version=$Apache::lonhomework::history{'resource.0.version'};
359: $got_grade =
360: ($Apache::lonhomework::history{"resource.$version.0.status"}
361: =~ /^(?:pass|fail)$/);
362: $is_correct =
363: ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
364: || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
365: } elsif (($type eq 'problem') || ($type eq 'tool')) {
366: if ((ref($partlist) eq 'ARRAY') && (@{$partlist} > 0)) {
367: my ($numcorrect,$numgraded) = (0,0);
368: foreach my $part (@{$partlist}) {
369: my $currtries = $Apache::lonhomework::history{"resource.$part.tries"};
370: my $maxtries = &Apache::lonnet::EXT("resource.$part.maxtries",$symb);
371: my $probstatus = &Apache::structuretags::get_problem_status($part);
372: my $earlyout;
373: unless (($probstatus eq 'no') ||
374: ($probstatus eq 'no_feedback_ever')) {
375: if ($Apache::lonhomework::history{"resource.$part.solved"} =~/^correct_/) {
376: $numcorrect ++;
377: } else {
378: $earlyout = 1;
379: }
380: }
381: if ($currtries == $maxtries) {
382: $earlyout = 1;
383: } else {
384: $numgraded ++;
385: }
386: last if ($earlyout);
387: }
388: my $numparts = scalar(@{$partlist});
389: if ($numparts == $numcorrect) {
390: $is_correct = 1;
391: }
392: if ($numparts == $numgraded) {
393: $got_grade = 1;
394: }
395: } else {
396: my $currtries = $Apache::lonhomework::history{"resource.0.tries"};
397: my $maxtries = &Apache::lonnet::EXT("resource.0.maxtries",$symb);
398: my $probstatus = &Apache::structuretags::get_problem_status('0');
399: unless (($probstatus eq 'no') ||
400: ($probstatus eq 'no_feedback_ever')) {
401: $is_correct =
402: ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
403: }
404: unless (($currtries == $maxtries) || ($is_correct)) {
405: $got_grade = 1;
406: }
407: }
408: }
409:
410: &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
411:
412: # no slot is currently open, and has been checked in for this version
413: # but hasn't got a grade, therefore must be awaiting a grade
414: if (!defined($slot_name)
415: && $checkedin
416: && !$got_grade) {
417: return ('WAITING_FOR_GRADE');
418: }
419:
420: # Previously used slot is no longer open, and has been checked in for this version.
421: # However, the problem is not closed, and potentially, another slot might be
422: # used to gain access to it to work on it, until the due date is reached, and the
423: # problem then becomes CLOSED. Therefore return the slotstatus -
424: # (which will be one of: NOT_IN_A_SLOT, RESERVABLE, RESERVABLE_LATER, or NOTRESERVABLE).
425:
426: if (!defined($slot_name) && (($type eq 'problem') || ($type eq 'tool'))) {
427: if ($slotstatus eq 'NOT_IN_A_SLOT') {
428: if (!$num_usable_slots) {
429: ($slotstatus,$datemsg) = &check_reservable_slot($slotstatus,$symb,$now,$checkedin,
430: $consumed_uniq);
431: }
432: }
433: return ($slotstatus,$datemsg);
434: }
435:
436: if ($slotstatus eq 'NOT_IN_A_SLOT'
437: && $checkedin ) {
438:
439: if ($got_grade) {
440: if ($blockip eq 'answer') {
441: return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
442: } else {
443: return ('SHOW_ANSWER');
444: }
445: } else {
446: return ('WAITING_FOR_GRADE');
447: }
448:
449: }
450:
451: if (($is_correct) && ($blockip ne 'answer')) {
452: if (($type eq 'problem') || ($type eq 'tool')) {
453: return ($status);
454: }
455: return ('SHOW_ANSWER');
456: }
457:
458: if ( $status eq 'CANNOT_ANSWER' &&
459: ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT' &&
460: $slotstatus ne 'NEED_DIFFERENT_IP') ) {
461: return ($status,$datemsg);
462: }
463: return ($slotstatus,$datemsg,$slot_name,$returned_slot,$ipused);
464: }
465:
466: sub check_reservable_slot {
467: my ($slotstatus,$symb,$now,$checkedin,$consumed_uniq) = @_;
468: my $datemsg;
469: if ($slotstatus eq 'NOT_IN_A_SLOT') {
470: if ($env{'request.course.id'}) {
471: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
472: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
473: unless ($symb) {
474: ($symb)=&Apache::lonnet::whichuser();
475: }
476: $slotstatus = 'NOTRESERVABLE';
477: my ($reservable_now_order,$reservable_now,$reservable_future_order,
478: $reservable_future) =
479: &Apache::loncommon::get_future_slots($cnum,$cdom,$now,$symb);
480: if ((ref($reservable_now_order) eq 'ARRAY') && (ref($reservable_now) eq 'HASH')) {
481: if (@{$reservable_now_order} > 0) {
482: if ((!$checkedin) || (ref($consumed_uniq) ne 'ARRAY')) {
483: $slotstatus = 'RESERVABLE';
484: $datemsg = $reservable_now->{$reservable_now_order->[-1]}{'endreserve'};
485: } else {
486: my ($uniqstart,$uniqend,$useslot);
487: if (ref($consumed_uniq) eq 'ARRAY') {
488: ($uniqstart,$uniqend)=@{$consumed_uniq};
489: }
490: foreach my $slot (reverse(@{$reservable_now_order})) {
491: if ($reservable_now->{$slot}{'uniqueperiod'} =~ /^(\d+)\,(\d+)$/) {
492: my ($new_uniq_start,$new_uniq_end) = ($1,$2);
493: next if (!
494: ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
495: ($uniqstart > $new_uniq_end && $uniqend > $new_uniq_end ));
496: }
497: $useslot = $slot;
498: last;
499: }
500: if ($useslot) {
501: $slotstatus = 'RESERVABLE';
502: $datemsg = $reservable_now->{$useslot}{'endreserve'};
503: }
504: }
505: }
506: }
507: unless ($slotstatus eq 'RESERVABLE') {
508: if ((ref($reservable_future_order) eq 'ARRAY') && (ref($reservable_future) eq 'HASH')) {
509: if (@{$reservable_future_order} > 0) {
510: if ((!$checkedin) || (ref($consumed_uniq) ne 'ARRAY')) {
511: $slotstatus = 'RESERVABLE_LATER';
512: $datemsg = $reservable_future->{$reservable_future_order->[0]}{'startreserve'};
513: } else {
514: my ($uniqstart,$uniqend,$useslot);
515: if (ref($consumed_uniq) eq 'ARRAY') {
516: ($uniqstart,$uniqend)=@{$consumed_uniq};
517: }
518: foreach my $slot (@{$reservable_future_order}) {
519: if ($reservable_future->{$slot}{'uniqueperiod'} =~ /^(\d+),(\d+)$/) {
520: my ($new_uniq_start,$new_uniq_end) = ($1,$2);
521: next if (!
522: ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
523: ($uniqstart > $new_uniq_end && $uniqend > $new_uniq_end ));
524: }
525: $useslot = $slot;
526: last;
527: }
528: if ($useslot) {
529: $slotstatus = 'RESERVABLE_LATER';
530: $datemsg = $reservable_future->{$useslot}{'startreserve'};
531: }
532: }
533: }
534: }
535: }
536: }
537: }
538: return ($slotstatus,$datemsg);
539: }
540:
541: # JB, 9/24/2002: Any changes in this function may require a change
542: # in lonnavmaps::resource::getDateStatus.
543: sub check_access {
544: my ($id,$symb) = @_;
545: my $date ='';
546: my $status;
547: my $datemsg = '';
548: my $lastdate = '';
549: my $type;
550: my $passed;
551:
552: if ($env{'request.state'} eq "construct") {
553: if ($env{'form.problemstate'}) {
554: if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
555: if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct'
556: && &hide_problem_status())) {
557: return ('CANNOT_ANSWER',
558: &mt('is in this state due to author settings.'));
559: }
560: } else {
561: return ($env{'form.problemstate'},
562: &mt('is in this state due to author settings.'));
563: }
564: }
565: &Apache::lonxml::debug("in construction ignoring dates");
566: $status='CAN_ANSWER';
567: $datemsg=&mt('is in under construction');
568: # return ($status,$datemsg);
569: }
570:
571: &Apache::lonxml::debug("checking for part :$id:");
572: &Apache::lonxml::debug("time:".time);
573:
574: unless ($symb) {
575: ($symb)=&Apache::lonnet::whichuser();
576: }
577: &Apache::lonxml::debug("symb:".$symb);
578: #if ($env{'request.state'} ne "construct" && $symb ne '') {
579: if ($env{'request.state'} ne "construct") {
580: my $idacc = &Apache::lonnet::EXT("resource.$id.acc",$symb);
581: my $allowed=&Apache::loncommon::check_ip_acc($idacc);
582: if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
583: $status='INVALID_ACCESS';
584: $date=&mt("can not be accessed from your location.");
585: return($status,$date);
586: }
587: if ($env{'form.grade_imsexport'}) {
588: if (($env{'request.course.id'}) &&
589: (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
590: return ('SHOW_ANSWER');
591: }
592: }
593: foreach my $temp ("opendate","duedate","answerdate") {
594: $lastdate = $date;
595: if ($temp eq 'duedate') {
596: $date = &due_date($id,$symb);
597: } else {
598: $date = &Apache::lonnet::EXT("resource.$id.$temp",$symb);
599: }
600:
601: my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type",$symb);
602: if ($thistype =~ /^(con_lost|no_such_host)/ ||
603: $date =~ /^(con_lost|no_such_host)/) {
604: $status='UNAVAILABLE';
605: $date=&mt("may open later.");
606: return($status,$date);
607: }
608: if ($thistype eq 'date_interval') {
609: if ($temp eq 'opendate') {
610: $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)-$date;
611: }
612: if ($temp eq 'answerdate') {
613: $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)+$date;
614: }
615: }
616: &Apache::lonxml::debug("found :$date: for :$temp:");
617: if ($date eq '') {
618: $date = &mt("an unknown date"); $passed = 0;
619: } elsif ($date eq 'con_lost') {
620: $date = &mt("an indeterminate date"); $passed = 0;
621: } else {
622: if (time < $date) { $passed = 0; } else { $passed = 1; }
623: $date = &Apache::lonlocal::locallocaltime($date);
624: }
625: if (!$passed) { $type=$temp; last; }
626: }
627: &Apache::lonxml::debug("have :$type:$passed:");
628: if ($passed) {
629: $status='SHOW_ANSWER';
630: $datemsg=$date;
631: } elsif ($type eq 'opendate') {
632: $status='CLOSED';
633: $datemsg = &mt('will open on [_1]',$date);
634: } elsif ($type eq 'duedate') {
635: $status='CAN_ANSWER';
636: $datemsg = &mt('is due at [_1]',$date);
637: } elsif ($type eq 'answerdate') {
638: $status='CLOSED';
639: $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
640: $lastdate,$date);
641: }
642: }
643: if ($status eq 'CAN_ANSWER' ||
644: (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
645: #check #tries, and if correct.
646: my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
647: my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries",$symb);
648: if ( $tries eq '' ) { $tries = '0'; }
649: if ( $maxtries eq '' &&
650: $env{'request.state'} ne 'construct') { $maxtries = '2'; }
651: if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
652: # if (correct and show prob status) or excused then CANNOT_ANSWER
653: if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
654: && (&show_problem_status()) ) {
655: if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
656: (&Apache::lonnet::EXT("resource.$id.retrypartial",$symb) !~/^1|on|yes$/i)) {
657: $status = 'CANNOT_ANSWER';
658: }
659: } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
660: $status = 'CANNOT_ANSWER';
661: }
662: if ($status eq 'CANNOT_ANSWER'
663: && &show_answer_problem_status()) {
664: $status = 'SHOW_ANSWER';
665: }
666: }
667: if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
668: my @interval=&Apache::lonnet::EXT("resource.$id.interval",$symb);
669: &Apache::lonxml::debug("looking for interval @interval");
670: if ($interval[0]=~ /^\d+/) {
671: my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
672: &Apache::lonxml::debug("looking for accesstime $first_access");
673: if (!$first_access) {
674: $status='NOT_YET_VIEWED';
675: my $due_date = &due_date($id,$symb);
676: my $seconds_left = $due_date - time;
677: my ($timelimit) = ($interval[0] =~ /^(\d+)/);
678: if ($seconds_left > $timelimit || $due_date eq '') {
679: $seconds_left = $timelimit;
680: }
681: $datemsg=&seconds_to_human_length($seconds_left);
682: }
683: }
684: }
685:
686: #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
687: # (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
688: # return ('UNCHECKEDOUT','needs to be checked out');
689: #}
690:
691: &Apache::lonxml::debug("sending back :$status:$datemsg:");
692: if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
693: &Apache::lonxml::debug("should be allowed to browse a resource when closed");
694: $status='CAN_ANSWER';
695: $datemsg=&mt('is closed but you are allowed to view it');
696: }
697:
698: return ($status,$datemsg);
699: }
700: # this should work exactly like the copy in lonnavmaps.pm
701: sub due_date {
702: my ($part_id,$symb,$udom,$uname)=@_;
703: my $date;
704: my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
705: $udom,$uname);
706: &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
707: my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
708: $udom,$uname);
709: &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
710: if ($interval[0] =~ /\d+/) {
711: my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
712: &Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
713: if (defined($first_access)) {
714: my ($timelimit) = ($interval[0] =~ /^(\d+)/);
715: my $interval = $first_access+$timelimit;
716: $date = (!$due_date || $interval < $due_date) ? $interval
717: : $due_date;
718: } else {
719: $date = $due_date;
720: }
721: } else {
722: $date = $due_date;
723: }
724: return $date;
725: }
726:
727: sub seconds_to_human_length {
728: my ($length)=@_;
729:
730: my $seconds=$length%60; $length=int($length/60);
731: my $minutes=$length%60; $length=int($length/60);
732: my $hours=$length%24; $length=int($length/24);
733: my $days=$length;
734:
735: my $timestr;
736: if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
737: if ($hours > 0) { $timestr.=($timestr?", ":"").
738: &mt('[quant,_1,hour]',$hours); }
739: if ($minutes > 0) { $timestr.=($timestr?", ":"").
740: &mt('[quant,_1,minute]',$minutes); }
741: if ($seconds > 0) { $timestr.=($timestr?", ":"").
742: &mt('[quant,_1,second]',$seconds); }
743: return $timestr;
744: }
745:
746: sub showhash {
747: my (%hash) = @_;
748: &showhashsubset(\%hash,'.');
749: return '';
750: }
751:
752: sub showarray {
753: my ($array)=@_;
754: my $string="(";
755: foreach my $elm (@{ $array }) {
756: if (ref($elm) eq 'ARRAY') {
757: $string.=&showarray($elm);
758: } elsif (ref($elm) eq 'HASH') {
759: $string.= "HASH --- \n<br />";
760: $string.= &showhashsubset($elm,'.');
761: } else {
762: $string.="$elm,"
763: }
764: }
765: chop($string);
766: $string.=")";
767: return $string;
768: }
769:
770: sub showhashsubset {
771: my ($hash,$keyre) = @_;
772: my $resultkey;
773: foreach $resultkey (sort(keys(%$hash))) {
774: if ($resultkey !~ /$keyre/) { next; }
775: if (ref($$hash{$resultkey}) eq 'ARRAY' ) {
776: &Apache::lonxml::debug("$resultkey ---- ".
777: &showarray($$hash{$resultkey}));
778: } elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
779: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
780: &showhashsubset($$hash{$resultkey},'.');
781: } else {
782: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
783: }
784: }
785: &Apache::lonxml::debug("\n<br />restored values^</br>\n");
786: return '';
787: }
788:
789: sub setuppermissions {
790: $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
791: unless ($Apache::lonhomework::browse eq 'F') {
792: $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'});
793: }
794: my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
795: if (! $viewgrades &&
796: exists($env{'request.course.sec'}) &&
797: $env{'request.course.sec'} !~ /^\s*$/) {
798: $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
799: '/'.$env{'request.course.sec'});
800: if ($viewgrades) {
801: $Apache::lonhomework::viewgradessec = $env{'request.course.sec'};
802: }
803: }
804: $Apache::lonhomework::viewgrades = $viewgrades;
805:
806: if ($Apache::lonhomework::browse eq 'F' &&
807: $env{'form.devalidatecourseresdata'} eq 'on') {
808: my (undef,$courseid) = &Apache::lonnet::whichuser();
809: &Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
810: $env{"course.$courseid.domain"});
811: }
812:
813: my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
814: if (! $modifygrades &&
815: exists($env{'request.course.sec'}) &&
816: $env{'request.course.sec'} !~ /^\s*$/) {
817: $modifygrades =
818: &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
819: '/'.$env{'request.course.sec'});
820: if ($modifygrades) {
821: $Apache::lonhomework::modifygradessec = $env{'request.course.sec'};
822: }
823: }
824: $Apache::lonhomework::modifygrades = $modifygrades;
825:
826: my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
827: if (! $queuegrade &&
828: exists($env{'request.course.sec'}) &&
829: $env{'request.course.sec'} !~ /^\s*$/) {
830: $queuegrade =
831: &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
832: '/'.$env{'request.course.sec'});
833: }
834: $Apache::lonhomework::queuegrade = $queuegrade;
835: return '';
836: }
837:
838: sub unset_permissions {
839: undef($Apache::lonhomework::queuegrade);
840: undef($Apache::lonhomework::modifygrades);
841: undef($Apache::lonhomework::modifygradessec);
842: undef($Apache::lonhomework::viewgrades);
843: undef($Apache::lonhomework::viewgradessec);
844: undef($Apache::lonhomework::browse);
845: }
846:
847: sub setupheader {
848: my $request=$_[0];
849: &Apache::loncommon::content_type($request,'text/html');
850: if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
851: &Apache::loncommon::no_cache($request);
852: }
853: # $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
854: # 'lastrevisiondate'));
855: $request->send_http_header;
856: return OK if $request->header_only;
857: return ''
858: }
859:
860: sub handle_save_or_undo {
861: my ($request,$problem,$result,$getobjref) = @_;
862:
863: my $file = &Apache::lonnet::filelocation("",$request->uri);
864: my $filebak =$file.".bak";
865: my $filetmp =$file.".tmp";
866: my $error=0;
867: if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
868: my $error=0;
869: if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
870: if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
871: if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
872: if (!$error) {
873: &Apache::lonxml::info("<p><b>".
874: &mt("Undid changes, Switched [_1] and [_2]",
875: '<span class="LC_filename">'.$filebak.
876: '</span>',
877: '<span class="LC_filename">'.$file.
878: '</span>')."</b></p>");
879: } else {
880: &Apache::lonxml::info("<p><span class=\"LC_error\">".
881: &mt("Unable to undo, unable to switch [_1] and [_2]",
882: '<span class="LC_filename">'.
883: $filebak.'</span>',
884: '<span class="LC_filename">'.
885: $file.'</span>')."</span></p>");
886: $error=1;
887: }
888: } else {
889: &Apache::lonnet::correct_line_ends($result);
890:
891: my $fs=Apache::File->new(">$filebak");
892: if (defined($fs)) {
893: print $fs $$problem;
894: } else {
895: &Apache::lonxml::info("<span class=\"LC_error\">".
896: &mt("Unable to make backup [_1]",
897: '<span class="LC_filename">'.
898: $filebak.'</span>')."</span>");
899: $error=2;
900: }
901: my $fh=Apache::File->new(">$file");
902: if (defined($fh)) {
903: print $fh $$result;
904: if (ref($getobjref) eq 'SCALAR') {
905: if ($file =~ m{([^/]+)\.(html?)$}) {
906: my $fname = $1;
907: my $ext = $2;
908: my $path = $file;
909: $path =~ s/\Q$fname\E\.\Q$ext\E$//;
910: my (%allfiles,%codebase);
911: &Apache::lonnet::extract_embedded_items($file,\%allfiles,
912: \%codebase,$result);
913: if (keys(%allfiles) > 0) {
914: my $url = $request->uri;
915: my $state = <<STATE;
916: <input type="hidden" name="action" value="upload_embedded" />
917: <input type="hidden" name="url" value="$url" />
918: STATE
919: $$getobjref = "<h3>".&mt("Reference Warning")."</h3>".
920: "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
921: "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
922: &Apache::loncommon::ask_for_embedded_content($url,$state,\%allfiles,\%codebase,
923: {'error_on_invalid_names' => 1,
924: 'ignore_remote_references' => 1,});
925: }
926: }
927: }
928: } else {
929: &Apache::lonxml::info('<span class="LC_error">'.
930: &mt("Unable to write to [_1]",
931: '<span class="LC_filename">'.
932: $file.'</span>').
933: '</span>');
934: $error|=4;
935: }
936: }
937: return $error;
938: }
939:
940: sub analyze_header {
941: my ($request) = @_;
942: my $js = &Apache::structuretags::setmode_javascript();
943:
944: # Breadcrumbs
945: my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
946: 'text' => 'Authoring Space'},
947: {'href' => '',
948: 'text' => 'Problem Testing'},
949: {'href' => '',
950: 'text' => 'Analyzing a problem'}];
951:
952: my $result =
953: &Apache::loncommon::start_page('Analyzing a problem',
954: $js,
955: {'bread_crumbs' => $brcrum,})
956: .&Apache::loncommon::head_subbox(
957: &Apache::loncommon::CSTR_pageheader());
958: $result .=
959: '<form name="lonhomework" method="post" action="'.
960: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
961: '<input type="hidden" name="problemmode" value="'.
962: $env{'form.problemmode'}.'" />'.
963: &Apache::structuretags::remember_problem_state().'
964: <div class="LC_edit_problem_analyze_header">
965: <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
966: 'onclick="javascript:setmode(this.form,'."'editxml'".')" />
967: <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
968: 'onclick="javascript:setmode(this.form,'."'edit'".')" />
969: <hr />
970: <input type="button" name="submitmode" value="'.&mt("View").'" '.
971: 'onclick="javascript:setmode(this.form,'."'view'".')" />
972: <hr />
973: </div>'
974: .&Apache::lonxml::message_location().
975: '</form>';
976: &Apache::lonxml::add_messages(\$result);
977: $request->print($result);
978: $request->rflush();
979: }
980:
981: sub analyze_footer {
982: my ($request) = @_;
983: $request->print(&Apache::loncommon::end_page());
984: $request->rflush();
985: }
986:
987: sub analyze {
988: my ($request,$file) = @_;
989: &Apache::lonxml::debug("Analyze");
990: my $result;
991: my %overall;
992: my %seedexample;
993: my %allparts;
994: my $rndseed=$env{'form.rndseed'};
995: &analyze_header($request);
996: my %prog_state=
997: &Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
998: for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
999: &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
1000: if (&Apache::loncommon::connection_aborted($request)) { return; }
1001: my $thisseed=$i+$rndseed;
1002: my $subresult=&Apache::lonnet::ssi($request->uri,
1003: ('grade_target' => 'analyze'),
1004: ('rndseed' => $thisseed));
1005: (my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
1006: my %analyze=&Apache::lonnet::str2hash($subresult);
1007: my @parts;
1008: if (ref($analyze{'parts'}) eq 'ARRAY') {
1009: @parts=@{ $analyze{'parts'} };
1010: }
1011: foreach my $part (@parts) {
1012: if (!exists($allparts{$part})) {$allparts{$part}=1;};
1013: if ($analyze{$part.'.type'} eq 'numericalresponse' ||
1014: $analyze{$part.'.type'} eq 'stringresponse' ||
1015: $analyze{$part.'.type'} eq 'formularesponse' ) {
1016: foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
1017: my $i=0;
1018: foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
1019: push( @{ $overall{$part.'.answer'}[$i] },
1020: $answer_part);
1021: my $concatanswer= join("\0",@{ $answer_part });
1022: if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
1023: $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
1024: }
1025: $seedexample{join("\0",$part,$i,@{$answer_part})}=
1026: $thisseed;
1027: $i++;
1028: }
1029: }
1030: if (!keys(%{ $analyze{$part.'.answer'} })) {
1031: my $answer_part =
1032: ['<span class="LC_error">'.&mt('Error').'</span>'];
1033: $seedexample{join("\0",$part,0,@{$answer_part})}=
1034: $thisseed;
1035: push( @{ $overall{$part.'.answer'}[0] },
1036: $answer_part);
1037: }
1038: }
1039: }
1040: }
1041: &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
1042: $request->print('<hr />'
1043: .'<h3>'
1044: .&mt('List of possible answers')
1045: .'</h3>'
1046: );
1047: foreach my $part (sort(keys(%allparts))) {
1048: if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
1049: (@{$overall{$part.'.answer'}} > 0)) {
1050: for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
1051: my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
1052: $request->print(&Apache::loncommon::start_data_table()
1053: .&Apache::loncommon::start_data_table_header_row()
1054: .'<th colspan="'.($num_cols+1).'">'
1055: .&mt('Part').' '.$part
1056: );
1057: if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
1058: $request->print(' '.&mt('Answer [_1]',$i+1));
1059: }
1060: $request->print('</th>'
1061: .&Apache::loncommon::end_data_table_header_row()
1062: );
1063: my %frequency;
1064: foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
1065: $frequency{join("\0",@{ $answer })}++;
1066: }
1067: $request->print(&Apache::loncommon::start_data_table_header_row()
1068: .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
1069: .'<th>'.&mt('Frequency').'<br />'
1070: .'('.&mt('click for example').')</th>'
1071: .&Apache::loncommon::end_data_table_header_row()
1072: );
1073: foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
1074: $request->print(&Apache::loncommon::start_data_table_row()
1075: .'<td>'
1076: .join('</td><td>',split("\0",$answer))
1077: .'</td>'
1078: .'<td>'
1079: .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
1080: .'</td>'
1081: .&Apache::loncommon::end_data_table_row()
1082: );
1083: }
1084: $request->print(&Apache::loncommon::end_data_table());
1085: }
1086: } else {
1087: $request->print('<p class="LC_warning">'
1088: .&mt('Response [_1] is not analyzable at this time.',$part)
1089: .'</p>'
1090: );
1091: }
1092: }
1093: if (scalar(keys(%allparts)) == 0 ) {
1094: $request->print('<p class="LC_warning">'
1095: .&mt('Found no analyzable responses in this problem.'
1096: .' Currently only Numerical, Formula and String response styles are supported.')
1097: .'</p>'
1098: );
1099: }
1100: &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
1101: &analyze_footer($request);
1102: &Apache::lonhomework::showhash(%overall);
1103: return $result;
1104: }
1105:
1106: {
1107: my $show_problem_status;
1108: sub reset_show_problem_status {
1109: undef($show_problem_status);
1110: }
1111:
1112: sub set_show_problem_status {
1113: my ($new_status) = @_;
1114: $show_problem_status = lc($new_status);
1115: }
1116:
1117: sub hide_problem_status {
1118: return ($show_problem_status eq 'no'
1119: || $show_problem_status eq 'no_feedback_ever');
1120: }
1121:
1122: sub show_problem_status {
1123: return ($show_problem_status eq 'yes'
1124: || $show_problem_status eq 'answer'
1125: || $show_problem_status eq '');
1126: }
1127:
1128: sub show_some_problem_status {
1129: return ($show_problem_status eq 'no');
1130: }
1131:
1132: sub show_no_problem_status {
1133: return ($show_problem_status eq 'no_feedback_ever');
1134: }
1135:
1136: sub show_answer_problem_status {
1137: return ($show_problem_status eq 'answer');
1138: }
1139: }
1140:
1141: sub editxmlmode {
1142: my ($request,$file) = @_;
1143: my $result;
1144: my $problem=&Apache::lonnet::getfile($file);
1145: if ($problem eq -1) {
1146: &Apache::lonxml::error(
1147: '<p class="LC_error">'
1148: .&mt('Unable to find [_1]',
1149: '<span class="LC_filename">'.$file.'</span>')
1150: .'</p>');
1151:
1152: $problem='';
1153: }
1154: if (($env{'form.problemmode'} eq 'saveeditxml') ||
1155: ($env{'form.problemmode'} eq 'saveviewxml') ||
1156: ($env{'form.problemmode'} eq 'undoxml')) {
1157: my $error=&handle_save_or_undo($request,\$problem,
1158: \$env{'form.editxmltext'});
1159: if (!$error) { $problem=&Apache::lonnet::getfile($file); }
1160: }
1161: &Apache::lonhomework::showhashsubset(\%env,'^form');
1162: if ($env{'form.problemmode'} eq 'saveviewxml') {
1163: &Apache::lonhomework::showhashsubset(\%env,'^form');
1164: $env{'form.problemmode'}='view';
1165: &renderpage($request,$file);
1166: } else {
1167: my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
1168: if ($cols > 80) { $cols = 80; }
1169: if ($cols < 70) { $cols = 70; }
1170: if ($rows < 20) { $rows = 20; }
1171: my $js =
1172: &Apache::edit::js_change_detection().
1173: &Apache::loncommon::resize_textarea_js().
1174: &Apache::structuretags::setmode_javascript().
1175: &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
1176:
1177: # Breadcrumbs
1178: my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1179: 'text' => 'Authoring Space'},
1180: {'href' => '',
1181: 'text' => 'Problem Editing'}];
1182:
1183: my $start_page =
1184: &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
1185: {'no_auto_mt_title' => 1,
1186: 'only_body' => 0,
1187: 'add_entries' => {
1188: 'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
1189: 'onload' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
1190: },
1191: 'bread_crumbs' => $brcrum,
1192: });
1193:
1194: $result=$start_page
1195: .&Apache::loncommon::head_subbox(
1196: &Apache::loncommon::CSTR_pageheader());
1197: $result.=&renderpage($request,$file,['no_output_web'],1).
1198: '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
1199: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1200: &Apache::structuretags::remember_problem_state().'
1201: <div class="LC_edit_problem_header">
1202: <div class="LC_edit_problem_header_title">'.
1203: &mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').
1204: '</div><div class="LC_edit_actionbar" id="actionbar">';
1205:
1206: $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
1207: &Apache::structuretags::problem_edit_buttons('editxml');
1208: $result.='<div>';
1209:
1210: $result .= '<ol class="LC_primary_menu" style="display:inline-block;font-size:90%;vertical-align:middle;">';
1211:
1212: unless ($env{'environment.nocodemirror'}) {
1213: # dropdown menus
1214: $result .= Apache::lonmenu::create_submenu("#", "",
1215: &mt("Problem Templates"), template_dropdown_datastructure());
1216:
1217: $result .= Apache::lonmenu::create_submenu("#", "",
1218: &mt("Response Types"), responseblock_dropdown_datastructure());
1219:
1220: $result .= Apache::lonmenu::create_submenu("#", "",
1221: &mt("Conditional Blocks"), conditional_scripting_datastructure());
1222:
1223: $result .= Apache::lonmenu::create_submenu("#", "",
1224: &mt("Miscellaneous"), misc_datastructure());
1225: }
1226:
1227: $result .= Apache::lonmenu::create_submenu("#", "",
1228: &mt("Help") . ' <img src="/adm/help/help.png" alt="' . &mt("Help") .
1229: '" style="vertical-align:text-bottom; height: auto; margin:0; "/>',
1230: helpmenu_datastructure(),"");
1231:
1232: $result.="</ol></div>";
1233:
1234: $result .= '</div></div>' .
1235: &Apache::lonxml::message_location() .
1236: &Apache::loncommon::xmleditor_js() .
1237: '<textarea ' . &Apache::edit::element_change_detection() .
1238: ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" ' .
1239: ' name="editxmltext" id="LC_editxmltext">' .
1240: &HTML::Entities::encode($problem,'<>&"') .
1241: '</textarea> <div id="LC_aftertextarea"> </div> </form>';
1242:
1243: my $resource = $env{'request.ambiguous'};
1244: unless($env{'environment.nocodemirror'}){
1245: $result .= '<link rel="stylesheet" href="/adm/codemirror/codemirror-combined-xml.css">
1246: <script src="/adm/codemirror/codemirror-compressed-xml.js"></script>
1247: <script>
1248: CodeMirror.defineMode("mixedmode", function(config) {
1249: return CodeMirror.multiplexingMode(
1250: CodeMirror.getMode(config, "xml"),
1251: {
1252: open: "\<script type=\"loncapa/perl\"\>", close: "\</script\>",
1253: mode: CodeMirror.getMode(config, "perl"),
1254: delimStyle: "tag",
1255: }
1256: );
1257: });
1258: var cm = CodeMirror.fromTextArea(document.getElementById("LC_editxmltext"),
1259: {
1260: mode: "mixedmode",
1261: lineWrapping: true,
1262: lineNumbers: true,
1263: tabSize: 4,
1264: indentUnit: 4,
1265:
1266: autoCloseTags: true,
1267: autoCloseBrackets: true,
1268: height: "auto",
1269: styleActiveLine: true,
1270:
1271: extraKeys: {
1272: "Tab": "indentMore",
1273: "Shift-Tab": "indentLess",
1274: }
1275: });
1276: restoreScrollPosition("'.$resource.'");
1277: </script>';
1278: }
1279:
1280: $result .= &Apache::loncommon::end_page();
1281: &Apache::lonxml::add_messages(\$result);
1282: $request->print($result);
1283: }
1284: return '';
1285: }
1286:
1287: #
1288: # Render the page in whatever target desired.
1289: #
1290: sub renderpage {
1291: my ($request,$file,$targets,$return_string,$donebuttonmsg,$viewasuser,$symb) = @_;
1292:
1293: my @targets = @{$targets || [&get_target()]};
1294: &Apache::lonhomework::showhashsubset(\%env,'form.');
1295: &Apache::lonxml::debug("Running targets ".join(':',@targets));
1296:
1297: my $overall_result;
1298: foreach my $target (@targets) {
1299: # FIXME need to do something intelligent when a problem goes
1300: # from viewable to not viewable due to map conditions
1301: #&setuppermissions();
1302: #if ( $Apache::lonhomework::browse ne '2'
1303: # && $Apache::lonhomework::browse ne 'F' ) {
1304: # $request->print(" You most likely shouldn't see me.");
1305: #}
1306: #my $t0 = [&gettimeofday()];
1307: my $output=1;
1308: if ($target eq 'no_output_web') {
1309: $target = 'web'; $output=0;
1310: }
1311: my $problem=&Apache::lonnet::getfile($file);
1312: my $result;
1313: if ($problem eq -1) {
1314: $problem='';
1315: my $filename=(split('/',$file))[-1];
1316: my $error =
1317: '<p class="LC_error">'
1318: .&mt('Unable to find [_1]',
1319: '<span class="LC_filename">'.$filename.'</span>')
1320: ."</p>";
1321: $result.=
1322: &Apache::loncommon::simple_error_page($request,'Not available',
1323: $error,{'no_auto_mt_msg' => 1});
1324: return;
1325: }
1326:
1327: my %mystyle;
1328: if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
1329: if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
1330: if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
1331:
1332: if (($target eq 'web') && ($viewasuser ne '') && ($symb ne '')) {
1333: $env{'request.user_in_effect'} = $viewasuser;
1334: }
1335:
1336: &Apache::lonxml::debug("Should be parsing now");
1337: $result .= &Apache::lonxml::xmlparse($request, $target, $problem,
1338: &setup_vars($target),%mystyle);
1339: &finished_parsing();
1340: if (!$output) { $result = ''; }
1341: #$request->print("Result follows:");
1342: if ($target eq 'modified') {
1343: &handle_save_or_undo($request,\$problem,\$result);
1344: } else {
1345: if ($target eq 'analyze') {
1346: $result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
1347: undef(%Apache::lonhomework::analyze);
1348: } elsif ($target eq 'web') {
1349: if ($donebuttonmsg) {
1350: $result =~ s{</body>}{};
1351: $result.= &Apache::loncommon::confirmwrapper(&Apache::lonhtmlcommon::confirm_success($donebuttonmsg,1))."\n</body>";
1352: }
1353: }
1354: #my $td=&tv_interval($t0);
1355: #if ( $Apache::lonxml::debug) {
1356: #$result =~ s:</body>::;
1357: #$result.="<br />Spent $td seconds processing target $target\n</body>";
1358: #}
1359: # $request->print($result);
1360: $overall_result.=$result;
1361: if (($target eq 'web') && ($viewasuser ne '') && ($symb ne '')) {
1362: my ($vuname,$vudom) = split(/:/,$viewasuser);
1363: $overall_result .= &Apache::grades::view_as_user($symb,$vuname,$vudom).
1364: '</body></html>';
1365: }
1366: # $request->rflush();
1367: }
1368: if (($target eq 'web') && ($viewasuser ne '') && ($symb ne '')) {
1369: undef($env{'request.user_in_effect'});
1370: }
1371: #$request->print(":Result ends");
1372: #my $td=&tv_interval($t0);
1373: }
1374: if (!$return_string) {
1375: &Apache::lonxml::add_messages(\$overall_result);
1376: $request->print($overall_result);
1377: $request->rflush();
1378: } else {
1379: return $overall_result;
1380: }
1381: }
1382:
1383: sub finished_parsing {
1384: undef($Apache::lonhomework::parsing_a_problem);
1385: undef($Apache::lonhomework::parsing_a_task);
1386: }
1387:
1388: # function extracted from get_template_html
1389: # returns "key" -> list
1390: # key: path of template
1391: # value 1: title
1392: # value 2: category
1393: # value 3: name of help topic ???
1394: sub get_template_list{
1395: my ($extension) = @_;
1396:
1397: my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
1398: '/templates/*.'.$extension);
1399: @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
1400: (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
1401: &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
1402: @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
1403: return @files;
1404: }
1405:
1406: sub get_template_html {
1407: my ($extension) = @_;
1408: my $result;
1409: my @allnames;
1410: &Apache::lonxml::debug("Looking for :$extension:");
1411: my $glob_extension = $extension;
1412: if ($extension eq 'survey' || $extension eq 'exam') {
1413: $glob_extension = 'problem';
1414: }
1415: my @files = &get_template_list($extension);
1416: my ($midpoint,$seconddiv,$numfiles);
1417: my @noexamplelink = ('blank.problem','blank.library','script.library');
1418: $numfiles = 0;
1419: foreach my $file (@files) {
1420: next if ($file->[1] !~ /\S/);
1421: $numfiles ++;
1422: }
1423: if ($numfiles > 0) {
1424: $result = '<div class="LC_left_float">';
1425: $midpoint = int($numfiles/2);
1426: if ($numfiles%2) {
1427: $midpoint ++;
1428: }
1429: }
1430: my $count = 0;
1431: my $currentcategory='';
1432: my $first = 1;
1433: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1434: foreach my $file (@files) {
1435: next if ($file->[1] !~ /\S/);
1436: if ($file->[2] ne $currentcategory) {
1437: $currentcategory=$file->[2];
1438: if ((!$seconddiv) && ($count >= $midpoint)) {
1439: $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
1440: $seconddiv = 1;
1441: } elsif (!$first) {
1442: $result.='</div>'."\n";
1443: } else {
1444: $first = 0;
1445: }
1446: $result.= '<div class="LC_Box">'."\n"
1447: .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
1448: $count++;
1449: }
1450: $result .=
1451: '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
1452: $file->[1].'</label>';
1453: if ($file->[3]) {
1454: $result.=&Apache::loncommon::help_open_topic($file->[3]);
1455: }
1456: # Provide example link
1457: my $filename=$file->[0];
1458: $filename=~s{^\Q$londocroot\E}{};
1459: if (!(grep($filename =~ /\Q$_\E$/,@noexamplelink))) {
1460: $result .= ' <span class="LC_fontsize_small">'
1461: .&Apache::loncommon::modal_link(
1462: $filename.'?inhibitmenu=yes',&mt('Example'),600,420,'sample')
1463: .'</span>';
1464: }
1465: $result .= '<br />'."\n";
1466: $count ++;
1467: }
1468: if ($numfiles > 0) {
1469: $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
1470: }
1471: return $result;
1472: }
1473:
1474: sub newproblem {
1475: my ($request) = @_;
1476:
1477: if ($env{'form.mode'} eq 'blank'){
1478: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1479: my $templatefilename =
1480: $request->dir_config('lonIncludes').'/templates/blank.problem';
1481: &File::Copy::copy($templatefilename,$dest);
1482: &renderpage($request,$dest);
1483: return;
1484: }
1485: my $errormsg;
1486: if ($env{'form.template'}) {
1487: my $file;
1488: my ($extension) = ($env{'form.template'} =~ /\.(\w+)$/);
1489: if ($extension) {
1490: my @files = &get_template_list($extension);
1491: foreach my $poss (@files) {
1492: if (ref($poss) eq 'ARRAY') {
1493: if ($env{'form.template'} eq $poss->[0]) {
1494: $file = $env{'form.template'};
1495: last;
1496: }
1497: }
1498: }
1499: if ($file) {
1500: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1501: &File::Copy::copy($file,$dest);
1502: &renderpage($request,$dest);
1503: return;
1504: } else {
1505: $errormsg = '<p class="LC_error">'.&mt('Invalid template file.').'</p>';
1506: }
1507: } else {
1508: $errormsg = '<p class="LC_error">'.&mt('Invalid template file; template needs to be a .problem, .library, or .task file.').'</p>';
1509: }
1510: }
1511:
1512: my ($extension) = ($request->uri =~ m/\.(\w+)$/);
1513: &Apache::lonxml::debug("Looking for :$extension:");
1514: my $templatelist=&get_template_html($extension);
1515: if ($env{'form.newfile'} && !$templatelist) {
1516: # no templates found
1517: my $templatefilename =
1518: $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
1519: &Apache::lonxml::debug("$templatefilename");
1520: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1521: &File::Copy::copy($templatefilename,$dest);
1522: &renderpage($request,$dest);
1523: } else {
1524: my $url=&HTML::Entities::encode($request->uri,'<>&"');
1525: my $dest = &Apache::lonnet::filelocation("",$request->uri);
1526: my $instructions;
1527: my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1528: 'text' => 'Authoring Space'},
1529: {'href' => '',
1530: 'text' => "Create New $extension"}];
1531: my $start_page =
1532: &Apache::loncommon::start_page("Create New $extension",
1533: undef,
1534: {'bread_crumbs' => $brcrum,});
1535: $request->print(
1536: $start_page
1537: .&Apache::loncommon::head_subbox(
1538: &Apache::loncommon::CSTR_pageheader())
1539: .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
1540: $errormsg
1541: ".&mt("The requested file [_1] currently does not exist.",
1542: '<span class="LC_filename">'.$url.'</span>').'
1543: <p class="LC_info">
1544: '.&mt("To create a new $extension, select a template from the".
1545: " list below. Then click on the \"Create $extension\" button.").'
1546: </p><div><form action="'.$url.'" method="post">');
1547:
1548: if (defined($templatelist)) {
1549: $request->print($templatelist);
1550: }
1551: $request->print('<br /><input type="submit" name="newfile" value="'.
1552: &mt("Create $extension").'" />');
1553: $request->print('</form></div>'.&Apache::loncommon::end_page());
1554: }
1555: return;
1556: }
1557:
1558: sub update_construct_style {
1559: if ($env{'request.state'} eq "construct"
1560: && $env{'form.problemmode'} eq 'view'
1561: && defined($env{'form.submitted'})
1562: && !defined($env{'form.resetdata'})
1563: && !defined($env{'form.newrandomization'})) {
1564: if ((!$env{'form.style_file'} && $env{'construct.style'})
1565: ||$env{'form.clear_style_file'}) {
1566: &Apache::lonnet::delenv('construct.style');
1567: } elsif ($env{'form.style_file'}
1568: && $env{'construct.style'} ne $env{'form.style_file'}) {
1569: &Apache::lonnet::appenv({'construct.style' =>
1570: $env{'form.style_file'}});
1571: }
1572: }
1573: }
1574:
1575: #
1576: # Sets interval for current user so time left will be zero, either for the entire folder
1577: # containing the current resource, or just the resource, depending on value of first item
1578: # in interval array retrieved from EXT("resource.0.interval");
1579: #
1580: sub zero_timer {
1581: my ($symb) = @_;
1582: my ($hastimeleft,$first_access,$now);
1583: my @interval=&Apache::lonnet::EXT("resource.0.interval",$symb);
1584: if (@interval > 1) {
1585: if ($interval[1] eq 'course') {
1586: return ('fail',&mt('Ending of timed events not supported for intervals set course-wide'));
1587: } else {
1588: my $now = time;
1589: my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
1590: if ($first_access > 0) {
1591: my ($timelimit,$donesuffix) = split(/_/,$interval[0],2);
1592: if ($donesuffix =~ /^done(?:|\:[^\:]+\:)(.*)$/) {
1593: my ($dummy,$proctor,$secret) = split(/_/,$1);
1594: if (($proctor) && ($secret ne '')) {
1595: my $key = $env{'form.LC_interval_done_proctorpass'};
1596: $key =~ s/^\s+//;
1597: $key =~ s/\s+$//;
1598: if ($env{'form.LC_interval_done_proctorpass'} ne $secret) {
1599: return ('fail',
1600: &mt('Incorrect key entered by proctor'));
1601: }
1602: }
1603: if ($first_access+$timelimit > $now) {
1604: my $done_time = $now - $first_access;
1605: my $snum = 1;
1606: if ($interval[1] eq 'map') {
1607: $snum = 2;
1608: }
1609: my $result =
1610: &Apache::lonparmset::storeparm_by_symb_inner($symb,'0_interval',
1611: $snum,$done_time,
1612: 'date_interval',
1613: $env{'user.name'},
1614: $env{'user.domain'});
1615: if ($result eq '') {
1616: # Record action in "User Notes"
1617: &Apache::lonmsg::store_instructor_comment(
1618: 'Pressed Done button for symb:<br />'.$symb,
1619: $env{'user.name'}, $env{'user.domain'});
1620: return ('ok');
1621: } else {
1622: return ('fail',&mt('Error ending timed event: [_1]',$result));
1623: }
1624: } else {
1625: return ('fail',&mt('Timed event already ended'));
1626: }
1627: } else {
1628: return ('fail',&mt('Timed event can not be ended before the time limit'));
1629: }
1630: } else {
1631: return ('fail',&mt('Timer not yet started for this timed event'));
1632: }
1633: }
1634: } else {
1635: return ('fail',&mt('No timer in use'));
1636: }
1637: return();
1638: }
1639:
1640: sub handler {
1641: #my $t0 = [&gettimeofday()];
1642: my $request=$_[0];
1643:
1644: $Apache::lonxml::request=$request;
1645: $Apache::lonxml::debug=$env{'user.debug'};
1646: $env{'request.uri'}=$request->uri;
1647: &setuppermissions();
1648:
1649: my $file=&Apache::lonnet::filelocation("",$request->uri);
1650:
1651: #check if we know where we are
1652: if ($env{'request.course.fn'} && !&Apache::lonnet::symbread('','',1,1)) {
1653: # if we are browsing we might not be able to know where we are
1654: if ($Apache::lonhomework::browse ne 'F' &&
1655: $env{'request.state'} ne "construct") {
1656: #should know where we are, so ask
1657: &unset_permissions();
1658: $request->internal_redirect('/adm/ambiguous');
1659: return OK;
1660: }
1661: }
1662: if (&setupheader($request)) {
1663: &unset_permissions();
1664: return OK;
1665: }
1666:
1667: &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1668: &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1669: my ($symb) = &Apache::lonnet::whichuser();
1670: &Apache::lonxml::debug('symb is '.$symb);
1671: if ($env{'request.state'} eq "construct") {
1672: if ( -e $file ) {
1673: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1674: ['problemmode']);
1675: if (!(defined $env{'form.problemmode'})) {
1676: #first visit to problem in construction space
1677: $env{'form.problemmode'}= 'view';
1678: &renderpage($request,$file);
1679: } elsif (($env{'form.problemmode'} eq 'editxml') ||
1680: ($env{'form.problemmode'} eq 'saveeditxml') ||
1681: ($env{'form.problemmode'} eq 'saveviewxml') ||
1682: ($env{'form.problemmode'} eq 'undoxml')) {
1683: &editxmlmode($request,$file);
1684: } elsif ($env{'form.problemmode'} eq 'calcanswers') {
1685: &analyze($request,$file);
1686: } else {
1687: &update_construct_style();
1688: &renderpage($request,$file);
1689: }
1690: } else {
1691: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1692: ['mode']);
1693: # requested file doesn't exist in contruction space
1694: &newproblem($request);
1695: }
1696: } else {
1697: # Set the event timer to zero if the "done button" was clicked. The button is
1698: # part of the doneButton form created in lonmenu.pm
1699: my ($donebuttonresult,$donemsg,$viewasuser);
1700: if ($symb && $env{'form.LC_interval_done'} eq 'true') {
1701: ($donebuttonresult,$donemsg) = &zero_timer($symb);
1702: undef($env{'form.LC_interval_done'});
1703: undef($env{'form.LC_interval_done_proctorpass'});
1704: }
1705: if (($env{'form.LC_viewas'} ne '') && $symb && $env{'request.course.id'} &&
1706: ($Apache::lonhomework::viewgrades || $Apache::lonhomework::modifygrades)) {
1707: if ($env{'form.LC_viewas'} =~ /^($match_username):($match_domain)$/) {
1708: my ($possuname,$possudom) = ($1,$2);
1709: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
1710: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1711: my ($canview,$posssec);
1712: if ($env{'request.course.sec'} ne '') {
1713: if ($Apache::lonhomework::modifygradessec eq $env{'request.course.sec'}) {
1714: $canview = 'section';
1715: $posssec = $env{'request.course.sec'};
1716: } elsif ($Apache::lonhomework::viewgradessec eq $env{'request.course.sec'}) {
1717: $canview = 'section';
1718: $posssec = $env{'request.course.sec'};
1719: }
1720: }
1721: my $crstype = &Apache::loncommon::course_type();
1722: if (&Apache::loncourseuser::is_course_user($possudom,$possuname,$cdom,$cnum,
1723: $canview,$crstype,$posssec)) {
1724: $viewasuser = $possuname.':'.$possudom;
1725: }
1726: }
1727: undef($env{'form.LC_viewas'});
1728: }
1729: # just render the page normally outside of construction space
1730: &Apache::lonxml::debug("not construct");
1731: undef(@Apache::lonhomework::ltipassback);
1732: &renderpage($request,$file,undef,undef,$donemsg,$viewasuser,$symb);
1733: if (@Apache::lonhomework::ltipassback) {
1734: unless ($registered_cleanup) {
1735: my $handlers = $request->get_handlers('PerlCleanupHandler');
1736: $request->set_handlers('PerlCleanupHandler' =>
1737: [\&do_ltipassback,@{$handlers}]);
1738: }
1739: }
1740: }
1741: #my $td=&tv_interval($t0);
1742: #&Apache::lonxml::debug("Spent $td seconds processing");
1743: # always turn off debug messages
1744: $Apache::lonxml::debug=0;
1745: &unset_permissions();
1746: return OK;
1747:
1748: }
1749:
1750: sub template_dropdown_datastructure {
1751: # gathering the all templates and their path, title, category and help topic
1752: my @templates = get_template_list('problem');
1753: # template category => title
1754: my %tmplthash = ();
1755: # template title => path
1756: my %tmpltcontent = ();
1757:
1758: foreach my $template (@templates){
1759: # put in hash if the template is not empty
1760: unless ($template->[1] eq ''){
1761: push(@{$tmplthash{$template->[2]}}, $template->[1]);
1762: push(@{$tmpltcontent{$template->[1]}},$template->[0]);
1763: }
1764: }
1765:
1766: my $catList = [];
1767: foreach my $cat (sort keys %tmplthash) {
1768: my $catItems = [];
1769: foreach my $title (sort @{$tmplthash{$cat}}) {
1770: my $path = $tmpltcontent{$title}->[0];
1771: my $code;
1772: open(FH, "<$path");
1773: while(<FH>){
1774: $code.= $_ unless $_ =~ /(<problem>)|(<\/problem>)/;
1775: }
1776: close(FH);
1777:
1778: if ($code ne '') {
1779: my $href = 'javascript:insertText(\'' . &convert_for_js(&HTML::Entities::encode($code,'<>&"')) . '\')';
1780: my $currItem = [$href, $title, undef];
1781: push @{$catItems}, $currItem;
1782: }
1783: }
1784: push @{$catList}, [$catItems, $cat, undef];
1785: }
1786:
1787: return $catList;
1788: }
1789:
1790: sub responseblock_dropdown_datastructure {
1791:
1792: my $mathCat = [
1793: [
1794: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_formularesponse())) . "\')", &mt("Formula Response"), undef],
1795: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_functionplotresponse())) . "\')", &mt("Function Plot Response"), undef],
1796: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_mathresponse())) . "\')", &mt("Math Response"), undef],
1797: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_numericalresponse())) . "\')", &mt("Numerical Response"), undef]
1798: ],
1799: &mt("Math"),
1800: undef
1801: ];
1802:
1803: my $miscCat = [
1804: [
1805: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_imageresponse())) . "\')", &mt("Click on Image"), undef],
1806: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_customresponse())) . "\')", &mt("Custom Response"), undef],
1807: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_externalresponse())) . "\')", &mt("External Response"), undef],
1808: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_matchresponse())) . "\')", &mt("Match Two Lists"), undef],
1809: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_radiobuttonresponse())) . "\')", &mt("One out of N statements"), undef],
1810: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_optionresponse())) . "\')", &mt("Select from Options"), undef],
1811: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_rankresponse())) . "\')", &mt("Rank Values"), undef]
1812: ],
1813: &mt("Miscellaneous"),
1814: undef
1815: ];
1816:
1817: my $chemCat = [
1818: [
1819: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_reactionresponse())) . "\')", &mt("Chemical Reaction"), undef],
1820: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicresponse())) . "\')", &mt("Organic Chemical Structure"), undef]
1821: ],
1822: &mt("Chemistry"),
1823: undef
1824: ];
1825:
1826: my $textCat = [
1827: [
1828: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_stringresponse())) . "\')", &mt("String Response"), undef],
1829: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_essayresponse())) . "\')", &mt("Essay"), undef]
1830: ],
1831: &mt("Text"),
1832: undef
1833: ];
1834:
1835: return [$mathCat, $miscCat, $chemCat, $textCat];
1836: }
1837:
1838:
1839: sub conditional_scripting_datastructure {
1840: # TODO: corresponding routines should be used for the javascript:insertText parts
1841: # instead of the placeholder routine default_xml_tag with the tags
1842: # e.g. &default_xml_tag("postanswerdate") should be replaced with a routine which
1843: # returns the corresponding content for this case
1844:
1845: #TODO translated is currently temporarily here, another solution should be found where the
1846: # needed string can be retrieved
1847:
1848: my $translatedTag = '
1849: <translated>
1850: <lang which="en"></lang>
1851: <lang which="default"></lang>
1852: </translated>';
1853: return [
1854: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode($translatedTag)) . "\')", &mt("Translated Block"), undef],
1855: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("block"))) . "\')", &mt("Conditional Block"), undef],
1856: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("postanswerdate"))) . "\')", &mt("After Answer Date Block"), undef],
1857: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("preduedate"))) . "\')", &mt("Before Due Date Block"), undef],
1858: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("solved"))) . "\')", &mt("Block For After Solved"), undef],
1859: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("notsolved"))) . "\')", &mt("Block For When Not Solved"), undef]
1860: ];
1861: }
1862:
1863: sub misc_datastructure {
1864: return [
1865: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_img())) . "\')", &mt("Image"), undef],
1866: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::lonplot::insert_gnuplot())) . "\')", &mt("GNU Plot"), undef],
1867: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicstructure())) . "\')", &mt("Organic Structure"), undef],
1868: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_script())) . "\')", &mt("Script Block"), undef],
1869: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("allow"))) . "\')", &mt("File Dependencies"), undef],
1870: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("import"))) . "\')", &mt("Import a File"), undef],
1871: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::londefdef::insert_meta())) . "\')", &mt("Custom Metadata"), undef],
1872: ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("part"))) . "\')", &mt("Problem Part"), undef]
1873: ];
1874: }
1875:
1876: # helper routine for the datastructure building subroutines
1877: sub default_xml_tag {
1878: my ($tag) = @_;
1879: return "\n<$tag></$tag>";
1880: }
1881:
1882:
1883: sub helpmenu_datastructure {
1884:
1885: # filename, title, width, height
1886: my $helpers = [
1887: ['Problem_LON-CAPA_Functions.hlp', &mt('Script Functions'), 800, 600],
1888: ['Greek_Symbols.hlp', &mt('Greek Symbols'), 500, 600],
1889: ['Other_Symbols.hlp', &mt('Other Symbols'), 500, 600],
1890: ['Authoring_Output_Tags.hlp', &mt('Output Tags'), 800, 600],
1891: ['Authoring_Multilingual_Problems.hlp',
1892: &mt('How to create problems in different languages'), 800, 600],
1893: ['loncapa.html', &mt('Language reference'), 800, 600],
1894: ];
1895:
1896: my $help_structure = [];
1897:
1898: foreach my $count (0..(scalar(@{$helpers})-1)) {
1899: my $filename = $helpers->[$count]->[0];
1900: my $title = $helpers->[$count]->[1];
1901: my $width = $helpers->[$count]->[2];
1902: my $height = $helpers->[$count]->[3];
1903: if ($width eq '') {
1904: $width = 500;
1905: }
1906: if ($height eq '') {
1907: $height = 600;
1908: }
1909: my $href = &HTML::Entities::encode("javascript:openMyModal('/adm/help/$filename',$width,$height,'yes');");
1910: push @{$help_structure}, [$href, $title, undef];
1911: }
1912:
1913: return $help_structure;
1914: }
1915:
1916: # we need substitution to not break javascript code
1917: sub convert_for_js {
1918: my $return = shift;
1919: $return =~ s|script|ESCAPEDSCRIPT|g;
1920: $return =~ s|\\|\\\\|g;
1921: $return =~ s|\n|\\r\\n|g;
1922: $return =~ s|'|\\'|g;
1923: $return =~ s|'|\\'|g;
1924: return $return;
1925: }
1926:
1927: sub do_ltipassback {
1928: if (@Apache::lonhomework::ltipassback) {
1929: foreach my $item (@Apache::lonhomework::ltipassback) {
1930: if (ref($item) eq 'HASH') {
1931: if ((ref($item->{'lti'}) eq 'HASH') && ($item->{'cid'} =~ /^($match_domain)_($match_courseid)$/)) {
1932: my ($cdom,$cnum) = ($1,$2);
1933: my $msgformat = $item->{'lti'}->{'passbackformat'};
1934: my $sigmethod = 'HMAC-SHA1';
1935: my $ltinum = $item->{'ltinum'};
1936: my $id = $item->{'pbid'};
1937: my $url = $item->{'pburl'};
1938: my $type = $item->{'pbtype'};
1939: my $scope = $item->{'scope'};
1940: my $map = $item->{'ltimap'};
1941: my $symb = $item->{'ltisymb'};
1942: my $uname = $item->{'uname'};
1943: my $udom = $item->{'udom'};
1944: my $keynum = $item->{'lti'}->{'cipher'};
1945: my $crsdef = $item->{'crsdef'};
1946: my $scoretype = $item->{'format'};
1947: my ($total,$possible);
1948: if ($scope eq 'resource') {
1949: $total = $item->{'total'};
1950: $possible = $item->{'possible'};
1951: } elsif ($scope eq 'map') {
1952: ($total,$possible) = &get_lti_score($uname,$udom,$map);
1953: } elsif ($scope eq 'course') {
1954: ($total,$possible) = &get_lti_score($uname,$udom);
1955: }
1956: if (($id ne '') && ($url ne '') && ($possible)) {
1957: &LONCAPA::ltiutils::send_grade($cdom,$cnum,$crsdef,$type,$ltinum,$keynum,$id,$url,$scoretype,$sigmethod,$msgformat,$total,$possible);
1958: }
1959: }
1960: }
1961: }
1962: undef(@Apache::lonhomework::ltipassback);
1963: }
1964: }
1965:
1966: sub get_lti_score {
1967: my ($uname,$udom,$mapurl) = @_;
1968: my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom);
1969: if (ref($navmap)) {
1970: my $iterator;
1971: if ($mapurl ne '') {
1972: my $map = $navmap->getResourceByUrl($mapurl);
1973: my $firstres = $map->map_start();
1974: my $finishres = $map->map_finish();
1975: $iterator = $navmap->getIterator($firstres,$finishres,undef,1);
1976: } else {
1977: $iterator = $navmap->getIterator(undef,undef,undef,1);
1978: }
1979: if (ref($iterator)) {
1980: my $depth = 1;
1981: my $total = 0;
1982: my $possible = 0;
1983: $iterator->next(); # ignore first BEGIN_MAP
1984: my $curRes = $iterator->next();
1985: while ( $depth > 0 ) {
1986: if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
1987: if ($curRes == $iterator->END_MAP()) { $depth--; }
1988: if (ref($curRes) && $curRes->is_gradable() && !$curRes->randomout) {
1989: my $parts = $curRes->parts();
1990: foreach my $part (@{$parts}) {
1991: next if ($curRes->solved($part) eq 'excused');
1992: $total += $curRes->weight($part) * $curRes->awarded($part);
1993: $possible += $curRes->weight($part);
1994: }
1995: }
1996: $curRes = $iterator->next();
1997: }
1998: if ($total > $possible) {
1999: $total = $possible;
2000: }
2001: return ($total,$possible);
2002: }
2003: }
2004: return;
2005: }
2006:
2007: 1;
2008: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>