File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.373: download - view: text, annotated - select for diffs
Tue Sep 18 14:30:19 2018 UTC (5 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  Args expected by ltiutils::send_grade changed in ltiutils rev. 1.15

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

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