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

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

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