File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.366: download - view: text, annotated - select for diffs
Tue Sep 20 19:28:08 2016 UTC (7 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Display error message.

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

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