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

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

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