File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.344.2.4: download - view: text, annotated - select for diffs
Mon Aug 8 12:07:20 2016 UTC (7 years, 9 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.344: preferred, unified
- For 2.11
  - Backport 1.356.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Homework handler
    3: #
    4: # $Id: lonhomework.pm,v 1.344.2.4 2016/08/08 12:07:20 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::Constants qw(:common);
   53: use Apache::loncommon();
   54: use Apache::lonlocal;
   55: use Time::HiRes qw( gettimeofday tv_interval );
   56: use HTML::Entities();
   57: use File::Copy();
   58: 
   59: # FIXME - improve commenting
   60: 
   61: 
   62: BEGIN {
   63:     &Apache::lonxml::register_insert();
   64: }
   65: 
   66: 
   67: =pod
   68: 
   69: =item set_bubble_lines()
   70: 
   71: Called at analysis time to set the bubble lines
   72: hash for the problem.. This should be called in the
   73: end_problemtype tag in analysis mode.
   74: 
   75: We fetch the hash of part id counters from lonxml
   76:     and push them into analyze:{part_id.bubble_lines}.
   77: 
   78: =cut
   79: 
   80: sub set_bubble_lines {
   81:     my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
   82: 
   83:     foreach my $key (keys(%bubble_counters)) {
   84: 	$Apache::lonhomework::analyze{"$key.bubble_lines"} =
   85: 	    $bubble_counters{"$key"};
   86:     }
   87: }
   88: 
   89: #
   90: # Decides what targets to render for.
   91: # Implicit inputs:
   92: #   Various session environment variables:
   93: #      request.state -  published  - is a /res/ resource
   94: #                       uploaded   - is a /uploaded/ resource
   95: #                       contruct   - is a /priv/ resource
   96: #      form.grade_target - a form parameter requesting a specific target
   97: sub get_target {
   98:     &Apache::lonxml::debug("request.state = $env{'request.state'}");
   99:     if( defined($env{'form.grade_target'})) {
  100: 	&Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
  101:     } else {
  102: 	&Apache::lonxml::debug("form.grade_target <undefined>");
  103:     }
  104:     if (($env{'request.state'} eq "published") ||
  105: 	($env{'request.state'} eq "uploaded")) {
  106: 	if ( defined($env{'form.grade_target'}  ) 
  107: 	     && ($env{'form.grade_target'} eq 'tex')) {
  108: 	    return ($env{'form.grade_target'});
  109: 	} elsif ( defined($env{'form.grade_target'}  ) 
  110: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
  111: 	    return ($env{'form.grade_target'});
  112: 	} elsif ( $env{'form.grade_target'} eq 'webgrade'
  113: 		  && ($Apache::lonhomework::queuegrade eq 'F' )) {
  114: 	    return ($env{'form.grade_target'});
  115: 	} elsif ($env{'form.grade_target'} eq 'answer') {
  116:             if ($env{'form.answer_output_mode'} eq 'tex') {
  117:                 return ($env{'form.grade_target'});
  118:             }
  119:         }
  120: 	if ($env{'form.webgrade'} &&
  121: 	    ($Apache::lonhomework::modifygrades eq 'F'
  122: 	     || $Apache::lonhomework::queuegrade eq 'F' )) {
  123: 	    return ('grade','webgrade');
  124: 	}
  125: 	if ( defined($env{'form.submitted'}) &&
  126: 	     ( !defined($env{'form.newrandomization'}))) {
  127: 	    return ('grade', 'web');
  128: 	} else {
  129: 	    return ('web');
  130: 	}
  131:     } elsif ($env{'request.state'} eq "construct") {
  132: #
  133: # We are in construction space, editing and testing problems
  134: #
  135: 	if ( defined($env{'form.grade_target'}) ) {
  136: 	    return ($env{'form.grade_target'});
  137: 	}
  138: 	if ( defined($env{'form.preview'})) {
  139: 	    if ( defined($env{'form.submitted'})) {
  140: #
  141: # We are doing a problem preview
  142: #
  143: 		return ('grade', 'web');
  144: 	    } else {
  145: 		return ('web');
  146: 	    }
  147: 	} else {
  148: 	    if ($env{'form.problemstate'} eq 'WEB_GRADE') {
  149: 		return ('grade','webgrade','answer');
  150:             } elsif ($env{'form.problemmode'} eq 'view') {
  151:                 return ('grade','web','answer');
  152: 	    } elsif ($env{'form.problemmode'} eq 'saveview') {
  153:                 return ('modified','web','answer');
  154:             } elsif ($env{'form.problemmode'} eq 'discard') {
  155:                 return ('web','answer');
  156:             } elsif (($env{'form.problemmode'} eq 'saveedit') ||
  157:                      ($env{'form.problemmode'} eq 'undo')) {
  158:                 return ('modified','no_output_web','edit');
  159:             } elsif ($env{'form.problemmode'} eq 'edit') {
  160: 		return ('no_output_web','edit');
  161: 	    } else {
  162: 		return ('web');
  163: 	    }
  164:         }
  165: #
  166: # End of Authoring Space
  167: #
  168:     }
  169: #
  170: # Huh? We are nowhere, so do nothing.
  171: #
  172:     return ();
  173: }
  174: 
  175: sub setup_vars {
  176:     my ($target) = @_;
  177:     return ';'
  178: #  return ';$external::target='.$target.';';
  179: }
  180: 
  181: sub proctor_checked_in {
  182:     my ($slot_name,$slot,$type)=@_;
  183:     my @possible_proctors=split(",",$slot->{'proctor'});
  184:     
  185:     return 1 if (!@possible_proctors);
  186: 
  187:     my $key;
  188:     if ($type eq 'Task') {
  189: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
  190: 	$key ="resource.$version.0.checkedin";
  191:     } elsif ($type eq 'problem') {
  192: 	$key ='resource.0.checkedin';
  193:     }
  194:     # backward compatability, used to be username@domain, 
  195:     # now is username:domain
  196:     my $who = $Apache::lonhomework::history{$key};
  197:     if ($who !~ /:/) {
  198: 	$who =~ tr/@/:/;
  199:     }     
  200:     foreach my $possible (@possible_proctors) { 
  201: 	if ($who eq $possible
  202: 	    && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
  203: 	    return 1;
  204: 	}
  205:     }
  206:     
  207:     return 0;
  208: }
  209: 
  210: sub check_slot_access {
  211:     my ($id,$type,$symb,$partlist)=@_;
  212: 
  213:     # does it pass normal muster
  214:     my ($status,$datemsg)=&check_access($id,$symb);
  215:     
  216:     my $useslots = &Apache::lonnet::EXT("resource.0.useslots",$symb);
  217:     if ($useslots ne 'resource' && $useslots ne 'map' 
  218: 	&& $useslots ne 'map_map') {
  219: 	return ($status,$datemsg);
  220:     }
  221: 
  222:     if ($status eq 'SHOW_ANSWER' ||
  223: 	$status eq 'CLOSED' ||
  224: 	$status eq 'INVALID_ACCESS' ||
  225: 	$status eq 'UNAVAILABLE') {
  226: 	return ($status,$datemsg);
  227:     }
  228:     if ($env{'request.state'} eq "construct") {
  229: 	return ($status,$datemsg);
  230:     }
  231:     
  232:     if ($type eq 'Task') {
  233: 	my $version=$Apache::lonhomework::history{'resource.version'};
  234: 	if ($Apache::lonhomework::history{"resource.$version.0.checkedin"} &&
  235: 	    $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
  236: 	    return ('SHOW_ANSWER');
  237: 	}
  238:     }
  239: 
  240:     my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent",$symb);
  241:     my $available = &Apache::lonnet::EXT("resource.0.available",$symb);
  242:     my @slots= (split(':',$availablestudent),split(':',$available));
  243: 
  244: #    if (!@slots) {
  245: #	return ($status,$datemsg);
  246: #    }
  247:     my $slotstatus='NOT_IN_A_SLOT';
  248:     my ($returned_slot,$slot_name);
  249:     my $now = time;
  250:     my $num_usable_slots = 0;
  251:     unless ($symb) {
  252:         ($symb) = &Apache::lonnet::whichuser();
  253:     }
  254:     foreach my $slot (@slots) {
  255: 	$slot =~ s/(^\s*|\s*$)//g;
  256: 	&Apache::lonxml::debug("getting $slot");
  257: 	my %slot=&Apache::lonnet::get_slot($slot);
  258: 	&Apache::lonhomework::showhash(%slot);
  259:         next if ($slot{'endtime'} < $now);
  260:         $num_usable_slots ++;
  261: 	if ($slot{'starttime'} < $now &&
  262: 	    $slot{'endtime'} > $now &&
  263: 	    &Apache::loncommon::check_ip_acc($slot{'ip'})) {
  264: 	    &Apache::lonxml::debug("$slot is good");
  265: 	    $slotstatus='NEEDS_CHECKIN';
  266: 	    $returned_slot=\%slot;
  267: 	    $slot_name=$slot;
  268: 	    last;
  269:         } 
  270:     }
  271:     if ($slotstatus eq 'NEEDS_CHECKIN' &&
  272: 	&proctor_checked_in($slot_name,$returned_slot,$type)) {
  273: 	&Apache::lonxml::debug("proctor checked in");
  274: 	$slotstatus=$status;
  275:     }
  276: 
  277:     my ($is_correct,$got_grade,$checkin,$checkinslot,$checkedin,$consumed_uniq);
  278:     if ($type eq 'Task') {
  279: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
  280:         $checkin = "resource.$version.0.checkedin";
  281: 	$got_grade = 
  282: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} 
  283: 	     =~ /^(?:pass|fail)$/);
  284: 	$is_correct =  
  285: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
  286: 	     || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
  287: 	$checkedin =
  288: 	    $Apache::lonhomework::history{"resource.$version.0.checkedin"};
  289:     } elsif ($type eq 'problem') {
  290:         $checkin = 'resource.0.checkedin';
  291: 	$checkedin  = $Apache::lonhomework::history{$checkin};
  292:     }
  293:     if ($checkedin) {
  294:         $checkinslot = $Apache::lonhomework::history{"$checkin.slot"};
  295:         my %slot=&Apache::lonnet::get_slot($checkinslot);
  296:         $consumed_uniq = $slot{'uniqueperiod'};
  297:     }
  298:     if ($type eq 'problem') {
  299:         if ((ref($partlist) eq 'ARRAY') && (@{$partlist} > 0)) {
  300:             my ($numcorrect,$numgraded) = (0,0);
  301:             foreach my $part (@{$partlist}) {
  302:                 my $currtries = $Apache::lonhomework::history{"resource.$part.tries"};
  303:                 my $maxtries = &Apache::lonnet::EXT("resource.$part.maxtries",$symb);
  304:                 my $probstatus = &Apache::structuretags::get_problem_status($part);
  305:                 my $earlyout;
  306:                 unless (($probstatus eq 'no') ||
  307:                         ($probstatus eq 'no_feedback_ever')) {
  308:                     if ($Apache::lonhomework::history{"resource.$part.solved"} =~/^correct_/) {
  309:                         $numcorrect ++;
  310:                     } else {
  311:                         $earlyout = 1;
  312:                     }
  313:                 }
  314:                 if (($currtries == $maxtries) || ($is_correct)) {
  315:                     $earlyout = 1;
  316:                 } else {
  317:                     $numgraded ++;
  318:                 }
  319:                 last if ($earlyout);
  320:             }
  321:             my $numparts = scalar(@{$partlist});
  322:             if ($numparts == $numcorrect) {
  323:                 $is_correct = 1;
  324:             }
  325:             if ($numparts == $numgraded) {
  326:                 $got_grade = 1;
  327:             }
  328:         } else {
  329:             my $currtries = $Apache::lonhomework::history{"resource.0.tries"};
  330:             my $maxtries = &Apache::lonnet::EXT("resource.0.maxtries",$symb);
  331:             my $probstatus = &Apache::structuretags::get_problem_status('0');
  332:             unless (($probstatus eq 'no') ||
  333:                     ($probstatus eq 'no_feedback_ever')) {
  334:                 $is_correct =
  335:                     ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
  336:             }
  337:             unless (($currtries == $maxtries) || ($is_correct)) {
  338:                 $got_grade = 1;
  339:             }
  340:         }
  341:     }
  342:     
  343:     &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
  344:     
  345:     # no slot is currently open, and has been checked in for this version
  346:     # but hasn't got a grade, therefore must be awaiting a grade
  347:     if (!defined($slot_name)
  348: 	&& $checkedin 
  349: 	&& !$got_grade) {
  350: 	return ('WAITING_FOR_GRADE');
  351:     }
  352: 
  353:     # Previously used slot is no longer open, and has been checked in for this version.
  354:     # However, the problem is not closed, and potentially, another slot might be
  355:     # used to gain access to it to work on it, until the due date is reached, and the
  356:     # problem then becomes CLOSED.  Therefore return the slotstatus - 
  357:     # (which will be one of: NOT_IN_A_SLOT, RESERVABLE, RESERVABLE_LATER, or NOTRESERVABLE.
  358:     if (!defined($slot_name) && $type eq 'problem') {
  359:         if ($slotstatus eq 'NOT_IN_A_SLOT') {
  360:             if (!$num_usable_slots) {
  361:                 if ($env{'request.course.id'}) {
  362:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  363:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  364:                     $slotstatus = 'NOTRESERVABLE';
  365:                     my ($reservable_now_order,$reservable_now,$reservable_future_order,
  366:                         $reservable_future) = 
  367:                         &Apache::loncommon::get_future_slots($cnum,$cdom,$now,$symb);
  368:                     if ((ref($reservable_now_order) eq 'ARRAY') && (ref($reservable_now) eq 'HASH')) {
  369:                         if (@{$reservable_now_order} > 0) {
  370:                             if ((!$checkedin) || (ref($consumed_uniq) ne 'ARRAY')) {
  371:                                 $slotstatus = 'RESERVABLE';
  372:                                 $datemsg = $reservable_now->{$reservable_now_order->[-1]}{'endreserve'};
  373:                             } else {
  374:                                 my ($uniqstart,$uniqend,$useslot);
  375:                                 if (ref($consumed_uniq) eq 'ARRAY') {
  376:                                     ($uniqstart,$uniqend)=@{$consumed_uniq};
  377:                                 }
  378:                                 foreach my $slot (reverse(@{$reservable_now_order})) {
  379:                                     if ($reservable_now->{$slot}{'uniqueperiod'} =~ /^(\d+)\,(\d+)$/) {
  380:                                         my ($new_uniq_start,$new_uniq_end) = ($1,$2);
  381:                                         next if (!
  382:                                             ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
  383:                                             ($uniqstart > $new_uniq_end   &&  $uniqend > $new_uniq_end  ));
  384:                                     }
  385:                                     $useslot = $slot;
  386:                                     last;
  387:                                 }
  388:                                 if ($useslot) {
  389:                                     $slotstatus = 'RESERVABLE';
  390:                                     $datemsg = $reservable_now->{$useslot}{'endreserve'};
  391:                                 }
  392:                             }
  393:                         }
  394:                     }
  395:                     unless ($slotstatus eq 'RESERVABLE') {
  396:                         if ((ref($reservable_future_order) eq 'ARRAY') && (ref($reservable_future) eq 'HASH')) {
  397:                             if (@{$reservable_future_order} > 0) {
  398:                                 if ((!$checkedin) || (ref($consumed_uniq) ne 'ARRAY')) {
  399:                                     $slotstatus = 'RESERVABLE_LATER';
  400:                                     $datemsg = $reservable_future->{$reservable_future_order->[0]}{'startreserve'};
  401:                                 } else {
  402:                                     my ($uniqstart,$uniqend,$useslot);
  403:                                     if (ref($consumed_uniq) eq 'ARRAY') {
  404:                                         ($uniqstart,$uniqend)=@{$consumed_uniq};
  405:                                     }
  406:                                     foreach my $slot (@{$reservable_future_order}) {
  407:                                         if ($reservable_future->{$slot}{'uniqueperiod'} =~ /^(\d+),(\d+)$/) {
  408:                                             my ($new_uniq_start,$new_uniq_end) = ($1,$2);
  409:                                             next if (!
  410:                                                ($uniqstart < $new_uniq_start && $uniqend < $new_uniq_start) ||
  411:                                                ($uniqstart > $new_uniq_end   &&  $uniqend > $new_uniq_end  ));
  412:                                         }
  413:                                         $useslot = $slot;
  414:                                         last;
  415:                                     }
  416:                                     if ($useslot) {
  417:                                         $slotstatus = 'RESERVABLE_LATER';
  418:                                         $datemsg = $reservable_future->{$useslot}{'startreserve'};
  419:                                     }
  420:                                 }
  421:                             }
  422:                         }
  423:                     }
  424:                 }
  425:             }
  426:         }
  427:         return ($slotstatus,$datemsg);
  428:     }
  429: 
  430:     if ($slotstatus eq 'NOT_IN_A_SLOT' 
  431: 	&& $checkedin ) {
  432: 
  433: 	if ($got_grade) {
  434: 	    return ('SHOW_ANSWER');
  435: 	} else {
  436: 	    return ('WAITING_FOR_GRADE');
  437: 	}
  438: 
  439:     }
  440: 
  441:     if ( $is_correct) {
  442: 	if ($type eq 'problem') {
  443: 	    return ($status);
  444: 	}
  445: 	return ('SHOW_ANSWER');
  446:     }
  447: 
  448:     if ( $status eq 'CANNOT_ANSWER' && 
  449: 	 ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
  450: 	return ($status,$datemsg);
  451:     }
  452: 
  453:     return ($slotstatus,$datemsg,$slot_name,$returned_slot);
  454: }
  455: 
  456: # JB, 9/24/2002: Any changes in this function may require a change
  457: # in lonnavmaps::resource::getDateStatus.
  458: sub check_access {
  459:     my ($id,$symb) = @_;
  460:     my $date ='';
  461:     my $status;
  462:     my $datemsg = '';
  463:     my $lastdate = '';
  464:     my $type;
  465:     my $passed;
  466: 
  467:     if ($env{'request.state'} eq "construct") {
  468: 	if ($env{'form.problemstate'}) {
  469: 	    if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
  470: 		if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' 
  471: 			&& &hide_problem_status())) {
  472: 		    return ('CANNOT_ANSWER',
  473: 			    &mt('is in this state due to author settings.'));
  474: 		}
  475: 	    } else {
  476: 		return ($env{'form.problemstate'},
  477: 			&mt('is in this state due to author settings.'));
  478: 	    }
  479: 	}
  480: 	&Apache::lonxml::debug("in construction ignoring dates");
  481: 	$status='CAN_ANSWER';
  482: 	$datemsg=&mt('is in under construction');
  483: #	return ($status,$datemsg);
  484:     }
  485: 
  486:     &Apache::lonxml::debug("checking for part :$id:");
  487:     &Apache::lonxml::debug("time:".time);
  488: 
  489:     unless ($symb) {
  490:         ($symb)=&Apache::lonnet::whichuser();
  491:     }
  492:     &Apache::lonxml::debug("symb:".$symb);
  493:     #if ($env{'request.state'} ne "construct" && $symb ne '') {
  494:     if ($env{'request.state'} ne "construct") {
  495:         my $idacc = &Apache::lonnet::EXT("resource.$id.acc",$symb);
  496: 	my $allowed=&Apache::loncommon::check_ip_acc($idacc);
  497: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
  498: 	    $status='INVALID_ACCESS';
  499: 	    $date=&mt("can not be accessed from your location.");
  500: 	    return($status,$date);
  501: 	}
  502: 	if ($env{'form.grade_imsexport'}) {
  503:             if (($env{'request.course.id'}) && 
  504:                 (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
  505:                 return ('SHOW_ANSWER');
  506:             }
  507:         }
  508: 	foreach my $temp ("opendate","duedate","answerdate") {
  509: 	    $lastdate = $date;
  510: 	    if ($temp eq 'duedate') {
  511: 		$date = &due_date($id,$symb);
  512: 	    } else {
  513: 		$date = &Apache::lonnet::EXT("resource.$id.$temp",$symb);
  514: 	    }
  515: 	    
  516: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type",$symb);
  517: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
  518: 		$date     =~ /^(con_lost|no_such_host)/) {
  519: 		$status='UNAVAILABLE';
  520: 		$date=&mt("may open later.");
  521: 		return($status,$date);
  522: 	    }
  523: 	    if ($thistype eq 'date_interval') {
  524: 		if ($temp eq 'opendate') {
  525: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)-$date;
  526: 		}
  527: 		if ($temp eq 'answerdate') {
  528: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)+$date;
  529: 		}
  530: 	    }
  531: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
  532: 	    if ($date eq '') {
  533: 		$date = &mt("an unknown date"); $passed = 0;
  534: 	    } elsif ($date eq 'con_lost') {
  535: 		$date = &mt("an indeterminate date"); $passed = 0;
  536: 	    } else {
  537: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
  538: 		$date = &Apache::lonlocal::locallocaltime($date);
  539: 	    }
  540: 	    if (!$passed) { $type=$temp; last; }
  541: 	}
  542: 	&Apache::lonxml::debug("have :$type:$passed:");
  543: 	if ($passed) {
  544: 	    $status='SHOW_ANSWER';
  545: 	    $datemsg=$date;
  546: 	} elsif ($type eq 'opendate') {
  547: 	    $status='CLOSED';
  548: 	    $datemsg = &mt('will open on [_1]',$date);
  549: 	} elsif ($type eq 'duedate') {
  550: 	    $status='CAN_ANSWER';
  551: 	    $datemsg = &mt('is due at [_1]',$date);
  552: 	} elsif ($type eq 'answerdate') {
  553: 	    $status='CLOSED';
  554: 	    $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
  555:                                $lastdate,$date);
  556: 	}
  557:     }
  558:     if ($status eq 'CAN_ANSWER' ||
  559: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
  560: 	#check #tries, and if correct.
  561: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
  562: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries",$symb);
  563: 	if ( $tries eq '' ) { $tries = '0'; }
  564: 	if ( $maxtries eq '' && 
  565: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
  566: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
  567: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
  568: 	if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
  569: 	      && (&show_problem_status()) ) {
  570:             if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
  571:                 (&Apache::lonnet::EXT("resource.$id.retrypartial",$symb) !~/^1|on|yes$/i)) {
  572: 	        $status = 'CANNOT_ANSWER';
  573:             }
  574:         } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
  575: 	    $status = 'CANNOT_ANSWER';
  576: 	}
  577: 	if ($status eq 'CANNOT_ANSWER'
  578: 	    && &show_answer_problem_status()) {
  579: 	    $status = 'SHOW_ANSWER';
  580: 	}
  581:     }
  582:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
  583: 	my @interval=&Apache::lonnet::EXT("resource.$id.interval",$symb);
  584: 	&Apache::lonxml::debug("looking for interval @interval");
  585: 	if ($interval[0]) {
  586: 	    my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
  587: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
  588: 	    if (!$first_access) {
  589: 		$status='NOT_YET_VIEWED';
  590: 		my $due_date = &due_date($id,$symb);
  591: 		my $seconds_left = $due_date - time;
  592: 		if ($seconds_left > $interval[0] || $due_date eq '') {
  593: 		    $seconds_left = $interval[0];
  594: 		}
  595: 		$datemsg=&seconds_to_human_length($seconds_left);
  596: 	    }
  597: 	}
  598:     }
  599: 
  600:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
  601:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
  602:   #    return ('UNCHECKEDOUT','needs to be checked out');
  603:   #}
  604: 
  605:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
  606:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
  607: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
  608: 	$status='CAN_ANSWER';
  609: 	$datemsg=&mt('is closed but you are allowed to view it');
  610:     }
  611: 
  612:     return ($status,$datemsg);
  613: }
  614: # this should work exactly like the copy in lonnavmaps.pm
  615: sub due_date {
  616:     my ($part_id,$symb,$udom,$uname)=@_;
  617:     my $date;
  618:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
  619: 				       $udom,$uname);
  620:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
  621:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
  622: 				       $udom,$uname);
  623:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
  624:     if ($interval[0] =~ /\d+/) {
  625: 	my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
  626: 	&Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
  627: 	if (defined($first_access)) {
  628: 	    my $interval = $first_access+$interval[0];
  629: 	    $date = (!$due_date || $interval < $due_date) ? $interval
  630:                                                           : $due_date;
  631: 	} else {
  632: 	    $date = $due_date;
  633: 	}
  634:     } else {
  635: 	$date = $due_date;
  636:     }
  637:     return $date;
  638: }
  639: 
  640: sub seconds_to_human_length {
  641:     my ($length)=@_;
  642: 
  643:     my $seconds=$length%60; $length=int($length/60);
  644:     my $minutes=$length%60; $length=int($length/60);
  645:     my $hours=$length%24;   $length=int($length/24);
  646:     my $days=$length;
  647: 
  648:     my $timestr;
  649:     if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
  650:     if ($hours > 0) { $timestr.=($timestr?", ":"").
  651: 			  &mt('[quant,_1,hour]',$hours); }
  652:     if ($minutes > 0) { $timestr.=($timestr?", ":"").
  653: 			    &mt('[quant,_1,minute]',$minutes); }
  654:     if ($seconds > 0) { $timestr.=($timestr?", ":"").
  655: 			    &mt('[quant,_1,second]',$seconds); }
  656:     return $timestr;
  657: }
  658: 
  659: sub showhash {
  660:     my (%hash) = @_;
  661:     &showhashsubset(\%hash,'.');
  662:     return '';
  663: }
  664: 
  665: sub showarray {
  666:     my ($array)=@_;
  667:     my $string="(";
  668:     foreach my $elm (@{ $array }) {
  669: 	if (ref($elm) eq 'ARRAY') {
  670: 	    $string.=&showarray($elm);
  671: 	} elsif (ref($elm) eq 'HASH') {
  672: 	    $string.= "HASH --- \n<br />";
  673: 	    $string.= &showhashsubset($elm,'.');
  674: 	} else {
  675: 	    $string.="$elm,"
  676: 	}
  677:     }
  678:     chop($string);
  679:     $string.=")";
  680:     return $string;
  681: }
  682: 
  683: sub showhashsubset {
  684:     my ($hash,$keyre) = @_;
  685:     my $resultkey;
  686:     foreach $resultkey (sort(keys(%$hash))) {
  687: 	if ($resultkey !~ /$keyre/) { next; }
  688: 	if (ref($$hash{$resultkey})  eq 'ARRAY' ) {
  689: 	    &Apache::lonxml::debug("$resultkey ---- ".
  690: 				   &showarray($$hash{$resultkey}));
  691: 	} elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
  692: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  693: 	    &showhashsubset($$hash{$resultkey},'.');
  694: 	} else {
  695: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  696: 	}
  697:     }
  698:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
  699:     return '';
  700: }
  701: 
  702: sub setuppermissions {
  703:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
  704:     unless ($Apache::lonhomework::browse eq 'F') {
  705:         $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'}); 
  706:     }
  707:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
  708:     if (! $viewgrades && 
  709: 	exists($env{'request.course.sec'}) && 
  710: 	$env{'request.course.sec'} !~ /^\s*$/) {
  711: 	$viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
  712:                                                '/'.$env{'request.course.sec'});
  713:     }
  714:     $Apache::lonhomework::viewgrades = $viewgrades;
  715: 
  716:     if ($Apache::lonhomework::browse eq 'F' && 
  717: 	$env{'form.devalidatecourseresdata'} eq 'on') {
  718: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
  719: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
  720: 					      $env{"course.$courseid.domain"});
  721:     }
  722: 
  723:     my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
  724:     if (! $modifygrades && 
  725: 	exists($env{'request.course.sec'}) && 
  726: 	$env{'request.course.sec'} !~ /^\s*$/) {
  727: 	$modifygrades = 
  728: 	    &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
  729: 				     '/'.$env{'request.course.sec'});
  730:     }
  731:     $Apache::lonhomework::modifygrades = $modifygrades;
  732: 
  733:     my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
  734:     if (! $queuegrade && 
  735: 	exists($env{'request.course.sec'}) && 
  736: 	$env{'request.course.sec'} !~ /^\s*$/) {
  737: 	$queuegrade = 
  738: 	    &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
  739: 				     '/'.$env{'request.course.sec'});
  740:     }
  741:     $Apache::lonhomework::queuegrade = $queuegrade;
  742:     return '';
  743: }
  744: 
  745: sub unset_permissions {
  746:     undef($Apache::lonhomework::queuegrade);
  747:     undef($Apache::lonhomework::modifygrades);
  748:     undef($Apache::lonhomework::viewgrades);
  749:     undef($Apache::lonhomework::browse);
  750: }
  751: 
  752: sub setupheader {
  753:     my $request=$_[0];
  754:     &Apache::loncommon::content_type($request,'text/html');
  755:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
  756: 	&Apache::loncommon::no_cache($request);
  757:     }
  758: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
  759: #							  'lastrevisiondate'));
  760:     $request->send_http_header;
  761:     return OK if $request->header_only;
  762:     return ''
  763: }
  764: 
  765: sub handle_save_or_undo {
  766:     my ($request,$problem,$result,$getobjref) = @_;
  767: 
  768:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
  769:     my $filebak =$file.".bak";
  770:     my $filetmp =$file.".tmp";
  771:     my $error=0;
  772:     if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
  773: 	my $error=0;
  774: 	if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
  775: 	if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
  776: 	if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
  777: 	if (!$error) {
  778: 	    &Apache::lonxml::info("<p><b>".
  779: 				  &mt("Undid changes, Switched [_1] and [_2]",
  780: 				      '<span class="LC_filename">'.$filebak.
  781: 				      '</span>',
  782: 				      '<span class="LC_filename">'.$file.
  783: 				      '</span>')."</b></p>");
  784: 	} else {
  785: 	    &Apache::lonxml::info("<p><span class=\"LC_error\">".
  786: 				  &mt("Unable to undo, unable to switch [_1] and [_2]",
  787: 				      '<span class="LC_filename">'.
  788: 				      $filebak.'</span>',
  789: 				      '<span class="LC_filename">'.
  790: 				      $file.'</span>')."</span></p>");
  791: 	    $error=1;
  792: 	}
  793:     } else {
  794:         &Apache::lonnet::correct_line_ends($result);
  795: 
  796: 	my $fs=Apache::File->new(">$filebak");
  797: 	if (defined($fs)) {
  798: 	    print $fs $$problem;
  799: 	} else {
  800: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
  801: 				  &mt("Unable to make backup [_1]",
  802: 				      '<span class="LC_filename">'.
  803: 				      $filebak.'</span>')."</span>");
  804: 	    $error=2;
  805: 	}
  806: 	my $fh=Apache::File->new(">$file");
  807: 	if (defined($fh)) {
  808: 	    print $fh $$result;
  809:             if (ref($getobjref) eq 'SCALAR') {
  810:                 if ($file =~ m{([^/]+)\.(html?)$}) {
  811:                     my $fname = $1;
  812:                     my $ext = $2;
  813:                     my $path = $file;
  814:                     $path =~ s/\Q$fname\E\.\Q$ext\E$//; 
  815:                     my (%allfiles,%codebase);
  816:                     &Apache::lonnet::extract_embedded_items($file,\%allfiles,
  817:                                                            \%codebase,$result);
  818:                     if (keys(%allfiles) > 0) {
  819:                         my $url = $request->uri;
  820:                         my $state = <<STATE;
  821:     <input type="hidden" name="action" value="upload_embedded" />
  822:     <input type="hidden" name="url" value="$url" />
  823: STATE
  824:                         $$getobjref = "<h3>".&mt("Reference Warning")."</h3>".
  825:                                       "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
  826:                                       "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
  827:                                       &Apache::loncommon::ask_for_embedded_content($url,$state,\%allfiles,\%codebase,
  828:                                       {'error_on_invalid_names'   => 1,
  829:                                        'ignore_remote_references' => 1,});
  830:                     }
  831:                 }
  832:             }
  833: 	} else {
  834: 	    &Apache::lonxml::info('<span class="LC_error">'.
  835: 				  &mt("Unable to write to [_1]",
  836: 				      '<span class="LC_filename">'.
  837: 				      $file.'</span>').
  838: 				  '</span>');
  839: 	    $error|=4;
  840: 	}
  841:     }
  842:     return $error;
  843: }
  844: 
  845: sub analyze_header {
  846:     my ($request) = @_;
  847:     my $js = &Apache::structuretags::setmode_javascript();
  848: 
  849:     # Breadcrumbs
  850:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
  851:                    'text' => 'Authoring Space'},
  852:                   {'href' => '',
  853:                    'text' => 'Problem Testing'},
  854:                   {'href' => '',
  855:                    'text' => 'Analyzing a problem'}];
  856: 
  857:     my $result =
  858:         &Apache::loncommon::start_page('Analyzing a problem',
  859:                                        $js,
  860:                                        {'bread_crumbs' => $brcrum,})
  861:        .&Apache::loncommon::head_subbox(
  862:                 &Apache::loncommon::CSTR_pageheader());
  863:     $result .= 
  864: 	&Apache::lonxml::message_location().'
  865:             <form name="lonhomework" method="post" action="'.
  866: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
  867:             '<input type="hidden" name="problemmode" value="'.
  868:             $env{'form.problemmode'}.'" />'.
  869: 	    &Apache::structuretags::remember_problem_state().'
  870:             <div class="LC_edit_problem_analyze_header">
  871:             <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
  872:             'onclick="javascript:setmode(this.form,'."'editxml'".')" />
  873:             <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
  874:             'onclick="javascript:setmode(this.form,'."'edit'".')" />
  875:             <hr />
  876:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
  877:             'onclick="javascript:setmode(this.form,'."'view'".')" />
  878:             <hr />
  879:             </div>
  880:             </form>';
  881:     &Apache::lonxml::add_messages(\$result);
  882:     $request->print($result);
  883:     $request->rflush();
  884: }
  885: 
  886: sub analyze_footer {
  887:     my ($request) = @_;
  888:     $request->print(&Apache::loncommon::end_page());
  889:     $request->rflush();
  890: }
  891: 
  892: sub analyze {
  893:     my ($request,$file) = @_;
  894:     &Apache::lonxml::debug("Analyze");
  895:     my $result;
  896:     my %overall;
  897:     my %seedexample;
  898:     my %allparts;
  899:     my $rndseed=$env{'form.rndseed'};
  900:     &analyze_header($request);
  901:     my %prog_state=
  902: 	&Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
  903:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
  904: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
  905: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
  906:         my $thisseed=$i+$rndseed;
  907: 	my $subresult=&Apache::lonnet::ssi($request->uri,
  908: 					   ('grade_target' => 'analyze'),
  909: 					   ('rndseed' => $thisseed));
  910: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
  911: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  912: 	my @parts;
  913:         if (ref($analyze{'parts'}) eq 'ARRAY') {
  914: 	    @parts=@{ $analyze{'parts'} };
  915: 	}
  916: 	foreach my $part (@parts) {
  917: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
  918: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
  919: 		$analyze{$part.'.type'} eq 'stringresponse'	||
  920: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
  921: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
  922: 		    my $i=0;
  923: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
  924: 			push( @{ $overall{$part.'.answer'}[$i] },
  925: 			      $answer_part);
  926: 			my $concatanswer= join("\0",@{ $answer_part });
  927: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
  928: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
  929: 			}
  930: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
  931: 			    $thisseed;
  932: 			$i++;
  933: 		    }
  934: 		}
  935: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
  936: 		    my $answer_part = 
  937: 			['<span class="LC_error">'.&mt('Error').'</span>'];
  938: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
  939: 			$thisseed;
  940: 		    push( @{ $overall{$part.'.answer'}[0] },
  941: 			  $answer_part);
  942: 		}
  943: 	    }
  944: 	}
  945:     }
  946:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
  947:     $request->print('<hr />'
  948:                    .'<h3>'
  949:                    .&mt('List of possible answers')
  950:                    .'</h3>'
  951:     );
  952:     foreach my $part (sort(keys(%allparts))) {
  953:         if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
  954:             (@{$overall{$part.'.answer'}} > 0)) {
  955: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
  956: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
  957:                 $request->print(&Apache::loncommon::start_data_table()
  958:                                .&Apache::loncommon::start_data_table_header_row()
  959:                                .'<th colspan="'.($num_cols+1).'">'
  960:                                .&mt('Part').' '.$part
  961:                 );
  962: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
  963: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
  964: 		}
  965: 		$request->print('</th>'
  966:                                .&Apache::loncommon::end_data_table_header_row()
  967:                 );
  968: 		my %frequency;
  969: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
  970: 		    $frequency{join("\0",@{ $answer })}++;
  971: 		}
  972:                 $request->print(&Apache::loncommon::start_data_table_header_row()
  973:                                .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
  974:                                .'<th>'.&mt('Frequency').'<br />'
  975:                                .'('.&mt('click for example').')</th>'
  976:                                .&Apache::loncommon::end_data_table_header_row()
  977:                 );
  978: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
  979:                     $request->print(&Apache::loncommon::start_data_table_row()
  980:                                    .'<td>'
  981:                                    .join('</td><td>',split("\0",$answer))
  982: 				   .'</td>'
  983:                                    .'<td>'
  984:                                    .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
  985: 				   .'</td>'
  986:                                    .&Apache::loncommon::end_data_table_row()
  987:                     );
  988: 		}
  989:                 $request->print(&Apache::loncommon::end_data_table());
  990: 	    }
  991: 	} else {
  992:             $request->print('<p class="LC_warning">'
  993:                            .&mt('Response [_1] is not analyzable at this time.',$part)
  994: 			   .'</p>'
  995:             );
  996: 	}
  997:     }
  998:     if (scalar(keys(%allparts)) == 0 ) {
  999:         $request->print('<p class="LC_warning">'
 1000:                        .&mt('Found no analyzable responses in this problem.'
 1001:                            .' Currently only Numerical, Formula and String response styles are supported.')
 1002:                        .'</p>'
 1003:         );
 1004:     }
 1005:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
 1006:     &analyze_footer($request);
 1007:     &Apache::lonhomework::showhash(%overall);
 1008:     return $result;
 1009: }
 1010: 
 1011: {
 1012:     my $show_problem_status;
 1013:     sub reset_show_problem_status {
 1014: 	undef($show_problem_status);
 1015:     }
 1016: 
 1017:     sub set_show_problem_status {
 1018: 	my ($new_status) = @_;
 1019: 	$show_problem_status = lc($new_status);
 1020:     }
 1021: 
 1022:     sub hide_problem_status {
 1023: 	return ($show_problem_status eq 'no'
 1024: 		|| $show_problem_status eq 'no_feedback_ever');
 1025:     }
 1026: 
 1027:     sub show_problem_status {
 1028: 	return ($show_problem_status eq 'yes'
 1029: 		|| $show_problem_status eq 'answer'
 1030: 		|| $show_problem_status eq '');
 1031:     }
 1032:     
 1033:     sub show_some_problem_status {
 1034: 	return ($show_problem_status eq 'no');
 1035:     }
 1036: 
 1037:     sub show_no_problem_status {
 1038: 	return ($show_problem_status eq 'no_feedback_ever');
 1039:     }
 1040:   
 1041:     sub show_answer_problem_status {
 1042: 	return ($show_problem_status eq 'answer');
 1043:     }
 1044: }
 1045: 
 1046: sub editxmlmode {
 1047:     my ($request,$file) = @_;
 1048:     my $result;
 1049:     my $problem=&Apache::lonnet::getfile($file);
 1050:     if ($problem eq -1) {
 1051: 	&Apache::lonxml::error(
 1052:             '<p class="LC_error">'
 1053:            .&mt('Unable to find [_1]',
 1054:                 '<span class="LC_filename">'.$file.'</span>')
 1055:            .'</p>');
 1056: 
 1057: 	$problem='';
 1058:     }
 1059: 
 1060:     if (($env{'form.problemmode'} eq 'saveeditxml') ||
 1061:         ($env{'form.problemmode'} eq 'saveviewxml') || 
 1062:         ($env{'form.problemmode'} eq 'undoxml')) {
 1063: 	my $error=&handle_save_or_undo($request,\$problem,
 1064: 				       \$env{'form.editxmltext'});
 1065: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
 1066:     }
 1067:     &Apache::lonhomework::showhashsubset(\%env,'^form');
 1068:     if ($env{'form.problemmode'} eq 'saveviewxml') {
 1069: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
 1070: 	$env{'form.problemmode'}='view';
 1071: 	&renderpage($request,$file);
 1072:     } else {
 1073: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
 1074: 	if ($cols > 80) { $cols = 80; }
 1075: 	if ($cols < 70) { $cols = 70; }
 1076: 	if ($rows < 20) { $rows = 20; }
 1077: 	my $js =
 1078: 	    &Apache::edit::js_change_detection(). 
 1079: 	    &Apache::loncommon::resize_textarea_js().
 1080:             &Apache::structuretags::setmode_javascript().
 1081:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
 1082: 
 1083:     # Breadcrumbs
 1084:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
 1085:                    'text' => 'Authoring Space'},
 1086:                   {'href' => '',
 1087:                    'text' => 'Problem Editing'}];
 1088: 
 1089: 	my $start_page = 
 1090: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
 1091: 					   {'no_auto_mt_title' => 1,
 1092: 					    'only_body'        => 0,
 1093: 					    'add_entries'      => {
 1094: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
 1095: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
 1096:                                                                   },
 1097:                                                 'bread_crumbs' => $brcrum,
 1098:                                              });
 1099: 
 1100:     $result=$start_page
 1101:            .&Apache::loncommon::head_subbox(
 1102:                 &Apache::loncommon::CSTR_pageheader());
 1103: 	$result.=&renderpage($request,$file,['no_output_web'],1).
 1104:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
 1105: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
 1106: 	    &Apache::structuretags::remember_problem_state().'
 1107:             <div class="LC_edit_problem_editxml_header">
 1108:               <table class="LC_edit_problem_header_title"><tr><td>
 1109:                <h2>'.&mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').'</h2>
 1110:                 </td><td align="right">
 1111:                   '.&Apache::loncommon::helpLatexCheatsheet('Problem_LON-CAPA_Functions','Script Functions').'
 1112:                 </td></tr>
 1113:               </table>';
 1114: 
 1115:          $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
 1116:                   &Apache::structuretags::problem_edit_buttons('editxml');
 1117:          
 1118:          $result.='<hr style="clear:both;" />'.&Apache::lonxml::message_location().'</div>'.  
 1119:                   '<textarea '.&Apache::edit::element_change_detection().
 1120: 	              ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" '.
 1121: 		      ' name="editxmltext" id="LC_editxmltext">'.
 1122: 		      &HTML::Entities::encode($problem,'<>&"').'</textarea>
 1123:             <div id="LC_aftertextarea">
 1124:             </div>
 1125:             </form>'.&Apache::loncommon::end_page();
 1126: 	&Apache::lonxml::add_messages(\$result);
 1127: 	$request->print($result);
 1128:     }
 1129:     return '';
 1130: }
 1131: 
 1132: #
 1133: #    Render the page in whatever target desired.
 1134: #
 1135: sub renderpage {
 1136:     my ($request,$file,$targets,$return_string) = @_;
 1137: 
 1138:     my @targets = @{$targets || [&get_target()]};
 1139:     &Apache::lonhomework::showhashsubset(\%env,'form.');
 1140:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
 1141: 
 1142:     my $overall_result;
 1143:     foreach my $target (@targets) {
 1144: 	# FIXME need to do something intelligent when a problem goes
 1145:         # from viewable to not viewable due to map conditions
 1146: 	#&setuppermissions();
 1147: 	#if (   $Apache::lonhomework::browse ne '2'
 1148: 	#    && $Apache::lonhomework::browse ne 'F' ) {
 1149: 	#    $request->print(" You most likely shouldn't see me.");
 1150: 	#}
 1151: 	#my $t0 = [&gettimeofday()];
 1152: 	my $output=1;
 1153: 	if ($target eq 'no_output_web') {
 1154: 	    $target = 'web'; $output=0;
 1155: 	}
 1156: 	my $problem=&Apache::lonnet::getfile($file);
 1157: 	my $result;
 1158: 	if ($problem eq -1) {
 1159: 	    $problem='';
 1160: 	    my $filename=(split('/',$file))[-1];
 1161: 	    my $error =
 1162:                 &mt('Unable to find [_1]',
 1163: 			   '<span class="LC_filename">'.$filename.'</span>');
 1164: 	    $result.=
 1165: 		&Apache::loncommon::simple_error_page($request,'Not available',
 1166: 						      $error,{'no_auto_mt_msg' => 1});
 1167: 	    return;
 1168: 	}
 1169: 
 1170: 	my %mystyle;
 1171: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
 1172: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
 1173: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
 1174: 
 1175: 	&Apache::lonxml::debug("Should be parsing now");
 1176: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
 1177: 					     &setup_vars($target),%mystyle);
 1178: 	&finished_parsing();
 1179: 	if (!$output) { $result = ''; }
 1180: 	#$request->print("Result follows:");
 1181: 	if ($target eq 'modified') {
 1182: 	    &handle_save_or_undo($request,\$problem,\$result);
 1183: 	} else {
 1184: 	    if ($target eq 'analyze') {
 1185: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
 1186: 		undef(%Apache::lonhomework::analyze);
 1187: 	    }
 1188: 	    #my $td=&tv_interval($t0);
 1189: 	    #if ( $Apache::lonxml::debug) {
 1190: 	    #$result =~ s:</body>::;
 1191: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
 1192: 	    #}
 1193: #	    $request->print($result);
 1194: 	    $overall_result.=$result;
 1195: #	    $request->rflush();
 1196: 	}
 1197: 	#$request->print(":Result ends");
 1198: 	#my $td=&tv_interval($t0);
 1199:     }
 1200:     if (!$return_string) {
 1201: 	&Apache::lonxml::add_messages(\$overall_result);
 1202: 	$request->print($overall_result);   
 1203: 	$request->rflush();   
 1204:     } else {
 1205: 	return $overall_result;
 1206:     }
 1207: }
 1208: 
 1209: sub finished_parsing {
 1210:     undef($Apache::lonhomework::parsing_a_problem);
 1211:     undef($Apache::lonhomework::parsing_a_task);
 1212: }
 1213: 
 1214: sub get_template_list {
 1215:     my ($extension) = @_;
 1216:     my $result;
 1217:     my @allnames;
 1218:     &Apache::lonxml::debug("Looking for :$extension:");
 1219:     my $glob_extension  = $extension;
 1220:     if ($extension eq 'survey' || $extension eq 'exam') {
 1221: 	$glob_extension = 'problem';
 1222:     }
 1223:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
 1224: 		     '/templates/*.'.$glob_extension);
 1225:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
 1226:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
 1227:                       &Apache::lonnet::metadata($_, 'help')]} (@files);
 1228:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
 1229:     my ($midpoint,$seconddiv,$numfiles);
 1230:     my @noexamplelink = ('blank.problem','blank.library','script.library');
 1231:     $numfiles = 0;
 1232:     foreach my $file (@files) {
 1233:         next if ($file->[1] !~ /\S/);
 1234:         $numfiles ++;
 1235:     }
 1236:     if ($numfiles > 0) {
 1237:         $result = '<div class="LC_left_float">';
 1238:         $midpoint = int($numfiles/2);
 1239:         if ($numfiles%2) {
 1240:             $midpoint ++;
 1241:         }
 1242:     }
 1243:     my $count = 0;
 1244:     my $currentcategory='';
 1245:     my $first = 1;
 1246:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1247:     foreach my $file (@files) {
 1248: 	next if ($file->[1] !~ /\S/);
 1249:         if ($file->[2] ne $currentcategory) {
 1250:            $currentcategory=$file->[2];
 1251:            if ((!$seconddiv) && ($count >= $midpoint)) {
 1252:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
 1253:                $seconddiv = 1;
 1254:            } elsif (!$first) {
 1255:                $result.='</div>'."\n";
 1256:            } else {
 1257:                $first = 0;
 1258:            }
 1259:            $result.= '<div class="LC_Box">'."\n"
 1260:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
 1261:            $count++;
 1262:         }
 1263: 	$result .=
 1264: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
 1265: 	    $file->[1].'</label>';
 1266:         if ($file->[3]) {
 1267:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
 1268:         }
 1269:         # Provide example link
 1270:         my $filename=$file->[0];
 1271:         $filename=~s{^\Q$londocroot\E}{};
 1272:         if (!(grep($filename =~ /\Q$_\E$/,@noexamplelink))) {
 1273:             $result .= ' <span class="LC_fontsize_small">'
 1274:                       .&Apache::loncommon::modal_link(
 1275:                            $filename.'?inhibitmenu=yes',&mt('Example'),600,420,'sample')
 1276:                       .'</span>';
 1277:         }
 1278:         $result .= '<br />'."\n";
 1279:         $count ++;
 1280:     }
 1281:     if ($numfiles > 0) {
 1282:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
 1283:     }
 1284:     return $result;
 1285: }
 1286: 
 1287: sub newproblem {
 1288:     my ($request) = @_;
 1289: 
 1290:     if ($env{'form.template'}) {
 1291: 	my $file = $env{'form.template'};
 1292: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1293: 	&File::Copy::copy($file,$dest);
 1294: 	&renderpage($request,$dest);
 1295: 	return;
 1296:     }
 1297: 
 1298:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
 1299:     &Apache::lonxml::debug("Looking for :$extension:");
 1300:     my $templatelist=&get_template_list($extension);
 1301:     if ($env{'form.newfile'} && !$templatelist) {
 1302: 	# no templates found
 1303: 	my $templatefilename =
 1304: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
 1305: 	&Apache::lonxml::debug("$templatefilename");
 1306: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1307: 	&File::Copy::copy($templatefilename,$dest);
 1308: 	&renderpage($request,$dest);
 1309:     } else {
 1310: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
 1311: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1312: 	my $errormsg;
 1313: 	my $instructions;
 1314:         my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
 1315:                        'text' => 'Authoring Space'},
 1316:                       {'href' => '',
 1317:                        'text' => "Create New $extension"}];
 1318: 	my $start_page = 
 1319:             &Apache::loncommon::start_page("Create New $extension",
 1320:                                            undef,
 1321:                                            {'bread_crumbs' => $brcrum,});
 1322: 	$request->print(
 1323:         $start_page
 1324:        .&Apache::loncommon::head_subbox(
 1325:                 &Apache::loncommon::CSTR_pageheader())
 1326:        .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
 1327: $errormsg
 1328: ".&mt("The requested file [_1] currently does not exist.",
 1329:       '<span class="LC_filename">'.$url.'</span>').'
 1330: <p class="LC_info">
 1331: '.&mt("To create a new $extension, select a template from the".
 1332:       " list below. Then click on the \"Create $extension\" button.").'
 1333: </p><div><form action="'.$url.'" method="post">');
 1334: 
 1335: 	if (defined($templatelist)) {
 1336: 	    $request->print($templatelist);
 1337: 	}
 1338: 	$request->print('<br /><input type="submit" name="newfile" value="'.
 1339: 			&mt("Create $extension").'" />');
 1340: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
 1341:     }
 1342:     return;
 1343: }
 1344: 
 1345: sub update_construct_style {
 1346:     if ($env{'request.state'} eq "construct"
 1347: 	&& $env{'form.problemmode'} eq 'view' 
 1348: 	&&  defined($env{'form.submitted'})
 1349: 	&& !defined($env{'form.resetdata'})
 1350: 	&& !defined($env{'form.newrandomization'})) {
 1351: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
 1352: 	    ||$env{'form.clear_style_file'}) {
 1353: 	    &Apache::lonnet::delenv('construct.style');
 1354: 	} elsif ($env{'form.style_file'} 
 1355: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
 1356: 	    &Apache::lonnet::appenv({'construct.style' => 
 1357: 				        $env{'form.style_file'}});
 1358: 	}
 1359:     }
 1360: }
 1361: 
 1362: 
 1363: sub handler {
 1364:     #my $t0 = [&gettimeofday()];
 1365:     my $request=$_[0];
 1366:     $Apache::lonxml::request=$request;
 1367:     $Apache::lonxml::debug=$env{'user.debug'};
 1368:     $env{'request.uri'}=$request->uri;
 1369:     &setuppermissions();
 1370: 
 1371:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1372: 
 1373:     #check if we know where we are
 1374:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread('','',1,1)) { 
 1375: 	# if we are browsing we might not be able to know where we are
 1376: 	if ($Apache::lonhomework::browse ne 'F' && 
 1377: 	    $env{'request.state'} ne "construct") {
 1378: 	    #should know where we are, so ask
 1379: 	    &unset_permissions();
 1380: 	    $request->internal_redirect('/adm/ambiguous');
 1381: 	    return OK;
 1382: 	}
 1383:     }
 1384:     if (&setupheader($request)) {
 1385: 	&unset_permissions();
 1386: 	return OK;
 1387:     }
 1388:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
 1389:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
 1390:     my ($symb) = &Apache::lonnet::whichuser();
 1391:     &Apache::lonxml::debug('symb is '.$symb);
 1392:     if ($env{'request.state'} eq "construct") {
 1393: 	if ( -e $file ) {
 1394: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1395: 						    ['problemmode']);
 1396: 	    if (!(defined $env{'form.problemmode'})) {
 1397: 		#first visit to problem in construction space
 1398: 		$env{'form.problemmode'}= 'view';
 1399: 		&renderpage($request,$file);
 1400: 	    } elsif (($env{'form.problemmode'} eq 'editxml') || 
 1401:                      ($env{'form.problemmode'} eq 'saveeditxml') ||
 1402:                      ($env{'form.problemmode'} eq 'saveviewxml') ||
 1403:                      ($env{'form.problemmode'} eq 'undoxml')) {
 1404: 		&editxmlmode($request,$file);
 1405: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
 1406: 		&analyze($request,$file);
 1407: 	    } else {
 1408: 		&update_construct_style();
 1409: 		&renderpage($request,$file);
 1410: 	    }
 1411: 	} else {
 1412: 	    # requested file doesn't exist in contruction space
 1413: 	    &newproblem($request);
 1414: 	}
 1415:     } else {
 1416: 	# just render the page normally outside of construction space
 1417: 	&Apache::lonxml::debug("not construct");
 1418: 	&renderpage($request,$file);
 1419:     }
 1420:     #my $td=&tv_interval($t0);
 1421:     #&Apache::lonxml::debug("Spent $td seconds processing");
 1422:     # always turn off debug messages
 1423:     $Apache::lonxml::debug=0;
 1424:     &unset_permissions();
 1425:     return OK;
 1426: 
 1427: }
 1428: 
 1429: 1;
 1430: __END__

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