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

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

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