File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.302: download - view: text, annotated - select for diffs
Tue Feb 17 15:25:18 2009 UTC (15 years, 2 months ago) by jms
Branches: MAIN
CVS tags: HEAD
Removed extra line at 907 which was accidently put in by JMS on 2.13.2009

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

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