File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.370: download - view: text, annotated - select for diffs
Wed Jan 31 15:28:28 2018 UTC (6 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Consumer
  Support for access control using slots for both "gradable" and "non-gradable"
  external tools.

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

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