File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.322: download - view: text, annotated - select for diffs
Mon Nov 1 16:19:49 2010 UTC (13 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5497.

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

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