File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.266: download - view: text, annotated - select for diffs
Fri Apr 6 21:21:34 2007 UTC (17 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- css and translation changes

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

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