File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.323: download - view: text, annotated - select for diffs
Sun Feb 6 18:43:10 2011 UTC (13 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #6425: make is so that pressing "Return" does not trigger an "Undo"

Also, try to disentangle the historically grown logic of this: form.problemmode now governs all behavior.

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

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