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

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