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

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

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