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

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

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