File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.320: download - view: text, annotated - select for diffs
Sat Jul 10 13:51:05 2010 UTC (13 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate TeX errors when printing .page or .sequence with answers (or only answers) from Construction Space.

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

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