File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.319: download - view: text, annotated - select for diffs
Tue Mar 16 19:55:37 2010 UTC (14 years, 1 month ago) by droeschl
Branches: MAIN
CVS tags: PRINT_INCOMPLETE_base, PRINT_INCOMPLETE, HEAD
In process of removing remote control, remote navmap and different icon modes code
- mostly remote navmap related code and files removed
- some minor refactoring
- some translations added/removed

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