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

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

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