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

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

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