File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.344.2.10.4.4: download - view: text, annotated - select for diffs
Fri Dec 29 23:45:18 2023 UTC (4 months, 3 weeks ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.344.2.10: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.381

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

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