Annotation of loncom/homework/lonhomework.pm, revision 1.233

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

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