File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.268.2.2: download - view: text, annotated - select for diffs
Fri Sep 21 17:25:58 2007 UTC (17 years, 1 month ago) by albertel
Branches: version_2_5_X
CVS tags: version_2_5_2
Diff to branchpoint 1.268: preferred, unified
- backport 1.272

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

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