File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.276: download - view: text, annotated - select for diffs
Mon Oct 8 09:22:50 2007 UTC (16 years, 6 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
bz4074 - Use lonxml subs to maintain the number of bubble lines required
for responses to these types of problems.

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

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